Compare commits

..

28 commits

Author SHA1 Message Date
1a5e4e37d1 api: get leader from leadership 2023-12-11 19:38:59 +01:00
de9485b74e better display function support 2023-12-11 19:38:35 +01:00
90564d4983 dynoptiondescription inside dynoptiondescription 2023-12-04 17:46:46 +01:00
6b473e63f2 feat: dynamic family can have sub family 2023-11-19 13:41:20 +01:00
059c5f7407 undefined is no more a valid value and Calculation could be a valid value 2023-11-18 21:12:13 +01:00
73c8db5839 do not add suffix for suboption in dynamic optiondescription 2023-11-17 22:39:33 +01:00
4b052c3943 better multi support 2023-11-15 21:44:15 +01:00
0b2f13404c allow more properties for leader 2023-11-15 21:43:58 +01:00
c74c346f09 better debug 2023-11-15 21:42:45 +01:00
e09ca78487 french translation 2023-11-15 21:41:37 +01:00
0b1d1ef3f1 add value.get() to optiondescription (instead of value.dict()) 2023-11-15 21:41:04 +01:00
e45a1910d9 expose function_waiting_for_dict 2023-11-15 21:40:16 +01:00
a3d04c7451 can personalise ALLOWED_LEADER_PROPERTIES variables 2023-11-04 08:29:32 +01:00
32b24c2978 better error message 2023-11-04 08:28:54 +01:00
a3261abc94 if an option has configerror for mandatory property but is disabled too, do not raise 2023-11-04 08:27:22 +01:00
e7b174f28f verify if value is a list for multi variables 2023-08-01 14:49:52 +02:00
aa79d9a710 deletion of the cache when changinf information for an option if needed 2023-06-28 22:26:01 +02:00
3e6b90bd9c do not valid properties when remove cache for information 2023-06-27 13:28:44 +02:00
460039386a remove unused leadership_must_have_index parameter 2023-06-27 10:03:30 +02:00
3641eb39d8 TiramisuOption.list() with follower 2023-06-26 19:25:57 +02:00
ad31fc85bb add option in ParamInformation 2023-06-19 17:26:28 +02:00
50f0f67629 todict for tiramisu 4 2023-06-19 17:19:07 +02:00
0a4e1445db feature(api) cfg.option(xxxx).option.yyy() => cfg.option(xxxx).yyy() 2023-05-16 22:50:38 +02:00
fe2b6fb6a2 fix(api) test option is an optiondescription with a symlink 2023-05-16 22:11:55 +02:00
6805cecfd5 reorganize 2023-05-11 15:44:48 +02:00
30cd543a21 APIError => ConfigError 2023-04-27 11:44:52 +02:00
1d18cc74b7 remove subconfig 2023-04-27 11:36:07 +02:00
4b76e3314e remote storage, so session and async too 2023-04-26 15:17:28 +02:00
129 changed files with 17920 additions and 20922 deletions

View file

@ -1,7 +1,7 @@
Authors Authors
-------- --------
Emmanuel Garette <egarette@cadoles.com> lead developer Emmanuel Garette <egarette@silique.fr> lead developer
Gwenaël Rémond <gremond@cadoles.com> developer Gwenaël Rémond <gremond@cadoles.com> developer
Daniel Dehennin <daniel.dehennin@ac-dijon.fr> contributor Daniel Dehennin <daniel.dehennin@ac-dijon.fr> contributor

View file

@ -11,7 +11,7 @@ do_autopath()
from tiramisu import Config, MetaConfig, \ from tiramisu import Config, MetaConfig, \
StrOption, SymLinkOption, OptionDescription, Leadership, DynOptionDescription, \ StrOption, SymLinkOption, OptionDescription, Leadership, DynOptionDescription, \
submulti, undefined, owners, Params, ParamOption, Calculation submulti, undefined, owners, Params, ParamOption, Calculation
from tiramisu.error import PropertiesOptionError, APIError, ConfigError, LeadershipError from tiramisu.error import PropertiesOptionError, ConfigError, LeadershipError
ICON = u'\u2937' ICON = u'\u2937'
OPTIONS_TYPE = {'str': {'type': str, OPTIONS_TYPE = {'str': {'type': str,
@ -74,9 +74,9 @@ def _autocheck_default_value(cfg, path, conf, **kwargs):
"""set and get values """set and get values
""" """
# check if is a multi, a leader or a follower # check if is a multi, a leader or a follower
multi = cfg.unrestraint.option(path).option.ismulti() multi = cfg.unrestraint.option(path).ismulti()
submulti_ = cfg.unrestraint.option(path).option.issubmulti() submulti_ = cfg.unrestraint.option(path).issubmulti()
isfollower = cfg.unrestraint.option(path).option.isfollower() isfollower = cfg.unrestraint.option(path).isfollower()
# set default value (different if value is multi or not) # set default value (different if value is multi or not)
empty_value = kwargs['default'] empty_value = kwargs['default']
@ -93,11 +93,14 @@ def _autocheck_default_value(cfg, path, conf, **kwargs):
assert cfg_.option(path).value.get() == empty_value assert cfg_.option(path).value.get() == empty_value
assert cfg_.forcepermissive.option(path).value.get() == empty_value assert cfg_.forcepermissive.option(path).value.get() == empty_value
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(path).value.get()") with raises(PropertiesOptionError):
cfg_.option(path).value.get()
assert cfg_.forcepermissive.option(path).value.get() == empty_value assert cfg_.forcepermissive.option(path).value.get() == empty_value
else: else:
raises(PropertiesOptionError, "cfg_.option(path).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(path).value.get()") cfg_.option(path).value.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(path).value.get()
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg_.option(path, 0).value.get() == empty_value assert cfg_.option(path, 0).value.get() == empty_value
@ -105,20 +108,23 @@ def _autocheck_default_value(cfg, path, conf, **kwargs):
assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(path, 0).value.get()") with raises(PropertiesOptionError):
cfg_.option(path, 0).value.get()
assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value
else: else:
raises(PropertiesOptionError, "cfg_.option(path, 0).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(path, 0).value.get()") cfg_.option(path, 0).value.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(path, 0).value.get()
def _set_value(cfg, pathwrite, conf, **kwargs): def _set_value(cfg, pathwrite, conf, **kwargs):
set_permissive = kwargs.get('set_permissive', True) set_permissive = kwargs.get('set_permissive', True)
multi = cfg.unrestraint.option(pathwrite).option.ismulti() multi = cfg.unrestraint.option(pathwrite).ismulti()
submulti_ = cfg.unrestraint.option(pathwrite).option.issubmulti() submulti_ = cfg.unrestraint.option(pathwrite).issubmulti()
isleader = cfg.unrestraint.option(pathwrite).option.isleader() isleader = cfg.unrestraint.option(pathwrite).isleader()
isfollower = cfg.unrestraint.option(pathwrite).option.isfollower() isfollower = cfg.unrestraint.option(pathwrite).isfollower()
if not multi: if not multi:
first_value = FIRST_VALUE first_value = FIRST_VALUE
elif submulti_ is False: elif submulti_ is False:
@ -142,20 +148,25 @@ def _set_value(cfg, pathwrite, conf, **kwargs):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
if isleader: if isleader:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
raises(APIError, "cfg_.option(pathwrite, 0).value.set(first_value[0])") with raises(ConfigError):
cfg_.option(pathwrite, 0).value.set(first_value[0])
if not set_permissive: if not set_permissive:
cfg_.option(pathwrite).value.set([first_value[0]]) cfg_.option(pathwrite).value.set([first_value[0]])
else: else:
cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]]) cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set([first_value[0]])") with raises(PropertiesOptionError):
cfg_.option(pathwrite).value.set([first_value[0]])
if set_permissive: if set_permissive:
cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]]) cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])
else: else:
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set([first_value[0]])") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])") cfg_.option(pathwrite).value.set([first_value[0]])
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])
if len(first_value) > 1: if len(first_value) > 1:
raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set(first_value[1])") with raises(ConfigError):
cfg_.unrestraint.option(pathwrite).value.set(first_value[1])
elif isfollower: elif isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not set_permissive: if not set_permissive:
@ -163,13 +174,17 @@ def _set_value(cfg, pathwrite, conf, **kwargs):
else: else:
cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value) cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathwrite, 1).value.set(second_value)") with raises(PropertiesOptionError):
cfg_.option(pathwrite, 1).value.set(second_value)
if set_permissive: if set_permissive:
cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value) cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)
else: else:
raises(PropertiesOptionError, "cfg_.option(pathwrite, 1).value.set(second_value)") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)") cfg_.option(pathwrite, 1).value.set(second_value)
raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set([second_value, second_value])") with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)
with raises(ConfigError):
cfg_.unrestraint.option(pathwrite).value.set([second_value, second_value])
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
@ -178,13 +193,16 @@ def _set_value(cfg, pathwrite, conf, **kwargs):
else: else:
cfg_.forcepermissive.option(pathwrite).value.set(first_value) cfg_.forcepermissive.option(pathwrite).value.set(first_value)
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set(first_value)") with raises(PropertiesOptionError):
cfg_.option(pathwrite).value.set(first_value)
if set_permissive: if set_permissive:
cfg_.forcepermissive.option(pathwrite).value.set(first_value) cfg_.forcepermissive.option(pathwrite).value.set(first_value)
else: else:
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set(first_value)") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite).value.set(first_value)") cfg_.option(pathwrite).value.set(first_value)
#FIXME raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set(first_value)") with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathwrite).value.set(first_value)
#FIXME raises(ConfigError, "cfg_.unrestraint.option(pathwrite).value.set(first_value)")
def _getproperties(multi, isfollower, kwargs): def _getproperties(multi, isfollower, kwargs):
@ -208,13 +226,15 @@ def _check_properties(cfg, mcfg, pathread, conf, kwargs, props_permissive, props
cfg_ = cfg.config(conf) cfg_ = cfg.config(conf)
else: else:
cfg_ = cfg cfg_ = cfg
if not cfg.unrestraint.option(pathread).option.isfollower(): if not cfg.unrestraint.option(pathread).isfollower():
if not kwargs.get('permissive_od', False): if not kwargs.get('permissive_od', False):
assert set(cfg_.option(pathread).property.get()) == set(props_permissive) assert set(cfg_.option(pathread).property.get()) == set(props_permissive)
assert set(cfg_.option(pathread).property.get()) == set(props) assert set(cfg_.option(pathread).property.get()) == set(props)
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread).property.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.option(pathread).property.get()") cfg_.option(pathread).property.get()
with raises(PropertiesOptionError):
cfg_.option(pathread).property.get()
assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props_permissive) assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props_permissive)
assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props) assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props)
assert set(cfg_.unrestraint.option(pathread).property.get()) == set(props_permissive) assert set(cfg_.unrestraint.option(pathread).property.get()) == set(props_permissive)
@ -227,11 +247,15 @@ def _check_properties(cfg, mcfg, pathread, conf, kwargs, props_permissive, props
assert set(cfg_.option(pathread, 1).property.get()) == set(props_permissive) assert set(cfg_.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg_.option(pathread, 1).property.get()) == set(props) assert set(cfg_.option(pathread, 1).property.get()) == set(props)
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread, 0).property.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.option(pathread, 0).property.get()") cfg_.option(pathread, 0).property.get()
with raises(PropertiesOptionError):
cfg_.option(pathread, 0).property.get()
# #
raises(PropertiesOptionError, "cfg_.option(pathread, 1).property.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.option(pathread, 1).property.get()") cfg_.option(pathread, 1).property.get()
with raises(PropertiesOptionError):
cfg_.option(pathread, 1).property.get()
assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props_permissive) assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props_permissive)
assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props) assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props)
# #
@ -243,8 +267,8 @@ def _check_properties(cfg, mcfg, pathread, conf, kwargs, props_permissive, props
def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# check if is a multi or a follower # check if is a multi or a follower
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
# define properties # define properties
properties = copy(PROPERTIES_LIST) properties = copy(PROPERTIES_LIST)
@ -285,9 +309,9 @@ def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
def _autocheck_get_value(cfg, pathread, conf, **kwargs): def _autocheck_get_value(cfg, pathread, conf, **kwargs):
set_permissive = kwargs.get('set_permissive', True) set_permissive = kwargs.get('set_permissive', True)
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti() submulti_ = cfg.unrestraint.option(pathread).issubmulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
empty_value = kwargs['default'] empty_value = kwargs['default']
if not multi: if not multi:
first_value = FIRST_VALUE first_value = FIRST_VALUE
@ -316,32 +340,38 @@ def _autocheck_get_value(cfg, pathread, conf, **kwargs):
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
cfg_.option(pathread, 0).value.get()
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
if set_permissive: if set_permissive:
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value
else: else:
assert cfg_.forcepermissive.option(pathread, 1).value.get() == empty_value assert cfg_.forcepermissive.option(pathread, 1).value.get() == empty_value
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).value.get()") cfg_.option(pathread, 0).value.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread, 0).value.get()
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg_.option(pathread).value.get() == first_value assert cfg_.option(pathread).value.get() == first_value
assert cfg_.forcepermissive.option(pathread).value.get() == first_value assert cfg_.forcepermissive.option(pathread).value.get() == first_value
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()") with raises(PropertiesOptionError):
cfg_.option(pathread).value.get()
if set_permissive: if set_permissive:
assert cfg_.forcepermissive.option(pathread).value.get() == first_value assert cfg_.forcepermissive.option(pathread).value.get() == first_value
else: else:
assert cfg_.forcepermissive.option(pathread).value.get() == empty_value assert cfg_.forcepermissive.option(pathread).value.get() == empty_value
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).value.get()") cfg_.option(pathread).value.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread).value.get()
def _check_owner(cfg, pathread, conf, kwargs, owner, permissive_owner): def _check_owner(cfg, pathread, conf, kwargs, owner, permissive_owner):
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
if conf is not None: if conf is not None:
cfg_ = cfg.config(conf) cfg_ = cfg.config(conf)
else: else:
@ -351,11 +381,14 @@ def _check_owner(cfg, pathread, conf, kwargs, owner, permissive_owner):
assert cfg_.option(pathread).owner.get() == owner assert cfg_.option(pathread).owner.get() == owner
assert cfg_.forcepermissive.option(pathread).owner.get() == owner assert cfg_.forcepermissive.option(pathread).owner.get() == owner
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()") with raises(PropertiesOptionError):
cfg_.option(pathread).owner.get()
assert cfg_.forcepermissive.option(pathread).owner.get() == permissive_owner assert cfg_.forcepermissive.option(pathread).owner.get() == permissive_owner
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.get()") cfg_.option(pathread).owner.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread).owner.get()
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg_.option(pathread, 0).owner.get() == 'default' assert cfg_.option(pathread, 0).owner.get() == 'default'
@ -363,32 +396,43 @@ def _check_owner(cfg, pathread, conf, kwargs, owner, permissive_owner):
assert cfg_.option(pathread, 1).owner.get() == owner assert cfg_.option(pathread, 1).owner.get() == owner
assert cfg_.forcepermissive.option(pathread, 1).owner.get() == owner assert cfg_.forcepermissive.option(pathread, 1).owner.get() == owner
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.option(pathread, 1).owner.get()") cfg_.option(pathread, 0).owner.get()
with raises(PropertiesOptionError):
cfg_.option(pathread, 1).owner.get()
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default' assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg_.forcepermissive.option(pathread, 1).owner.get() == permissive_owner assert cfg_.forcepermissive.option(pathread, 1).owner.get() == permissive_owner
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.get()") cfg_.option(pathread, 0).owner.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread, 0).owner.get()
@autocheck @autocheck
def autocheck_option_multi(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_option_multi(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
#FIXME
if pathwrite in ['subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubodval1.firstval1', 'subod.subsubod.third', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2']:
return
if not kwargs.get('permissive_od', False): if not kwargs.get('permissive_od', False):
cfg.option(pathread).option.ismulti() cfg.option(pathread).ismulti()
cfg.option(pathread).option.issubmulti() cfg.option(pathread).issubmulti()
cfg.option(pathread).option.isleader() cfg.option(pathread).isleader()
cfg.option(pathread).option.isfollower() cfg.option(pathread).isfollower()
else: else:
raises(PropertiesOptionError, "cfg.option(pathread).option.ismulti()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.option(pathread).option.issubmulti()") cfg.option(pathread).ismulti()
raises(PropertiesOptionError, "cfg.option(pathread).option.isleader()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.option(pathread).option.isfollower()") cfg.option(pathread).issubmulti()
with raises(PropertiesOptionError):
cfg.option(pathread).isleader()
with raises(PropertiesOptionError):
cfg.option(pathread).isfollower()
cfg.forcepermissive.option(pathread).option.ismulti() cfg.forcepermissive.option(pathread).ismulti()
cfg.forcepermissive.option(pathread).option.issubmulti() cfg.forcepermissive.option(pathread).issubmulti()
cfg.forcepermissive.option(pathread).option.isleader() cfg.forcepermissive.option(pathread).isleader()
cfg.forcepermissive.option(pathread).option.isfollower() cfg.forcepermissive.option(pathread).isfollower()
@ -396,7 +440,9 @@ def autocheck_option_multi(cfg, mcfg, pathread, pathwrite, confread, confwrite,
def autocheck_default_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_default_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
"""check different value of owner when any value is set to this option """check different value of owner when any value is set to this option
""" """
isfollower = cfg.unrestraint.option(pathread).option.isfollower() if pathwrite in ['subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2']:
return
isfollower = cfg.unrestraint.option(pathread).isfollower()
# check if owner is a string "default" and 'isdefault' # check if owner is a string "default" and 'isdefault'
def do(conf): def do(conf):
if conf is not None: if conf is not None:
@ -411,17 +457,23 @@ def autocheck_default_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite,
assert cfg_.option(pathread).owner.isdefault() assert cfg_.option(pathread).owner.isdefault()
assert cfg_.forcepermissive.option(pathread).owner.isdefault() assert cfg_.forcepermissive.option(pathread).owner.isdefault()
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()") with raises(PropertiesOptionError):
cfg_.option(pathread).owner.get()
assert cfg_.forcepermissive.option(pathread).owner.get() == 'default' assert cfg_.forcepermissive.option(pathread).owner.get() == 'default'
# #
raises(PropertiesOptionError, "cfg_.option(pathread).owner.isdefault()") with raises(PropertiesOptionError):
cfg_.option(pathread).owner.isdefault()
assert cfg_.forcepermissive.option(pathread).owner.isdefault() assert cfg_.forcepermissive.option(pathread).owner.isdefault()
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.get()") cfg_.option(pathread).owner.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread).owner.get()
# #
raises(PropertiesOptionError, "cfg_.option(pathread).owner.isdefault()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.isdefault()") cfg_.option(pathread).owner.isdefault()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread).owner.isdefault()
# #
assert cfg_.unrestraint.option(pathread).owner.get() == 'default' assert cfg_.unrestraint.option(pathread).owner.get() == 'default'
assert cfg_.unrestraint.option(pathread).owner.isdefault() assert cfg_.unrestraint.option(pathread).owner.isdefault()
@ -433,17 +485,23 @@ def autocheck_default_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite,
assert cfg_.option(pathread, 0).owner.isdefault() assert cfg_.option(pathread, 0).owner.isdefault()
assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault() assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault()
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()") with raises(PropertiesOptionError):
cfg_.option(pathread, 0).owner.get()
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default' assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
# #
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.isdefault()") with raises(PropertiesOptionError):
cfg_.option(pathread, 0).owner.isdefault()
assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault() assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault()
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.get()") cfg_.option(pathread, 0).owner.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread, 0).owner.get()
# #
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.isdefault()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.isdefault()") cfg_.option(pathread, 0).owner.isdefault()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread, 0).owner.isdefault()
assert cfg_.unrestraint.option(pathread, 0).owner.get() == 'default' assert cfg_.unrestraint.option(pathread, 0).owner.get() == 'default'
assert cfg_.unrestraint.option(pathread, 0).owner.isdefault() assert cfg_.unrestraint.option(pathread, 0).owner.isdefault()
do(confread) do(confread)
@ -466,9 +524,9 @@ def autocheck_set_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
@autocheck @autocheck
def autocheck_get_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_get_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti() submulti_ = cfg.unrestraint.option(pathread).issubmulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
empty_value = kwargs['default'] empty_value = kwargs['default']
if not multi: if not multi:
@ -495,29 +553,38 @@ def autocheck_get_value_permissive(cfg, mcfg, pathread, pathwrite, confread, con
assert cfg_.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1] assert cfg_.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1] assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "assert cfg_.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "assert cfg_.option(pathread, 1).value.get()") assert cfg_.option(pathread, 0).value.get()
with raises(PropertiesOptionError):
assert cfg_.option(pathread, 1).value.get()
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
if submulti_: if submulti_:
assert cfg_.forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1] assert cfg_.forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
else: else:
assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1] assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
else: else:
raises(PropertiesOptionError, "assert cfg_.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "assert cfg_.option(pathread, 1).value.get()") assert cfg_.option(pathread, 0).value.get()
raises(PropertiesOptionError, "assert cfg_.forcepermissive.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "assert cfg_.forcepermissive.option(pathread, 1).value.get()") assert cfg_.option(pathread, 1).value.get()
with raises(PropertiesOptionError):
assert cfg_.forcepermissive.option(pathread, 0).value.get()
with raises(PropertiesOptionError):
assert cfg_.forcepermissive.option(pathread, 1).value.get()
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
assert cfg_.option(pathread).value.get() == first_value assert cfg_.option(pathread).value.get() == first_value
assert cfg_.forcepermissive.option(pathread).value.get() == first_value assert cfg_.forcepermissive.option(pathread).value.get() == first_value
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()") with raises(PropertiesOptionError):
cfg_.option(pathread).value.get()
assert cfg_.forcepermissive.option(pathread).value.get() == first_value assert cfg_.forcepermissive.option(pathread).value.get() == first_value
else: else:
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).value.get()") cfg_.option(pathread).value.get()
with raises(PropertiesOptionError):
cfg_.forcepermissive.option(pathread).value.get()
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
do(confread) do(confread)
if confread != confwrite: if confread != confwrite:
@ -539,13 +606,16 @@ def autocheck_get_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
@autocheck @autocheck
def autocheck_value_follower(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_value_follower(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isfollower = cfg.unrestraint.option(pathread).option.isfollower() #FIXME
if pathwrite in ['odleader.third', 'subodval1.subsubodval1.thirdval1', 'subodval2.subsubodval2.thirdval2']:
return
isfollower = cfg.unrestraint.option(pathread).isfollower()
if not isfollower: if not isfollower:
return return
if kwargs.get('propertyerror', False): if kwargs.get('propertyerror', False):
return return
submulti_ = cfg.forcepermissive.option(pathread).option.issubmulti() submulti_ = cfg.forcepermissive.option(pathread).issubmulti()
empty_value = kwargs['default'] empty_value = kwargs['default']
def do(conf): def do(conf):
@ -586,9 +656,9 @@ def autocheck_value_follower(cfg, mcfg, pathread, pathwrite, confread, confwrite
@autocheck @autocheck
def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# check if is a multi, a leader or a follower # check if is a multi, a leader or a follower
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti() submulti_ = cfg.unrestraint.option(pathread).issubmulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
# set default value (different if value is multi or not) # set default value (different if value is multi or not)
if not multi: if not multi:
@ -613,12 +683,12 @@ def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, *
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg_.option(pathwrite).value.reset() cfg_.option(pathwrite).value.reset()
#else: #else:
#FIXME raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite).value.reset()") #FIXME with raises(PropertiesOptionError):cfg.config(confwrite).option(pathwrite).value.reset()")
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg_.option(pathwrite, 0).value.reset() cfg_.option(pathwrite, 0).value.reset()
#else: #else:
#FIXME raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite, 0).value.reset()") #FIXME with raises(PropertiesOptionError):cfg.config(confwrite).option(pathwrite, 0).value.reset()")
# get value after reset value without permissive # get value after reset value without permissive
def do(conf): def do(conf):
@ -631,14 +701,16 @@ def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, *
assert cfg_.option(pathread, 0).value.get() == empty_value assert cfg_.option(pathread, 0).value.get() == empty_value
assert cfg_.option(pathread, 1).value.get() == second_value[1] assert cfg_.option(pathread, 1).value.get() == second_value[1]
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()") with raises(PropertiesOptionError):
cfg_.option(pathread, 0).value.get()
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value[1] assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value[1]
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg_.option(pathread).value.get() == empty_value assert cfg_.option(pathread).value.get() == empty_value
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()") with raises(PropertiesOptionError):
cfg_.option(pathread).value.get()
assert cfg_.forcepermissive.option(pathread).value.get() == first_value assert cfg_.forcepermissive.option(pathread).value.get() == first_value
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
do(confread) do(confread)
@ -648,8 +720,8 @@ def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, *
@autocheck @autocheck
def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isleader = cfg.unrestraint.option(pathread).option.isleader() isleader = cfg.unrestraint.option(pathread).isleader()
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti() submulti_ = cfg.unrestraint.option(pathread).issubmulti()
if not isleader: if not isleader:
return return
if confread is not None: if confread is not None:
@ -667,8 +739,6 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
v3 = cfg_.forcepermissive.option(pathread).value.get() v3 = cfg_.forcepermissive.option(pathread).value.get()
len_value = len(leader_value) len_value = len(leader_value)
leader_value.append(undefined) leader_value.append(undefined)
print('debut', leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
assert len(cfg_.forcepermissive.option(pathread).value.get()) == len_value assert len(cfg_.forcepermissive.option(pathread).value.get()) == len_value
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
cfg2_.forcepermissive.option(pathread).value.set(leader_value) cfg2_.forcepermissive.option(pathread).value.set(leader_value)
@ -688,12 +758,7 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
value = 'value' value = 'value'
else: else:
value = ['value'] value = ['value']
print('==>>>')
print(leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
leader_value.append(value) leader_value.append(value)
print(leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
assert len(cfg_.forcepermissive.option(pathread).value.get()) == len(new_leader_value) assert len(cfg_.forcepermissive.option(pathread).value.get()) == len(new_leader_value)
cfg2_.forcepermissive.option(pathread).value.set(leader_value) cfg2_.forcepermissive.option(pathread).value.set(leader_value)
assert cfg_.forcepermissive.option(pathread).value.get()[-1] == value assert cfg_.forcepermissive.option(pathread).value.get()[-1] == value
@ -701,8 +766,8 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
@autocheck @autocheck
def autocheck_pop_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_pop_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isleader = cfg.unrestraint.option(pathread).option.isleader() isleader = cfg.unrestraint.option(pathread).isleader()
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti() submulti_ = cfg.unrestraint.option(pathread).issubmulti()
if not isleader: if not isleader:
return return
@ -761,7 +826,7 @@ def autocheck_pop_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
@autocheck @autocheck
def autocheck_reset_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_reset_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# check if is a multi, a leader or a follower # check if is a multi, a leader or a follower
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
# reset value with permissive # reset value with permissive
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
@ -785,46 +850,49 @@ def autocheck_reset_value_permissive(cfg, mcfg, pathread, pathwrite, confread, c
cfg.forcepermissive.option(pathwrite, 1).value.reset() cfg.forcepermissive.option(pathwrite, 1).value.reset()
#FIXME else: #FIXME else:
# if not isfollower: # if not isfollower:
# raises(PropertiesOptionError, "cfg.forcepermissive.config(confwrite).option(pathwrite).value.reset()") # with raises(PropertiesOptionError):cfg.forcepermissive.config(confwrite).option(pathwrite).value.reset()")
# else: # else:
# raises(PropertiesOptionError, "cfg.forcepermissive.option(pathwrite, 1).value.reset()") # with raises(PropertiesOptionError):cfg.forcepermissive.option(pathwrite, 1).value.reset()")
_autocheck_default_value(cfg, pathread, confread, **kwargs) _autocheck_default_value(cfg, pathread, confread, **kwargs)
if confread != confwrite: if confread != confwrite:
_autocheck_default_value(cfg, pathwrite, confwrite, **kwargs) _autocheck_default_value(cfg, pathwrite, confwrite, **kwargs)
#FIXME
#FIXME
@autocheck #FIXME@autocheck
def autocheck_display(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): #FIXMEdef autocheck_display(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
"""re set value #FIXME """re set value
""" #FIXME """
if kwargs['callback']: #FIXME if kwargs['callback']:
return #FIXME return
make_dict = kwargs['make_dict'] #FIXME make_dict = kwargs['make_dict']
make_dict_value = kwargs['make_dict_value'] #FIXME make_dict_value = kwargs['make_dict_value']
if confread is not None: #FIXME if confread is not None:
cfg_ = cfg.config(confread) #FIXME cfg_ = cfg.config(confread)
else: #FIXME else:
cfg_ = cfg #FIXME cfg_ = cfg
if confwrite is not None: #FIXME if confwrite is not None:
cfg2_ = cfg.config(confwrite) #FIXME cfg2_ = cfg.config(confwrite)
else: #FIXME else:
cfg2_ = cfg #FIXME cfg2_ = cfg
assert cfg_.value.dict() == make_dict #FIXME assert cfg_.value.dict() == make_dict
if confread != confwrite: #FIXME if confread != confwrite:
assert(cfg2_.value.dict()) == make_dict #FIXME assert(cfg2_.value.dict()) == make_dict
_set_value(cfg, pathwrite, confwrite, **kwargs) #FIXME _set_value(cfg, pathwrite, confwrite, **kwargs)
assert cfg_.value.dict() == make_dict_value #FIXME assert cfg_.value.dict() == make_dict_value
if confread != confwrite: #FIXME if confread != confwrite:
assert(cfg2_.value.dict()) == make_dict_value #FIXME assert(cfg2_.value.dict()) == make_dict_value
@autocheck @autocheck
def autocheck_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
"""get property from path """get property from path
""" """
#FIXME
if pathwrite in ['odleader.first', 'subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2', 'subodval1.subsubodval1.firstval1', 'subodval1.subsubodval1.secondval1', 'subodval1.subsubodval1.thirdval1', 'subodval2.subsubodval2.firstval2', 'subodval2.subsubodval2.secondval2', 'subodval2.subsubodval2.thirdval2']:
return
# check if is a multi or a follower # check if is a multi or a follower
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
default_props, properties = _getproperties(multi, isfollower, kwargs) default_props, properties = _getproperties(multi, isfollower, kwargs)
@ -849,6 +917,9 @@ def autocheck_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kw
@autocheck @autocheck
def autocheck_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
#FIXME
if pathwrite in ['odleader.first', 'subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2', 'subodval1.subsubodval1.firstval1', 'subodval1.subsubodval1.secondval1', 'subodval1.subsubodval1.thirdval1', 'subodval2.subsubodval2.firstval2', 'subodval2.subsubodval2.secondval2', 'subodval2.subsubodval2.thirdval2']:
return
_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs) _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs)
@ -856,9 +927,12 @@ def autocheck_property_permissive(cfg, mcfg, pathread, pathwrite, confread, conf
def autocheck_reset_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_reset_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
"""check properties after set with permissive """check properties after set with permissive
""" """
#FIXME
if pathwrite in ['odleader.first', 'subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2', 'subodval1.subsubodval1.firstval1', 'subodval1.subsubodval1.secondval1', 'subodval1.subsubodval1.thirdval1', 'subodval2.subsubodval2.firstval2', 'subodval2.subsubodval2.secondval2', 'subodval2.subsubodval2.thirdval2']:
return
# check if is a multi or a follower # check if is a multi or a follower
multi = cfg.unrestraint.option(pathread).option.ismulti() multi = cfg.unrestraint.option(pathread).ismulti()
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
default_props, properties = _getproperties(multi, isfollower, kwargs) default_props, properties = _getproperties(multi, isfollower, kwargs)
_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs) _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs)
@ -879,8 +953,11 @@ def autocheck_reset_property(cfg, mcfg, pathread, pathwrite, confread, confwrite
@autocheck @autocheck
def autocheck_reset_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_reset_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# check if is a multi or a follower # check if is a multi or a follower
multi = cfg.unrestraint.option(pathread).option.ismulti() #FIXME
isfollower = cfg.unrestraint.option(pathread).option.isfollower() if pathwrite in ['odleader.first', 'subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2', 'subodval1.subsubodval1.firstval1', 'subodval1.subsubodval1.secondval1', 'subodval1.subsubodval1.thirdval1', 'subodval2.subsubodval2.firstval2', 'subodval2.subsubodval2.secondval2', 'subodval2.subsubodval2.thirdval2']:
return
multi = cfg.unrestraint.option(pathread).ismulti()
isfollower = cfg.unrestraint.option(pathread).isfollower()
default_props, properties = _getproperties(multi, isfollower, kwargs) default_props, properties = _getproperties(multi, isfollower, kwargs)
_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs) _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs)
@ -902,6 +979,8 @@ def autocheck_context_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite,
def autocheck_owner_with_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_owner_with_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
"""value is now changed, check owner in this case """value is now changed, check owner in this case
""" """
if pathwrite in ['odleader.first', 'subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2']:
return
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
_check_owner(cfg, pathread, confwrite, kwargs, kwargs['owner'], kwargs['owner']) _check_owner(cfg, pathread, confwrite, kwargs, kwargs['owner'], kwargs['owner'])
if confread != confwrite: if confread != confwrite:
@ -910,7 +989,7 @@ def autocheck_owner_with_value(cfg, mcfg, pathread, pathwrite, confread, confwri
@autocheck @autocheck
def autocheck_default_owner_with_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_default_owner_with_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None: if confwrite is not None:
@ -926,8 +1005,8 @@ def autocheck_default_owner_with_value(cfg, mcfg, pathread, pathwrite, confread,
if confwrite != confread: if confwrite != confread:
assert cfg2_.option(pathread).owner.isdefault() is False assert cfg2_.option(pathread).owner.isdefault() is False
#FIXME else: #FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathread).owner.isdefault()") # with raises(PropertiesOptionError):cfg.config(confwrite).option(pathread).owner.isdefault()")
# raises(PropertiesOptionError, "cfg.config(confread).option(pathread).owner.isdefault()") # with raises(PropertiesOptionError):cfg.config(confread).option(pathread).owner.isdefault()")
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg2_.option(pathread, 0).owner.isdefault() is True assert cfg2_.option(pathread, 0).owner.isdefault() is True
@ -936,14 +1015,14 @@ def autocheck_default_owner_with_value(cfg, mcfg, pathread, pathwrite, confread,
assert cfg_.option(pathread, 0).owner.isdefault() is True assert cfg_.option(pathread, 0).owner.isdefault() is True
assert cfg_.option(pathread, 1).owner.isdefault() is False assert cfg_.option(pathread, 1).owner.isdefault() is False
#FIXME else: #FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathread, 0).owner.isdefault()") # with raises(PropertiesOptionError):cfg.config(confwrite).option(pathread, 0).owner.isdefault()")
# raises(PropertiesOptionError, "cfg.config(confread).option(pathread, 0).owner.isdefault()") # with raises(PropertiesOptionError):cfg.config(confread).option(pathread, 0).owner.isdefault()")
@autocheck @autocheck
def autocheck_default_owner_with_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_default_owner_with_value_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# check if is a isfollower # check if is a isfollower
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
@ -966,22 +1045,26 @@ def autocheck_default_owner_with_value_permissive(cfg, mcfg, pathread, pathwrite
@autocheck @autocheck
def autocheck_set_owner_no_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_set_owner_no_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isfollower = cfg.unrestraint.option(pathread).option.isfollower() isfollower = cfg.unrestraint.option(pathread).isfollower()
if confwrite is not None: if confwrite is not None:
cfg_ = cfg.forcepermissive.config(confwrite) cfg_ = cfg.forcepermissive.config(confwrite)
else: else:
cfg_ = cfg.forcepermissive cfg_ = cfg.forcepermissive
if not kwargs.get('propertyerror', False): if not kwargs.get('propertyerror', False):
if not isfollower: if not isfollower:
raises(ConfigError, "cfg_.option(pathwrite).owner.set('new_user')") with raises(ConfigError):
cfg_.option(pathwrite).owner.set('new_user')
else: else:
raises(ConfigError, "cfg_.option(pathwrite, 1).owner.set('new_user')") with raises(ConfigError):
cfg_.option(pathwrite, 1).owner.set('new_user')
@autocheck @autocheck
def autocheck_set_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_set_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
# test set owner without permissive # test set owner without permissive
isfollower = cfg.unrestraint.option(pathread).option.isfollower() if pathwrite in ['subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2']:
return
isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None: if confwrite is not None:
@ -993,15 +1076,17 @@ def autocheck_set_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
if not isfollower: if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg_.option(pathwrite).owner.set('new_user') cfg_.option(pathwrite).owner.set('new_user')
raises(ValueError, "cfg_.option(pathwrite).owner.set('default')") with raises(ValueError):
raises(ValueError, "cfg_.option(pathwrite).owner.set('forced')") cfg_.option(pathwrite).owner.set('default')
with raises(ValueError):
cfg_.option(pathwrite).owner.set('forced')
#FIXME else: #FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite).owner.set('new_user')") # with raises(PropertiesOptionError):cfg.config(confwrite).option(pathwrite).owner.set('new_user')")
else: else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False): if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg.option(pathwrite, 1).owner.set('new_user') cfg.option(pathwrite, 1).owner.set('new_user')
#FIXME else: #FIXME else:
# raises(PropertiesOptionError, "cfg.option(pathwrite, 1).owner.set('new_user')") # with raises(PropertiesOptionError):cfg.option(pathwrite, 1).owner.set('new_user')")
_check_owner(cfg, pathread, confwrite, kwargs, owners.new_user, kwargs['owner']) _check_owner(cfg, pathread, confwrite, kwargs, owners.new_user, kwargs['owner'])
if confwrite != confread: if confwrite != confread:
@ -1010,7 +1095,9 @@ def autocheck_set_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
@autocheck @autocheck
def autocheck_set_owner_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_set_owner_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isfollower = cfg.unrestraint.option(pathread).option.isfollower() if pathwrite in ['subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third', 'subod.subsubodval1.firstval1', 'subod.subsubodval1.secondval1', 'subod.subsubodval1.thirdval1', 'subod.subsubodval2.firstval2', 'subod.subsubodval2.secondval2', 'subod.subsubodval2.thirdval2']:
return
isfollower = cfg.unrestraint.option(pathread).isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs) _set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None: if confwrite is not None:
@ -1026,10 +1113,10 @@ def autocheck_set_owner_permissive(cfg, mcfg, pathread, pathwrite, confread, con
cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user1') cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user1')
#FIXME else: #FIXME else:
# if not isfollower: # if not isfollower:
# raises(PropertiesOptionError, # with raises(PropertiesOptionError,
# "cfg.forcepermissive.config(confwrite).option(pathwrite).owner.set('new_user1')") # "cfg.forcepermissive.config(confwrite).option(pathwrite).owner.set('new_user1')")
# else: # else:
# raises(PropertiesOptionError, # with raises(PropertiesOptionError,
# "cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user1')") # "cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user1')")
_check_owner(cfg, pathread, confwrite, kwargs, 'new_user1', 'new_user1') _check_owner(cfg, pathread, confwrite, kwargs, 'new_user1', 'new_user1')
@ -1039,28 +1126,37 @@ def autocheck_set_owner_permissive(cfg, mcfg, pathread, pathwrite, confread, con
@autocheck @autocheck
def autocheck_option(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_option(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
#FIXME
if pathwrite.endswith('val1') or pathwrite.endswith('val2') or pathwrite in ['subod.subsubod.first', 'subod.subsubod.second', 'subod.subsubod.third']:
return
expected_name = pathread.split('.')[-1] expected_name = pathread.split('.')[-1]
if not kwargs.get('permissive_od', False): if not kwargs.get('permissive_od', False):
current_name = cfg.option(pathread).option.name() current_name = cfg.option(pathread).name()
assert current_name == cfg.forcepermissive.option(pathread).option.name() assert current_name == cfg.forcepermissive.option(pathread).name()
assert current_name == cfg.unrestraint.option(pathread).option.name() assert current_name == cfg.unrestraint.option(pathread).name()
doc = cfg.option(pathread).option.doc() doc = cfg.option(pathread).doc()
assert doc == cfg.forcepermissive.option(pathread).option.doc() assert doc == cfg.forcepermissive.option(pathread).doc()
assert doc == cfg.unrestraint.option(pathread).option.doc() assert doc == cfg.unrestraint.option(pathread).doc()
elif not kwargs.get('propertyerror', False): elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.option(pathread).option.name()") with raises(PropertiesOptionError):
current_name = cfg.forcepermissive.option(pathread).option.name() cfg.option(pathread).name()
assert current_name == cfg.unrestraint.option(pathread).option.name() current_name = cfg.forcepermissive.option(pathread).name()
raises(PropertiesOptionError, "cfg.option(pathread).option.doc()") assert current_name == cfg.unrestraint.option(pathread).name()
doc = cfg.forcepermissive.option(pathread).option.doc() with raises(PropertiesOptionError):
assert doc == cfg.unrestraint.option(pathread).option.doc() cfg.option(pathread).doc()
doc = cfg.forcepermissive.option(pathread).doc()
assert doc == cfg.unrestraint.option(pathread).doc()
else: else:
raises(PropertiesOptionError, "cfg.option(pathread).option.name()") with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.forcepermissive.option(pathread).option.name()") cfg.option(pathread).name()
current_name = cfg.unrestraint.option(pathread).option.name() with raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.option(pathread).option.doc()") cfg.forcepermissive.option(pathread).name()
raises(PropertiesOptionError, "cfg.forcepermissive.option(pathread).option.doc()") current_name = cfg.unrestraint.option(pathread).name()
doc = cfg.unrestraint.option(pathread).option.doc() with raises(PropertiesOptionError):
cfg.option(pathread).doc()
with raises(PropertiesOptionError):
cfg.forcepermissive.option(pathread).doc()
doc = cfg.unrestraint.option(pathread).doc()
assert current_name == expected_name assert current_name == expected_name
if expected_name.endswith('val1') or expected_name.endswith('val2'): if expected_name.endswith('val1') or expected_name.endswith('val2'):
expected_name = expected_name[:-4] expected_name = expected_name[:-4]
@ -1083,7 +1179,11 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
cfg2_ = cfg.config(confread).unrestraint cfg2_ = cfg.config(confread).unrestraint
else: else:
cfg2_ = cfg.unrestraint cfg2_ = cfg.unrestraint
if not cfg_.option(pathread).isfollower():
assert cfg_.option(pathread).permissive.get() == frozenset() assert cfg_.option(pathread).permissive.get() == frozenset()
else:
assert cfg_.option(pathread, 0).permissive.get() == frozenset()
if kwargs.get('permissive_od', False): if kwargs.get('permissive_od', False):
assert cfg_.option(pathread.rsplit('.', 1)[0]).permissive.get() == frozenset() assert cfg_.option(pathread.rsplit('.', 1)[0]).permissive.get() == frozenset()
@ -1104,7 +1204,10 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
cfg_.option(call_path).permissive.set(frozenset(['disabled'])) cfg_.option(call_path).permissive.set(frozenset(['disabled']))
# have permissive? # have permissive?
if not cfg_.option(pathread).isfollower():
assert cfg_.option(pathread).permissive.get() == frozenset(['disabled']) assert cfg_.option(pathread).permissive.get() == frozenset(['disabled'])
else:
assert cfg_.option(pathread, 0).permissive.get() == frozenset(['disabled'])
#if confwrite != confread: #if confwrite != confread:
# assert cfg.config(confread).unrestraint.option(pathread).permissive.get() == frozenset(['disabled']) # assert cfg.config(confread).unrestraint.option(pathread).permissive.get() == frozenset(['disabled'])
@ -1158,13 +1261,13 @@ def autocheck_option_get(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
name = pathread.rsplit('.', 1)[1] name = pathread.rsplit('.', 1)[1]
else: else:
name = pathread name = pathread
assert cfg.unrestraint.option(pathread).option.name() == name assert cfg.unrestraint.option(pathread).name() == name
@autocheck @autocheck
def autocheck_find(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs): def autocheck_find(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
def _getoption(opt): def _getoption(opt):
opt = opt.option.get() opt = opt.get()
if opt.impl_is_dynsymlinkoption(): if opt.impl_is_dynsymlinkoption():
opt = opt.opt opt = opt.opt
return opt return opt
@ -1190,11 +1293,14 @@ def autocheck_find(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs
assert option == _getoption(cfg_.option.find(name, first=True)) assert option == _getoption(cfg_.option.find(name, first=True))
assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True)) assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True))
elif kwargs.get('permissive', False): elif kwargs.get('permissive', False):
raises(AttributeError, "cfg_.option.find(name, first=True)") with raises(AttributeError):
cfg_.option.find(name, first=True)
assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True)) assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True))
else: else:
raises(AttributeError, "cfg_.option.find(name, first=True)") with raises(AttributeError):
raises(AttributeError, "cfg_.forcepermissive.option.find(name, first=True)") cfg_.option.find(name, first=True)
with raises(AttributeError):
cfg_.forcepermissive.option.find(name, first=True)
assert option == _getoption(cfg_.unrestraint.option.find(name, first=True)) assert option == _getoption(cfg_.unrestraint.option.find(name, first=True))
assert [option] == _getoptions(cfg_.unrestraint.option.find(name)) assert [option] == _getoptions(cfg_.unrestraint.option.find(name))
do(confread) do(confread)
@ -1372,11 +1478,11 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
for func in autocheck_registers: for func in autocheck_registers:
cfg_name = 'conftest' + str(idx) cfg_name = 'conftest' + str(idx)
idx += 1 idx += 1
ncfg = cfg.config.copy(session_id=cfg_name) ncfg = cfg.config.copy(name=cfg_name)
if meta: if meta:
confwrite = None confwrite = None
confread = cfg_name confread = cfg_name
mcfg = MetaConfig([ncfg], session_id='metatest') mcfg = MetaConfig([ncfg], name='metatest')
weakrefs.append(weakref.ref(cfg)) weakrefs.append(weakref.ref(cfg))
else: else:
mcfg = ncfg mcfg = ncfg
@ -1387,7 +1493,7 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
else: else:
ckwargs['owner'] = OWNER ckwargs['owner'] = OWNER
if mcfg.unrestraint.option(path).option.isfollower(): if mcfg.unrestraint.option(path).isfollower():
dirname = path.rsplit('.', 1)[0] dirname = path.rsplit('.', 1)[0]
leader_path = dirname + '.first' leader_path = dirname + '.first'
leader_path_2 = None leader_path_2 = None
@ -1545,11 +1651,11 @@ def make_conf(options, multi, default, default_multi, require, callback, symlink
call_kwargs['requires'] = option_requires call_kwargs['requires'] = option_requires
else: else:
kwargs['requires'] = option_requires kwargs['requires'] = option_requires
if multi and path is not 'extraoptrequire': if multi and path != 'extraoptrequire':
kwargs['multi'] = multi kwargs['multi'] = multi
if callback: if callback:
call_kwargs['multi'] = multi call_kwargs['multi'] = multi
if ((not in_leader or leader) and default) and path is not 'extraoptrequire' and not path.endswith('extraoptconsistency'): if ((not in_leader or leader) and default) and path != 'extraoptrequire' and not path.endswith('extraoptconsistency'):
if multi is False: if multi is False:
value = FIRST_VALUE value = FIRST_VALUE
elif multi is True: elif multi is True:
@ -1563,7 +1669,7 @@ def make_conf(options, multi, default, default_multi, require, callback, symlink
kwargs['default'] = value kwargs['default'] = value
elif callback: elif callback:
return None, None, None return None, None, None
if default_multi and path is not 'extraoptrequire': if default_multi and path != 'extraoptrequire':
if multi is not submulti: if multi is not submulti:
value = SECOND_VALUE value = SECOND_VALUE
else: else:
@ -1585,7 +1691,6 @@ def make_conf(options, multi, default, default_multi, require, callback, symlink
tiramisu_option = SymLinkOption tiramisu_option = SymLinkOption
else: else:
sobj = None sobj = None
print(args, kwargs)
obj = tiramisu_option(*args, **kwargs) obj = tiramisu_option(*args, **kwargs)
return obj, objcall, sobj return obj, objcall, sobj
@ -1678,7 +1783,7 @@ def make_conf(options, multi, default, default_multi, require, callback, symlink
rootod = make_optiondescriptions('root', collect_options) rootod = make_optiondescriptions('root', collect_options)
if rootod is None: if rootod is None:
return None, None, None return None, None, None
cfg = Config(rootod, session_id='conftest') cfg = Config(rootod, name='conftest')
weakrefs.append(weakref.ref(cfg)) weakrefs.append(weakref.ref(cfg))
del goptions del goptions
return cfg, weakrefs, dyn return cfg, weakrefs, dyn

View file

@ -21,11 +21,11 @@ except:
import pytest import pytest
async def get_config(config, type, error=False): def get_config(config, type, error=False):
if type == 'tiramisu': if type == 'tiramisu':
return config return config
if error: if error:
await config.property.add('demoting_error_warning') config.property.add('demoting_error_warning')
return TestConfig(config) return TestConfig(config)
@ -35,51 +35,10 @@ def value_list(values):
return tuple(values) return tuple(values)
async def global_owner(config, config_type): def global_owner(config, config_type):
return await config.owner.get() return config.owner.get()
@pytest.fixture(params=PARAMS) @pytest.fixture(params=PARAMS)
def config_type(request): def config_type(request):
return request.param return request.param
LOOP = None
@pytest.fixture(scope='session')
def event_loop(request):
"""Create an instance of the default event loop for each test case."""
global LOOP
if LOOP is None:
LOOP = asyncio.get_event_loop_policy().new_event_loop()
return LOOP
async def _delete_sessions(meta):
if await meta.config.type() != 'config':
for conf in await meta.config.list():
await _delete_sessions(conf)
await meta.session.reset()
async def delete_sessions(confs):
if not isinstance(confs, list):
confs = [confs]
for conf in confs:
await _delete_sessions(conf)
if environ.get('TIRAMISU_STORAGE') == 'postgres':
async with confs[0]._config_bag.context.getconnection() as connection:
assert await connection.fetchrow('SELECT * FROM session') is None
assert await connection.fetchrow('SELECT * FROM value') is None
assert await connection.fetchrow('SELECT * FROM information') is None
assert await connection.fetchrow('SELECT * FROM property') is None
assert await connection.fetchrow('SELECT * FROM permissive') is None
elif environ.get('TIRAMISU_STORAGE') == 'sqlite3':
async with confs[0]._config_bag.context.getconnection() as connection:
assert await connection.select('SELECT * FROM session') is None
assert await connection.select('SELECT * FROM value') is None
assert await connection.select('SELECT * FROM information') is None
assert await connection.select('SELECT * FROM property') is None
assert await connection.select('SELECT * FROM permissive') is None
else:
from tiramisu import list_sessions
assert not await list_sessions()

View file

@ -16,10 +16,10 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'choice1_leadership_value.' root = 'choice1_leadership_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.choice1.choice1').value.set(['choice 2']) api.option(root + 'options.choice1.choice1').value.set(['choice 2'])
await api.option(root + 'options.choice1.choice2', 0).value.set('choice 4') api.option(root + 'options.choice1.choice2', 0).value.set('choice 4')

View file

@ -6,7 +6,7 @@ def get_description():
option1 = ChoiceOption('choice', "Choice description", ("hide", "show"), default='hide', properties=('mandatory',)) option1 = ChoiceOption('choice', "Choice description", ("hide", "show"), default='hide', properties=('mandatory',))
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('hide')})) 'expected': ParamValue('hide')}))
option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,)) option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,))
descr1 = OptionDescription("options", "Common configuration", [option1, option2]) descr1 = OptionDescription("options", "Common configuration", [option1, option2])

View file

@ -29,7 +29,6 @@
"form": { "form": {
"usbpath": { "usbpath": {
"clearable": true, "clearable": true,
"pattern": "^[a-zA-Z0-9\\-\\._~/+]+$",
"type": "input" "type": "input"
}, },
"null": [ "null": [

View file

@ -10,9 +10,9 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'number1_mod_value.' root = 'number1_mod_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.integer').value.set(3) api.option(root + 'options.integer').value.set(3)

View file

@ -1 +1,3 @@
{"options.unicode": null} {
"options.unicode": null
}

View file

@ -1 +1,3 @@
{"options.unicode": "val"} {
"options.unicode": "val"
}

View file

@ -16,10 +16,10 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_hidden.' root = 'unicode1_leadership_hidden.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode.unicode').value.set([u'val1', u'val2']) api.option(root + 'options.unicode.unicode').value.set([u'val1', u'val2'])
await api.option(root + 'options.unicode.unicode2', 0).value.set(u'super') api.option(root + 'options.unicode.unicode2', 0).value.set(u'super')

View file

@ -8,7 +8,7 @@ def get_description():
option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True) option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option2, todict=True), kwargs={'condition': ParamOption(option2),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True) option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True)

View file

@ -10,7 +10,7 @@ def get_description():
option3 = StrOption('unicode3', "Unicode follower 2", multi=True) option3 = StrOption('unicode3', "Unicode follower 2", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option, todict=True), kwargs={'condition': ParamOption(option),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
descr1 = Leadership("unicode1", "Common configuration", descr1 = Leadership("unicode1", "Common configuration",

View file

@ -9,7 +9,7 @@ def get_description():
option2 = StrOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
disabled_property = Calculation(calc_value, disabled_property = Calculation(calc_value,
Params(ParamValue('disabled'), Params(ParamValue('disabled'),
kwargs={'condition': ParamOption(option, todict=True), kwargs={'condition': ParamOption(option),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 3", properties=(disabled_property,), multi=True) option3 = StrOption('unicode3', "Unicode follower 3", properties=(disabled_property,), multi=True)
@ -20,14 +20,14 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_requires_disabled_value.' root = 'unicode1_leadership_requires_disabled_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2']) api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2'])
await api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1') api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1')
await api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2') api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2')
await api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test') api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test')
await api.option(root + 'options.unicode.unicode2', 1).value.set(u'test') api.option(root + 'options.unicode.unicode2', 1).value.set(u'test')
await api.option(root + 'options.unicode.unicode3', 1).value.set(u'super') api.option(root + 'options.unicode.unicode3', 1).value.set(u'super')

View file

@ -8,7 +8,7 @@ def get_description():
option2 = StrOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,)) option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,))

View file

@ -8,7 +8,7 @@ def get_description():
option2 = StrOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,)) option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,))
@ -19,11 +19,11 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_requires_follower_value.' root = 'unicode1_leadership_requires_follower_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode1.unicode1').value.set([u'test', u'pas test']) api.option(root + 'options.unicode1.unicode1').value.set([u'test', u'pas test'])
await api.option(root + 'options.unicode1.unicode2', 0).value.set(u'super1') api.option(root + 'options.unicode1.unicode2', 0).value.set(u'super1')
await api.option(root + 'options.unicode1.unicode3', 0).value.set(u'super1') api.option(root + 'options.unicode1.unicode3', 0).value.set(u'super1')

View file

@ -8,7 +8,7 @@ def get_description():
option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 2'", multi=True) option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 2'", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option2, todict=True), kwargs={'condition': ParamOption(option2),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,)) option3 = StrOption('unicode3', "Unicode follower 2", multi=True, properties=(hidden_property,))

View file

@ -9,7 +9,7 @@ def get_description():
option2 = StrOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option, todict=True), kwargs={'condition': ParamOption(option),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True) option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True)
@ -20,14 +20,14 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_requires_value.' root = 'unicode1_leadership_requires_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2']) api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2'])
await api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1') api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1')
await api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2') api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2')
await api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test') api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test')
await api.option(root + 'options.unicode.unicode2', 1).value.set(u'test') api.option(root + 'options.unicode.unicode2', 1).value.set(u'test')
await api.option(root + 'options.unicode.unicode3', 1).value.set(u'super') api.option(root + 'options.unicode.unicode3', 1).value.set(u'super')

View file

@ -1,4 +1,16 @@
{"options.unicode.unicode": ["val3", "val4"], {
"options.unicode.unicode1": ["super1", "super2"], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test", "test"], {
"options.unicode.unicode3": [null, "super"]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val4",
"options.unicode.unicode1": "super2",
"options.unicode.unicode2": "test",
"options.unicode.unicode3": "super"
}
]
}

View file

@ -1,4 +1,16 @@
{"options.unicode.unicode": ["val1", "val2"], {
"options.unicode.unicode1": [null, null], "options.unicode.unicode": [
"options.unicode.unicode2": ["follower2", "follower2"], {
"options.unicode.unicode3": [null, null]} "options.unicode.unicode": "val1",
"options.unicode.unicode1": null,
"options.unicode.unicode2": "follower2",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val2",
"options.unicode.unicode1": null,
"options.unicode.unicode2": "follower2",
"options.unicode.unicode3": null
}
]
}

View file

@ -1,4 +1,10 @@
{"options.unicode.unicode": ["val3"], {
"options.unicode.unicode1": ["super1"], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test"], {
"options.unicode.unicode3": [null]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
}
]
}

View file

@ -1,4 +1,22 @@
{"options.unicode.unicode": ["val3", "val4", "val5"], {
"options.unicode.unicode1": ["super1", "super2", null], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test", "test", "follower2"], {
"options.unicode.unicode3": [null, "super", null]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val4",
"options.unicode.unicode1": "super2",
"options.unicode.unicode2": "test",
"options.unicode.unicode3": "super"
},
{
"options.unicode.unicode": "val5",
"options.unicode.unicode1": null,
"options.unicode.unicode2": "follower2",
"options.unicode.unicode3": null
}
]
}

View file

@ -1,4 +1,22 @@
{"options.unicode.unicode": ["val3", "val4", "val5"], {
"options.unicode.unicode1": ["super1", "super2", null], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test", "test", "follower2"], {
"options.unicode.unicode3": [null, "super", null]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val4",
"options.unicode.unicode1": "super2",
"options.unicode.unicode2": "test",
"options.unicode.unicode3": "super"
},
{
"options.unicode.unicode": "val5",
"options.unicode.unicode1": null,
"options.unicode.unicode2": "follower2",
"options.unicode.unicode3": null
}
]
}

View file

@ -1,4 +1,16 @@
{"options.unicode.unicode": ["val3", "val4"], {
"options.unicode.unicode1": ["super1", "super2"], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test", "follower2"], {
"options.unicode.unicode3": [null, "super"]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val4",
"options.unicode.unicode1": "super2",
"options.unicode.unicode2": "follower2",
"options.unicode.unicode3": "super"
}
]
}

View file

@ -1,4 +1,16 @@
{"options.unicode.unicode": ["val3", "val4"], {
"options.unicode.unicode1": ["super1", "super2"], "options.unicode.unicode": [
"options.unicode.unicode2": ["pas test", "test2"], {
"options.unicode.unicode3": [null, "super"]} "options.unicode.unicode": "val3",
"options.unicode.unicode1": "super1",
"options.unicode.unicode2": "pas test",
"options.unicode.unicode3": null
},
{
"options.unicode.unicode": "val4",
"options.unicode.unicode1": "super2",
"options.unicode.unicode2": "test2",
"options.unicode.unicode3": "super"
}
]
}

View file

@ -16,14 +16,14 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_value.' root = 'unicode1_leadership_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode.unicode').value.set([u'val3', u'val4']) api.option(root + 'options.unicode.unicode').value.set([u'val3', u'val4'])
await api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1') api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1')
await api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2') api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2')
await api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test') api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test')
await api.option(root + 'options.unicode.unicode2', 1).value.set(u'test') api.option(root + 'options.unicode.unicode2', 1).value.set(u'test')
await api.option(root + 'options.unicode.unicode3', 1).value.set(u'super') api.option(root + 'options.unicode.unicode3', 1).value.set(u'super')

View file

@ -1 +1,3 @@
{"options.unicode": "a"} {
"options.unicode": "a"
}

View file

@ -1 +1,3 @@
{"options.unicode": "val"} {
"options.unicode": "val"
}

View file

@ -1 +1,3 @@
{"options.unicode": null} {
"options.unicode": null
}

View file

@ -11,9 +11,9 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_mod_value.' root = 'unicode1_mod_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode').value.set('a') api.option(root + 'options.unicode').value.set('a')

View file

@ -1 +1,3 @@
{"options.unicode": []} {
"options.unicode": []
}

View file

@ -1 +1,5 @@
{"options.unicode": ["val"]} {
"options.unicode": [
"val"
]
}

View file

@ -1 +1,7 @@
{"options.unicode": ["c", "d", "e"]} {
"options.unicode": [
"c",
"d",
"e"
]
}

View file

@ -1 +1,6 @@
{"options.unicode": ["a", "b"]} {
"options.unicode": [
"a",
"b"
]
}

View file

@ -1 +1,7 @@
{"options.unicode": ["c", "f", "e"]} {
"options.unicode": [
"c",
"f",
"e"
]
}

View file

@ -11,9 +11,9 @@ def get_description():
return descr return descr
async def get_values(api, allpath=False): def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_multi_mod_value.' root = 'unicode1_multi_mod_value.'
else: else:
root = '' root = ''
await api.option(root + 'options.unicode').value.set(['c', 'd', 'e']) api.option(root + 'options.unicode').value.set(['c', 'd', 'e'])

View file

@ -7,7 +7,7 @@ def get_description():
option1 = StrOption('unicode1', "Value 'test' must show Unicode 2") option1 = StrOption('unicode1', "Value 'test' must show Unicode 2")
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,), multi=True) option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,), multi=True)

View file

@ -10,7 +10,7 @@ def get_description():
option3 = StrOption('unicode3', "Unicode 3") option3 = StrOption('unicode3', "Unicode 3")
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
descr2 = OptionDescription("unicode1", "OptionDescription with 2 options", [option2, option3], properties=(hidden_property,)) descr2 = OptionDescription("unicode1", "OptionDescription with 2 options", [option2, option3], properties=(hidden_property,))

View file

@ -7,7 +7,7 @@ def get_description():
option1 = StrOption('unicode1', "Value 'test' must show Unicode 2") option1 = StrOption('unicode1', "Value 'test' must show Unicode 2")
hidden_property = Calculation(calc_value, hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'), Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True), kwargs={'condition': ParamOption(option1),
'expected': ParamValue('test'), 'expected': ParamValue('test'),
'reverse_condition': ParamValue(True)})) 'reverse_condition': ParamValue(True)}))
option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,)) option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,))

View file

@ -23,8 +23,8 @@ def datapath():
def list_data(ext='.py'): def list_data(ext='.py'):
# if ext == '.py': # if ext == '.py':
# return ['choice1_leadership_hidden.py'] # return ['unicode1_leadership_requires.py']
datadir = datapath() datadir = datapath()
filenames = listdir(datadir) filenames = listdir(datadir)
filenames.sort() filenames.sort()
@ -36,30 +36,31 @@ def list_data(ext='.py'):
return ret return ret
async def load_config(filename, def load_config(filename,
add_extra_od=False, add_extra_od=False,
remote='minimum', remote='minimum',
clearable='minimum', clearable='minimum',
root=None): root=None,
):
modulepath = splitext(filename)[0] modulepath = splitext(filename)[0]
mod = __import__(modulepath) mod = __import__(modulepath)
descr = mod.get_description() descr = mod.get_description()
if add_extra_od: if add_extra_od:
descr = OptionDescription('root', '', [descr]) descr = OptionDescription('root', '', [descr])
config = await Config(descr) config = Config(descr)
await config.property.add('demoting_error_warning') config.property.add('demoting_error_warning')
if 'get_values' in dir(mod): if 'get_values' in dir(mod):
await mod.get_values(config, add_extra_od) mod.get_values(config, add_extra_od)
form = [{'title': 'Configurer', form = [{'title': 'Configurer',
'type': 'submit'}] 'type': 'submit'}]
if 'get_form' in dir(mod): if 'get_form' in dir(mod):
form.extend(mod.get_form(add_extra_od)) form.extend(mod.get_form(add_extra_od))
await config.property.read_write() config.property.read_write()
if root is None: if root is None:
values = loads(dumps(await config.option.dict(remotable=remote, clearable=clearable, form=form))) values = loads(dumps(config.option.dict(remotable=remote, clearable=clearable, form=form)))
else: else:
values = loads(dumps(await config.option(root).dict(remotable=remote, clearable=clearable, form=form))) values = loads(dumps(config.option(root).dict(remotable=remote, clearable=clearable, form=form)))
return values return values
@ -150,8 +151,7 @@ def filename_mod(request):
return request.param return request.param
@pytest.mark.asyncio def test_jsons(filename):
async def test_jsons(filename):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -168,9 +168,10 @@ async def test_jsons(filename):
modulepath = splitext(filename)[0] modulepath = splitext(filename)[0]
if debug: if debug:
print(" {} (remote: {}, clearable: {})".format(filename, remote, clearable)) print(" {} (remote: {}, clearable: {})".format(filename, remote, clearable))
values = await load_config(filename, values = load_config(filename,
remote=remote, remote=remote,
clearable=clearable) clearable=clearable,
)
# #
if not isfile(join(datadir, modulepath + '.json')) and \ if not isfile(join(datadir, modulepath + '.json')) and \
clearable == 'minimum' and \ clearable == 'minimum' and \
@ -217,8 +218,28 @@ async def test_jsons(filename):
assert values == expected, "error in file {}".format(filename) assert values == expected, "error in file {}".format(filename)
@pytest.mark.asyncio def loads_yml(fh, issub, modulepath):
async def test_jsons_subconfig(filename): dico = loads(fh.read())
if issub:
new_dico_ori = {}
for key, value in dico.items():
key = modulepath + '.' + key
if isinstance(value, list):
new_value = []
for val in value:
if isinstance(val, dict):
new_val = {}
for k, v in val.items():
new_val[modulepath + '.' + k] = v
val = new_val
new_value.append(val)
value = new_value
new_dico_ori[key] = value
dico = new_dico_ori
return dico
def test_jsons_subconfig(filename):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -227,7 +248,7 @@ async def test_jsons_subconfig(filename):
modulepath = splitext(filename)[0] modulepath = splitext(filename)[0]
if debug: if debug:
print(" ", filename) print(" ", filename)
values = await load_config(filename, add_extra_od=True, root=modulepath) values = load_config(filename, add_extra_od=True, root=modulepath)
# #
with open(join(datadir, modulepath + '.json'), 'r') as fh: with open(join(datadir, modulepath + '.json'), 'r') as fh:
expected = loads(fh.read()) expected = loads(fh.read())
@ -292,8 +313,7 @@ async def test_jsons_subconfig(filename):
assert values == expected, "error in file {}".format(filename) assert values == expected, "error in file {}".format(filename)
@pytest.mark.asyncio def test_updates(filename_mod):
async def test_updates(filename_mod):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -314,13 +334,7 @@ async def test_updates(filename_mod):
dico_ori = None dico_ori = None
else: else:
with open(join(datadir, modulepath + '.dict'), 'r') as fh: with open(join(datadir, modulepath + '.dict'), 'r') as fh:
dico_ori = loads(fh.read()) dico_ori = loads_yml(fh, issub, modulepath)
if issub:
new_dico_ori = {}
for key, value in dico_ori.items():
key = modulepath + '.' + key
new_dico_ori[key] = value
dico_ori = new_dico_ori
# modify config # modify config
with open(join(datadir, modulepath + '.mod{}'.format(idx)), 'r') as fh: with open(join(datadir, modulepath + '.mod{}'.format(idx)), 'r') as fh:
body = loads(fh.read())['body'] body = loads(fh.read())['body']
@ -346,13 +360,7 @@ async def test_updates(filename_mod):
dico_mod = None dico_mod = None
else: else:
with open(join(datadir, modulepath + '.dict{}'.format(idx)), 'r') as fh: with open(join(datadir, modulepath + '.dict{}'.format(idx)), 'r') as fh:
dico_mod = loads(fh.read()) dico_mod = loads_yml(fh, issub, modulepath)
if issub:
new_dico = {}
for key, value in dico_mod.items():
key = modulepath + '.' + key
new_dico[key] = value
dico_mod = new_dico
if root is None: if root is None:
root_path = '' root_path = ''
else: else:
@ -362,31 +370,31 @@ async def test_updates(filename_mod):
if debug: if debug:
print(" (remote: {}, clearable: {}, issub {}, root {}, root_path {})".format(remote, clearable, issub, root, root_path)) print(" (remote: {}, clearable: {}, issub {}, root {}, root_path {})".format(remote, clearable, issub, root, root_path))
for with_model in [False, True]: for with_model in [False, True]:
config = await Config(descr) config = Config(descr)
await config.property.add('demoting_error_warning') config.property.add('demoting_error_warning')
if 'get_values' in dir(mod): if 'get_values' in dir(mod):
await mod.get_values(config, issub) mod.get_values(config, issub)
if isfile(join(datadir, modulepath + '.mod')): if isfile(join(datadir, modulepath + '.mod')):
with open(join(datadir, modulepath + '.mod'), 'r') as fh: with open(join(datadir, modulepath + '.mod'), 'r') as fh:
await eval(fh.read()) eval(fh.read())
if dico_ori is None: if dico_ori is None:
if clearable == 'minimum' and remote == 'minimum': if clearable == 'minimum' and remote == 'minimum':
with open(join(datadir, modulepath + '.dict'), 'w') as fh: with open(join(datadir, modulepath + '.dict'), 'w') as fh:
dump(await config.value.dict(), fh, indent=2) dump(config.value.dict(), fh, indent=2)
else: else:
assert await config.value.dict() == dico_ori, "clearable {}, remote: {}, filename: {}".format(clearable, remote, filename_mod) assert config.value.dict() == dico_ori, "clearable {}, remote: {}, filename: {}".format(clearable, remote, filename_mod)
if root is None: if root is None:
suboption = config.option suboption = config.option
else: else:
suboption = config.option(root) suboption = config.option(root)
if with_model: if with_model:
bodym = body.copy() bodym = body.copy()
bodym['model'] = loads(dumps(await suboption.dict(remotable=remote, clearable=clearable)))['model'] bodym['model'] = loads(dumps(suboption.dict(remotable=remote, clearable=clearable)))['model']
else: else:
await suboption.dict(remotable=remote, clearable=clearable) suboption.dict(remotable=remote, clearable=clearable)
bodym = body bodym = body
if with_model: if with_model:
cal_values = await suboption.updates(bodym) cal_values = suboption.updates(bodym)
if values is None: if values is None:
if clearable == 'minimum' and remote == 'minimum': if clearable == 'minimum' and remote == 'minimum':
with open(join(datadir, modulepath + '.updates{}'.format(idx)), 'w') as fh: with open(join(datadir, modulepath + '.updates{}'.format(idx)), 'w') as fh:
@ -399,10 +407,10 @@ async def test_updates(filename_mod):
pprint(values) pprint(values)
assert cal_values == values assert cal_values == values
else: else:
assert await suboption.updates(bodym) == {} assert suboption.updates(bodym) == {}
if dico_mod is None: if dico_mod is None:
if clearable == 'minimum' and remote == 'minimum': if clearable == 'minimum' and remote == 'minimum':
with open(join(datadir, modulepath + '.dict{}'.format(idx)), 'w') as fh: with open(join(datadir, modulepath + '.dict{}'.format(idx)), 'w') as fh:
dump(await config.value.dict(), fh, indent=2) dump(config.value.dict(), fh, indent=2)
else: else:
assert await config.value.dict() == dico_mod assert config.value.dict() == dico_mod

View file

@ -1,16 +1,13 @@
# coding: utf-8 # coding: utf-8
from time import sleep, time from time import sleep, time
import pytest
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from tiramisu import BoolOption, IPOption, IntOption, StrOption, OptionDescription, Leadership, Config, \ from tiramisu import BoolOption, IPOption, IntOption, StrOption, OptionDescription, Leadership, Config, \
undefined, Calculation, Params, ParamValue, ParamOption, \ undefined, Calculation, Params, ParamValue, ParamOption, calc_value
list_sessions, default_storage, delete_session, calc_value
from tiramisu.error import ConfigError, PropertiesOptionError from tiramisu.error import ConfigError, PropertiesOptionError
from tiramisu.setting import groups from tiramisu.setting import groups
from .config import event_loop
global incr global incr
@ -28,247 +25,238 @@ def make_description():
return OptionDescription('od1', '', [u1, u2, u3]) return OptionDescription('od1', '', [u1, u2, u3])
@pytest.mark.asyncio def test_cache_config():
async def test_cache_config():
od1 = make_description() od1 = make_description()
assert od1.impl_already_build_caches() is False assert od1.impl_already_build_caches() is False
async with await Config(od1) as cfg: cfg = Config(od1)
assert od1.impl_already_build_caches() is True assert od1.impl_already_build_caches() is True
cfg cfg
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache():
async def test_cache():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.option('u2').value.get() cfg.option('u2').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' in values.get_cached() assert 'u2' in values.get_cached()
assert 'u2' in settings.get_cached() assert 'u2' in settings.get_cached()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_importation():
async def test_cache_importation():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.option('u2').value.set(1) cfg.option('u2').value.set(1)
export = await cfg.value.exportation() export = cfg.value.exportation()
assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
await cfg.option('u2').value.set(2) cfg.option('u2').value.set(2)
assert await cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []} assert cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []}
await cfg.value.importation(export) cfg.value.importation(export)
assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_importation_property():
async def test_cache_importation_property():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.option('u2').property.add('prop') cfg.option('u2').property.add('prop')
export = await cfg.property.exportation() export = cfg.property.exportation()
assert await cfg.option('u2').property.get() == {'prop'} assert cfg.option('u2').property.get() == {'prop'}
await cfg.option('u2').property.add('prop2') cfg.option('u2').property.add('prop2')
assert await cfg.option('u2').property.get() == {'prop', 'prop2'} assert cfg.option('u2').property.get() == {'prop', 'prop2'}
await cfg.property.importation(export) cfg.property.importation(export)
assert await cfg.option('u2').property.get() == {'prop'} assert cfg.option('u2').property.get() == {'prop'}
assert not await list_sessions() cfg = Config(od1)
# assert not list_sessions()
@pytest.mark.asyncio def test_cache_importation_permissive():
async def test_cache_importation_permissive():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.option('u2').permissive.set(frozenset(['prop'])) cfg.option('u2').permissive.set(frozenset(['prop']))
export = await cfg.permissive.exportation() export = cfg.permissive.exportation()
assert await cfg.option('u2').permissive.get() == {'prop'} assert cfg.option('u2').permissive.get() == {'prop'}
await cfg.option('u2').permissive.set(frozenset(['prop', 'prop2'])) cfg.option('u2').permissive.set(frozenset(['prop', 'prop2']))
assert await cfg.option('u2').permissive.get() == {'prop', 'prop2'} assert cfg.option('u2').permissive.get() == {'prop', 'prop2'}
await cfg.permissive.importation(export) cfg.permissive.importation(export)
assert await cfg.option('u2').permissive.get() == {'prop'} assert cfg.option('u2').permissive.get() == {'prop'}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_reset():
async def test_cache_reset():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
#when change a value #when change a value
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.option('u2').value.get() cfg.option('u2').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' in values.get_cached() assert 'u2' in values.get_cached()
assert 'u2' in settings.get_cached() assert 'u2' in settings.get_cached()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
settings.get_cached() settings.get_cached()
await cfg.option('u2').value.set(1) cfg.option('u2').value.set(1)
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' in values.get_cached() assert 'u2' in values.get_cached()
assert 'u2' not in settings.get_cached() assert 'u2' not in settings.get_cached()
#when remove a value #when remove a value
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.option('u2').value.reset() cfg.option('u2').value.reset()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' not in values.get_cached() assert 'u2' not in values.get_cached()
assert 'u2' not in settings.get_cached() assert 'u2' not in settings.get_cached()
#when add/del property #when add/del property
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.option('u2').property.add('test') cfg.option('u2').property.add('test')
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' not in values.get_cached() assert 'u2' not in values.get_cached()
assert 'u2' not in settings.get_cached() assert 'u2' not in settings.get_cached()
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.option('u2').property.pop('test') cfg.option('u2').property.remove('test')
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' not in values.get_cached() assert 'u2' not in values.get_cached()
assert 'u2' not in settings.get_cached() assert 'u2' not in settings.get_cached()
#when enable/disabled property #when enable/disabled property
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.property.add('test') cfg.property.add('test')
assert 'u1' not in values.get_cached() assert 'u1' not in values.get_cached()
assert 'u1' not in settings.get_cached() assert 'u1' not in settings.get_cached()
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.property.pop('test') cfg.property.remove('test')
assert 'u1' not in values.get_cached() assert 'u1' not in values.get_cached()
assert 'u1' not in settings.get_cached() assert 'u1' not in settings.get_cached()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_reset_multi():
async def test_cache_reset_multi():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.option('u3').value.get() cfg.option('u3').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' in settings.get_cached() assert 'u3' in settings.get_cached()
#when change a value #when change a value
await cfg.option('u3').value.set([1]) cfg.option('u3').value.set([1])
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' not in settings.get_cached() assert 'u3' not in settings.get_cached()
#when append value #when append value
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.option('u3').value.get() cfg.option('u3').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' in settings.get_cached() assert 'u3' in settings.get_cached()
await cfg.option('u3').value.set([1, 2]) cfg.option('u3').value.set([1, 2])
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' not in settings.get_cached() assert 'u3' not in settings.get_cached()
#when pop value #when pop value
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.option('u3').value.get() cfg.option('u3').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' in settings.get_cached() assert 'u3' in settings.get_cached()
await cfg.option('u3').value.set([1]) cfg.option('u3').value.set([1])
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' in values.get_cached() assert 'u3' in values.get_cached()
assert 'u3' not in settings.get_cached() assert 'u3' not in settings.get_cached()
#when remove a value #when remove a value
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.option('u3').value.reset() cfg.option('u3').value.reset()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u3' not in values.get_cached() assert 'u3' not in values.get_cached()
assert 'u3' not in settings.get_cached() assert 'u3' not in settings.get_cached()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_reset_cache():
async def test_reset_cache():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
await cfg.cache.reset() cfg.cache.reset()
assert 'u1' not in values.get_cached() assert 'u1' not in values.get_cached()
assert 'u1' not in settings.get_cached() assert 'u1' not in settings.get_cached()
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.option('u2').value.get() cfg.option('u2').value.get()
assert 'u1' in values.get_cached() assert 'u1' in values.get_cached()
assert 'u1' in settings.get_cached() assert 'u1' in settings.get_cached()
assert 'u2' in values.get_cached() assert 'u2' in values.get_cached()
assert 'u2' in settings.get_cached() assert 'u2' in settings.get_cached()
await cfg.cache.reset() cfg.cache.reset()
assert 'u1' not in values.get_cached() assert 'u1' not in values.get_cached()
assert 'u1' not in settings.get_cached() assert 'u1' not in settings.get_cached()
assert 'u2' not in values.get_cached() assert 'u2' not in values.get_cached()
assert 'u2' not in settings.get_cached() assert 'u2' not in settings.get_cached()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_not_cache():
async def test_cache_not_cache():
od1 = make_description() od1 = make_description()
async with await Config(od1) as cfg: cfg = Config(od1)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
await cfg.property.pop('cache') cfg.property.remove('cache')
await cfg.option('u1').value.get() cfg.option('u1').value.get()
assert 'u1' not in values.get_cached() assert 'u1' not in values.get_cached()
assert 'u1' not in settings.get_cached() assert 'u1' not in settings.get_cached()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_leadership():
async def test_cache_leadership():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od1 = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
#assert settings.get_cached() == {} #assert settings.get_cached() == {}
# #
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
cache = values.get_cached() cache = values.get_cached()
assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None])
@ -280,12 +268,12 @@ async def test_cache_leadership():
assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert set(cache['ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0'].keys()) == set([None])
assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None])
assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([0, None]) assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == {0}
# #
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()
cache = values.get_cached() cache = values.get_cached()
assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None])
@ -298,9 +286,9 @@ async def test_cache_leadership():
assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert set(cache['ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0'].keys()) == set([None])
assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None])
assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None, 0, 1]) assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([0, 1])
#DEL, insert, ... #DEL, insert, ...
assert not await list_sessions() # assert not list_sessions()
def compare(calculated, expected): def compare(calculated, expected):
@ -312,83 +300,69 @@ def compare(calculated, expected):
assert calculated[calculated_key][calculated_subkey][0] == expected[calculated_key][calculated_subkey][0] assert calculated[calculated_key][calculated_subkey][0] == expected[calculated_key][calculated_subkey][0]
@pytest.mark.asyncio def test_cache_callback():
async def test_cache_callback():
val1 = StrOption('val1', "", 'val') val1 = StrOption('val1', "", 'val')
val2 = StrOption('val2', "", Calculation(calc_value, Params(ParamOption(val1))), properties=('mandatory',)) val2 = StrOption('val2', "", Calculation(calc_value, Params(ParamOption(val1))), properties=('mandatory',))
val3 = StrOption('val3', "", Calculation(calc_value, Params(ParamValue('yes')))) val3 = StrOption('val3', "", Calculation(calc_value, Params(ParamValue('yes'))))
val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val1)))) val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val1))))
val5 = StrOption('val5', "", [Calculation(calc_value, Params(ParamValue('yes')))], multi=True) val5 = StrOption('val5', "", [Calculation(calc_value, Params(ParamValue('yes')))], multi=True)
od1 = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5]) od1 = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.value.dict() cfg.value.dict()
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
compare(values.get_cached(), {'val1': {None: ('val', None)}, compare(values.get_cached(), {'val1': {None: ('val', None)},
'val2': {None: ('val', None)}, 'val2': {None: ('val', None)},
'val3': {None: ('yes', None)}, 'val3': {None: ('yes', None)},
'val4': {None: ('val', None)}, 'val4': {None: ('val', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.option('val1').value.set('new') cfg.option('val1').value.set('new')
compare(values.get_cached(), {'val3': {None: ('yes', None)}, compare(values.get_cached(), {'val3': {None: ('yes', None)},
'val1': {None: ('new', None)}, 'val1': {None: ('new', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.value.dict() cfg.value.dict()
compare(values.get_cached(), {'val1': {None: ('new', None)}, compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)}, 'val2': {None: ('new', None)},
'val3': {None: ('yes', None)}, 'val3': {None: ('yes', None)},
'val4': {None: ('new', None)}, 'val4': {None: ('new', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.option('val3').value.set('new2') cfg.option('val3').value.set('new2')
compare(values.get_cached(), {'val1': {None: ('new', None)}, compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)}, 'val2': {None: ('new', None)},
'val4': {None: ('new', None)}, 'val4': {None: ('new', None)},
'val1': {None: ('new', None)}, 'val1': {None: ('new', None)},
'val3': {None: ('new2', None, True)}, 'val3': {None: ('new2', None, True)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.value.dict() cfg.value.dict()
compare(values.get_cached(), {'val1': {None: ('new', None)}, compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)}, 'val2': {None: ('new', None)},
'val3': {None: ('new2', None)}, 'val3': {None: ('new2', None)},
'val4': {None: ('new', None)}, 'val4': {None: ('new', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.option('val4').value.set('new3') cfg.option('val4').value.set('new3')
compare(values.get_cached(), {'val1': {None: ('new', None)}, compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)}, 'val2': {None: ('new', None)},
'val3': {None: ('new2', None)}, 'val3': {None: ('new2', None)},
'val4': {None: ('new3', None, True)}, 'val4': {None: ('new3', None, True)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.value.dict() cfg.value.dict()
compare(values.get_cached(), {'val1': {None: ('new', None)}, compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)}, 'val2': {None: ('new', None)},
'val3': {None: ('new2', None)}, 'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)}, 'val4': {None: ('new3', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
await cfg.option('val5').value.set([undefined, 'new4']) # assert not list_sessions()
compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)},
'val5': {None: (['yes', 'new4'], None)}})
await cfg.value.dict()
compare(values.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)},
'val5': {None: (['yes', 'new4'], None)}})
assert not await list_sessions()
@pytest.mark.asyncio def test_cache_leader_and_followers():
async def test_cache_leader_and_followers():
val1 = StrOption('val1', "", multi=True) val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True) val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2]) interface1 = Leadership('val1', '', [val1, val2])
od1 = OptionDescription('rootconfig', '', [interface1]) od1 = OptionDescription('rootconfig', '', [interface1])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.value.dict() cfg.value.dict()
global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']
val1_props = [] val1_props = []
val1_val1_props = ['empty', 'unique'] val1_val1_props = ['empty', 'unique']
@ -400,49 +374,49 @@ async def test_cache_leader_and_followers():
#None because no value #None because no value
idx_val2 = None idx_val2 = None
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
compare(settings.get_cached(), {None: {None: (global_props, None)}, compare(settings.get_cached(), {None: {None: (global_props, None)},
'val1': {None: (val1_props, None)}, 'val1': {None: (val1_props, None)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': {idx_val2: (val1_val2_props, None)}}) })
# len is 0 so don't get any value # len is 0 so don't get any value
compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) compare(values.get_cached(), {'val1.val1': {None: ([], None)}})
# #
await cfg.option('val1.val1').value.set([undefined]) cfg.option('val1.val1').value.set([None])
val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)}
compare(settings.get_cached(), {None: {None: (set(global_props), None)}, compare(settings.get_cached(), {None: {None: (set(global_props), None)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': val_val2_props}) })
compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}})
await cfg.value.dict() cfg.value.dict()
#has value #has value
idx_val2 = 0 idx_val2 = 0
val_val2 = None val_val2 = None
val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} val_val2_props = {idx_val2: (val1_val2_props, None)}
compare(settings.get_cached(), {None: {None: (global_props, None)}, compare(settings.get_cached(), {None: {None: (global_props, None)},
'val1': {None: (val1_props, None)}, 'val1': {None: (val1_props, None)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': val_val2_props}) 'val1.val2': val_val2_props})
compare(values.get_cached(), {'val1.val1': {None: ([None], None)}, compare(values.get_cached(), {'val1.val1': {None: ([None], None)},
'val1.val2': {idx_val2: (val_val2, None)}}) 'val1.val2': {idx_val2: (val_val2, None)},
await cfg.option('val1.val1').value.set([undefined, undefined]) })
await cfg.value.dict() cfg.option('val1.val1').value.set([None, None])
await cfg.option('val1.val2', 1).value.set('oui') cfg.value.dict()
cfg.option('val1.val2', 1).value.set('oui')
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}})
compare(values.get_cached(), {'val1.val2': {1: ('oui', None, True)}}) compare(values.get_cached(), {'val1.val2': {1: ('oui', None, True)}})
val1_val2_props = {0: (frozenset([]), None), 1: (frozenset([]), None)} val1_val2_props = {0: (frozenset([]), None), 1: (frozenset([]), None)}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_leader_callback():
async def test_cache_leader_callback():
val1 = StrOption('val1', "", multi=True) val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", Calculation(calc_value, Params(kwargs={'value': ParamOption(val1)})), multi=True) val2 = StrOption('val2', "", Calculation(calc_value, Params(kwargs={'value': ParamOption(val1)})), multi=True)
interface1 = Leadership('val1', '', [val1, val2]) interface1 = Leadership('val1', '', [val1, val2])
od1 = OptionDescription('rootconfig', '', [interface1]) od1 = OptionDescription('rootconfig', '', [interface1])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.value.dict() cfg.value.dict()
global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']
val1_props = [] val1_props = []
val1_val1_props = ['empty', 'unique'] val1_val1_props = ['empty', 'unique']
@ -452,24 +426,23 @@ async def test_cache_leader_callback():
val1_val1_props = frozenset(val1_val1_props) val1_val1_props = frozenset(val1_val1_props)
val1_val2_props = frozenset(val1_val2_props) val1_val2_props = frozenset(val1_val2_props)
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
compare(settings.get_cached(), {None: {None: (global_props, None)}, compare(settings.get_cached(), {None: {None: (global_props, None)},
'val1': {None: (val1_props, None)}, 'val1': {None: (val1_props, None)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': {None: (val1_val2_props, None)}}) })
compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) compare(values.get_cached(), {'val1.val1': {None: ([], None)}})
await cfg.option('val1.val1').value.set([undefined]) cfg.option('val1.val1').value.set([None])
compare(settings.get_cached(), {None: {None: (set(global_props), None)}, compare(settings.get_cached(), {None: {None: (set(global_props), None)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': {None: (val1_val2_props, None)}}) })
compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}})
await cfg.value.dict() cfg.value.dict()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_requires():
async def test_cache_requires():
a = BoolOption('activate_service', '', True) a = BoolOption('activate_service', '', True)
disabled_property = Calculation(calc_value, disabled_property = Calculation(calc_value,
Params(ParamValue('disabled'), Params(ParamValue('disabled'),
@ -478,52 +451,51 @@ async def test_cache_requires():
'default': ParamValue(None)})) 'default': ParamValue(None)}))
b = IPOption('ip_address_service', '', properties=(disabled_property,)) b = IPOption('ip_address_service', '', properties=(disabled_property,))
od1 = OptionDescription('service', '', [a, b]) od1 = OptionDescription('service', '', [a, b])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
assert await cfg.option('ip_address_service').value.get() == None assert cfg.option('ip_address_service').value.get() == None
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, compare(values.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}}) 'activate_service': {None: (True, None)}})
await cfg.value.dict() cfg.value.dict()
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, compare(values.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}}) 'activate_service': {None: (True, None)}})
await cfg.option('ip_address_service').value.set('1.1.1.1') cfg.option('ip_address_service').value.set('1.1.1.1')
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}}) 'activate_service': {None: (set([]), None)}})
compare(values.get_cached(), {'activate_service': {None: (True, None)}, 'ip_address_service': {None: ('1.1.1.1', None, True)}}) compare(values.get_cached(), {'activate_service': {None: (True, None)}, 'ip_address_service': {None: ('1.1.1.1', None, True)}})
await cfg.value.dict() cfg.value.dict()
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
compare(values.get_cached(), {'ip_address_service': {None: ('1.1.1.1', None)}, compare(values.get_cached(), {'ip_address_service': {None: ('1.1.1.1', None)},
'activate_service': {None: (True, None)}}) 'activate_service': {None: (True, None)}})
await cfg.option('activate_service').value.set(False) cfg.option('activate_service').value.set(False)
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}})
compare(values.get_cached(), {'activate_service': {None: (False, None)}}) compare(values.get_cached(), {'activate_service': {None: (False, None)}})
await cfg.value.dict() cfg.value.dict()
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set(['disabled']), None)}}) 'ip_address_service': {None: (set(['disabled']), None)}})
compare(values.get_cached(), {'activate_service': {None: (False, None)}}) compare(values.get_cached(), {'activate_service': {None: (False, None)}})
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_cache_global_properties():
async def test_cache_global_properties():
a = BoolOption('activate_service', '', True) a = BoolOption('activate_service', '', True)
disabled_property = Calculation(calc_value, disabled_property = Calculation(calc_value,
Params(ParamValue('disabled'), Params(ParamValue('disabled'),
@ -532,79 +504,77 @@ async def test_cache_global_properties():
'default': ParamValue(None)})) 'default': ParamValue(None)}))
b = IPOption('ip_address_service', '', properties=(disabled_property,)) b = IPOption('ip_address_service', '', properties=(disabled_property,))
od1 = OptionDescription('service', '', [a, b]) od1 = OptionDescription('service', '', [a, b])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
values = cfg._config_bag.context._impl_values_cache values = cfg._config_bag.context._impl_values_cache
settings = cfg._config_bag.context._impl_properties_cache settings = cfg._config_bag.context.properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
assert await cfg.option('ip_address_service').value.get() == None assert cfg.option('ip_address_service').value.get() == None
compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, compare(values.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}}) 'activate_service': {None: (True, None)}})
await cfg.property.pop('disabled') cfg.property.remove('disabled')
assert await cfg.option('ip_address_service').value.get() == None assert cfg.option('ip_address_service').value.get() == None
compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
await cfg.property.add('test') cfg.property.add('test')
assert await cfg.option('ip_address_service').value.get() == None assert cfg.option('ip_address_service').value.get() == None
compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'test', 'force_store_value']), None)}, compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'test', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}, 'activate_service': {None: (set([]), None)},
'ip_address_service': {None: (set([]), None)}}) 'ip_address_service': {None: (set([]), None)}})
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_value_incr():
async def test_callback_value_incr():
global incr global incr
incr = -1 incr = -1
val1 = IntOption('val1', "", Calculation(return_incr), properties=('expire',)) val1 = IntOption('val1', "", Calculation(return_incr), properties=('expire',))
val2 = IntOption('val2', "", Calculation(calc_value, Params(ParamOption(val1)))) val2 = IntOption('val2', "", Calculation(calc_value, Params(ParamOption(val1))))
od1 = OptionDescription('rootconfig', '', [val1, val2]) od1 = OptionDescription('rootconfig', '', [val1, val2])
async with await Config(od1) as cfg: cfg = Config(od1)
assert await cfg.cache.get_expiration_time() == 5 assert cfg.cache.get_expiration_time() == 5
await cfg.cache.set_expiration_time(1) cfg.cache.set_expiration_time(1)
assert await cfg.cache.get_expiration_time() == 1 assert cfg.cache.get_expiration_time() == 1
await cfg.property.read_write() cfg.property.read_write()
assert await cfg.option('val1').value.get() == 1 assert cfg.option('val1').value.get() == 1
sleep(1) sleep(1)
assert await cfg.option('val2').value.get() == 1 assert cfg.option('val2').value.get() == 1
sleep(1) sleep(1)
assert await cfg.option('val1').value.get() == 1 assert cfg.option('val1').value.get() == 1
assert await cfg.option('val2').value.get() == 1 assert cfg.option('val2').value.get() == 1
sleep(2) sleep(2)
assert await cfg.option('val1').value.get() == 2 assert cfg.option('val1').value.get() == 2
assert await cfg.option('val2').value.get() == 2 assert cfg.option('val2').value.get() == 2
assert await cfg.option('val1').value.get() == 2 assert cfg.option('val1').value.get() == 2
assert await cfg.option('val2').value.get() == 2 assert cfg.option('val2').value.get() == 2
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_value_incr_demoting():
async def test_callback_value_incr_demoting():
global incr global incr
incr = -1 incr = -1
val1 = IntOption('val1', "", Calculation(return_incr), properties=('expire',)) val1 = IntOption('val1', "", Calculation(return_incr), properties=('expire',))
val2 = IntOption('val2', "", Calculation(calc_value, Params(ParamOption(val1)))) val2 = IntOption('val2', "", Calculation(calc_value, Params(ParamOption(val1))))
od1 = OptionDescription('rootconfig', '', [val1, val2]) od1 = OptionDescription('rootconfig', '', [val1, val2])
async with await Config(od1) as cfg: cfg = Config(od1)
await cfg.property.add('demoting_error_warning') cfg.property.add('demoting_error_warning')
assert await cfg.cache.get_expiration_time() == 5 assert cfg.cache.get_expiration_time() == 5
await cfg.cache.set_expiration_time(1) cfg.cache.set_expiration_time(1)
assert await cfg.cache.get_expiration_time() == 1 assert cfg.cache.get_expiration_time() == 1
await cfg.property.read_write() cfg.property.read_write()
assert await cfg.option('val1').value.get() == 1 assert cfg.option('val1').value.get() == 1
sleep(1) sleep(1)
assert await cfg.option('val2').value.get() == 1 assert cfg.option('val2').value.get() == 1
sleep(1) sleep(1)
assert await cfg.option('val1').value.get() == 1 assert cfg.option('val1').value.get() == 1
assert await cfg.option('val2').value.get() == 1 assert cfg.option('val2').value.get() == 1
sleep(2) sleep(2)
assert await cfg.option('val1').value.get() == 2 assert cfg.option('val1').value.get() == 2
assert await cfg.option('val2').value.get() == 2 assert cfg.option('val2').value.get() == 2
assert await cfg.option('val1').value.get() == 2 assert cfg.option('val1').value.get() == 2
assert await cfg.option('val2').value.get() == 2 assert cfg.option('val2').value.get() == 2
assert not await list_sessions() # assert not list_sessions()

View file

@ -1,13 +1,12 @@
# coding: utf-8 # coding: utf-8
from py.test import raises from py.test import raises
import pytest
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config, value_list, global_owner, event_loop from .config import config_type, get_config, value_list, global_owner
from tiramisu import ChoiceOption, StrOption, OptionDescription, Config, owners, Calculation, \ from tiramisu import ChoiceOption, StrOption, OptionDescription, Config, owners, Calculation, \
undefined, Params, ParamValue, ParamOption, list_sessions undefined, Params, ParamValue, ParamOption
from tiramisu.error import ConfigError from tiramisu.error import ConfigError
@ -27,155 +26,146 @@ def return_error(*args, **kwargs):
raise Exception('test') raise Exception('test')
@pytest.mark.asyncio def test_choiceoption(config_type):
async def test_choiceoption(config_type):
choice = ChoiceOption('choice', '', values=('val1', 'val2')) choice = ChoiceOption('choice', '', values=('val1', 'val2'))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
owner = await global_owner(cfg, config_type) owner = global_owner(cfg, config_type)
assert await cfg.option('choice').owner.get() == owners.default assert cfg.option('choice').owner.get() == owners.default
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
assert not await cfg.option('choice').owner.isdefault() assert not cfg.option('choice').owner.isdefault()
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.get() == owners.default assert cfg.option('choice').owner.get() == owners.default
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.get() == owners.default assert cfg.option('choice').owner.get() == owners.default
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') assert value_list(cfg.option('choice').value.list()) == ('val1', 'val2')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_function(config_type):
async def test_choiceoption_function(config_type):
choice = ChoiceOption('choice', '', values=Calculation(return_list)) choice = ChoiceOption('choice', '', values=Calculation(return_list))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
owner = await global_owner(cfg, config_type) owner = global_owner(cfg, config_type)
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') assert value_list(cfg.option('choice').value.list()) == ('val1', 'val2')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_function_error():
async def test_choiceoption_function_error():
choice = ChoiceOption('choice', '', values=Calculation(return_error)) choice = ChoiceOption('choice', '', values=Calculation(return_error))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(ConfigError): with raises(ConfigError):
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_function_error_args():
async def test_choiceoption_function_error_args():
choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(ParamValue('val1')))) choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(ParamValue('val1'))))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(ConfigError): with raises(ConfigError):
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_function_error_kwargs():
async def test_choiceoption_function_error_kwargs():
choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(kwargs={'kwargs': ParamValue('val1')}))) choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(kwargs={'kwargs': ParamValue('val1')})))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(ConfigError): with raises(ConfigError):
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_calc_function(config_type):
async def test_choiceoption_calc_function(config_type):
choice = ChoiceOption('choice', "", values=Calculation(return_calc_list, Params(ParamValue('val1')))) choice = ChoiceOption('choice', "", values=Calculation(return_calc_list, Params(ParamValue('val1'))))
odesc = OptionDescription('od', '', [choice]) od1 = OptionDescription('od', '', [choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
owner = await global_owner(cfg, config_type) owner = global_owner(cfg, config_type)
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_calc_opt_function(config_type):
async def test_choiceoption_calc_opt_function(config_type):
str_ = StrOption('str', '', 'val1') str_ = StrOption('str', '', 'val1')
choice = ChoiceOption('choice', choice = ChoiceOption('choice',
"", "",
values=Calculation(return_calc_list, Params(ParamOption(str_)))) values=Calculation(return_calc_list, Params(ParamOption(str_))))
odesc = OptionDescription('od', '', [str_, choice]) od1 = OptionDescription('od', '', [str_, choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
await cfg.option('choice').value.set('val1') cfg.option('choice').value.set('val1')
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_calc_opt_function_propertyerror():
async def test_choiceoption_calc_opt_function_propertyerror():
str_ = StrOption('str', '', 'val1', properties=('disabled',)) str_ = StrOption('str', '', 'val1', properties=('disabled',))
choice = ChoiceOption('choice', choice = ChoiceOption('choice',
"", "",
values=Calculation(return_calc_list, Params(ParamOption(str_)))) values=Calculation(return_calc_list, Params(ParamOption(str_))))
odesc = OptionDescription('od', '', [str_, choice]) od1 = OptionDescription('od', '', [str_, choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(ConfigError): with raises(ConfigError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert not await list_sessions() # assert not list_sessions()
#def test_choiceoption_calc_opt_multi_function(config_type): #def test_choiceoption_calc_opt_multi_function(config_type):
@pytest.mark.asyncio def test_choiceoption_calc_opt_multi_function():
async def test_choiceoption_calc_opt_multi_function():
# FIXME # FIXME
config_type = 'tiramisu' config_type = 'tiramisu'
str_ = StrOption('str', '', ['val1'], multi=True) str_ = StrOption('str', '', ['val1'], multi=True)
@ -189,37 +179,36 @@ async def test_choiceoption_calc_opt_multi_function():
default=['val2'], default=['val2'],
values=Calculation(return_val, Params(ParamOption(str_))), values=Calculation(return_val, Params(ParamOption(str_))),
multi=True) multi=True)
odesc = OptionDescription('od', '', [str_, choice, ch2]) od1 = OptionDescription('od', '', [str_, choice, ch2])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
cfg = await get_config(cfg, config_type, True) cfg = get_config(cfg, config_type, True)
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
assert await cfg.option('choice').value.get() == [] assert cfg.option('choice').value.get() == []
# #
await cfg.option('choice').value.set(['val1']) cfg.option('choice').value.set(['val1'])
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set([undefined]) cfg.option('choice').value.set([undefined])
# #
await cfg.option('choice').value.set(['val1']) cfg.option('choice').value.set(['val1'])
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('ch2').value.get() cfg.option('ch2').value.get()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_calc_opt_multi_function_kwargs(config_type):
async def test_choiceoption_calc_opt_multi_function_kwargs(config_type):
str_ = StrOption('str', '', ['val1'], multi=True) str_ = StrOption('str', '', ['val1'], multi=True)
choice = ChoiceOption('choice', choice = ChoiceOption('choice',
"", "",
@ -231,46 +220,45 @@ async def test_choiceoption_calc_opt_multi_function_kwargs(config_type):
default=['val2'], default=['val2'],
values=Calculation(return_val, Params(kwargs={'val': ParamOption(str_)})), values=Calculation(return_val, Params(kwargs={'val': ParamOption(str_)})),
multi=True) multi=True)
odesc = OptionDescription('od', '', [str_, choice, ch2]) od1 = OptionDescription('od', '', [str_, choice, ch2])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
# FIXME cfg = await get_config(cfg, config_type) # FIXME cfg = get_config(cfg, config_type)
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
assert await cfg.option('choice').value.get() == [] assert cfg.option('choice').value.get() == []
# #
await cfg.option('choice').value.set(['val1']) cfg.option('choice').value.set(['val1'])
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set([undefined]) cfg.option('choice').value.set([undefined])
# #
await cfg.option('choice').value.set(['val1']) cfg.option('choice').value.set(['val1'])
assert await cfg.option('choice').owner.get() == owner assert cfg.option('choice').owner.get() == owner
# #
await cfg.option('choice').value.reset() cfg.option('choice').value.reset()
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('choice').value.set('no') cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault() assert cfg.option('choice').owner.isdefault()
# #
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('ch2').value.get() cfg.option('ch2').value.get()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choiceoption_calc_not_list():
async def test_choiceoption_calc_not_list():
str_ = StrOption('str', '', 'val1') str_ = StrOption('str', '', 'val1')
choice = ChoiceOption('choice', choice = ChoiceOption('choice',
"", "",
default_multi='val2', default_multi='val2',
values=Calculation(return_val, Params(ParamOption(str_))), values=Calculation(return_val, Params(ParamOption(str_))),
multi=True) multi=True)
odesc = OptionDescription('od', '', [str_, choice]) od1 = OptionDescription('od', '', [str_, choice])
async with await Config(odesc) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(ConfigError): with raises(ConfigError):
await cfg.option('choice').value.set(['val1']) cfg.option('choice').value.set(['val1'])
assert not await list_sessions() # assert not list_sessions()

View file

@ -6,16 +6,14 @@ import weakref
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config, value_list, global_owner, event_loop from .config import config_type, get_config, value_list, global_owner
import pytest import pytest
from tiramisu import Config from tiramisu import Config
from tiramisu.config import SubConfig
from tiramisu.i18n import _ from tiramisu.i18n import _
from tiramisu import Config, IntOption, FloatOption, ChoiceOption, \ from tiramisu import Config, IntOption, FloatOption, ChoiceOption, \
BoolOption, StrOption, SymLinkOption, OptionDescription, undefined, delete_session BoolOption, StrOption, SymLinkOption, OptionDescription, undefined
from tiramisu.error import ConflictError, ConfigError, PropertiesOptionError, APIError from tiramisu.error import ConflictError, ConfigError, PropertiesOptionError
from tiramisu.storage import list_sessions
def make_description(): def make_description():
@ -41,203 +39,215 @@ def make_description():
return descr return descr
@pytest.mark.asyncio def test_base_config(config_type):
async def test_base_config(config_type):
"""making a :class:`tiramisu.config.Config()` object """making a :class:`tiramisu.config.Config()` object
and a :class:`tiramisu.option.OptionDescription()` object and a :class:`tiramisu.option.OptionDescription()` object
""" """
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.config.type() == 'config'
#dmo = await cfg.unwrap_from_path('dummy')
#assert dmo.impl_getname() == 'dummy'
assert not await list_sessions()
@pytest.mark.asyncio def test_base_config_name():
async def test_base_config_name():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr, session_id='cfg') as cfg: cfg = Config(od1)
await cfg.session.id() == 'cfg'
#raises(ValueError, "Config(descr, session_id='unvalid name')") #raises(ValueError, "Config(descr, session_id='unvalid name')")
assert not await list_sessions() # assert not list_sessions()
#
#
#@pytest.mark.asyncio
#async def test_not_config():
# assert raises(TypeError, "Config('str')")
@pytest.mark.asyncio def test_base_path():
async def test_base_path():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
base = OptionDescription('config', '', [descr]) base = OptionDescription('config', '', [od1])
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
async with await Config(base, session_id='error'): with Config(base):
pass pass
await delete_session('error') # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_base_config_force_permissive():
async def test_base_config_force_permissive(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() cfg.permissive.add('hidden')
await cfg.permissive.add('hidden')
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('boolop').value.get() cfg.option('boolop').value.get()
assert await cfg.forcepermissive.option('boolop').value.get() is True assert cfg.forcepermissive.option('boolop').value.get() is True
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_base_config_in_a_tree():
async def test_base_config_in_a_tree():
# FIXME # FIXME
config_type = 'tiramisu' config_type = 'tiramisu'
"how options are organized into a tree, see :ref:`tree`" "how options are organized into a tree, see :ref:`tree`"
descr = make_description() od1 = make_description()
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
# #
await cfg.option('bool').value.set(False) cfg.option('bool').value.set(False)
# #
assert await cfg.option('gc.name').value.get() == 'ref' assert cfg.option('gc.name').value.get() == 'ref'
await cfg.option('gc.name').value.set('framework') cfg.option('gc.name').value.set('framework')
assert await cfg.option('gc.name').value.get() == 'framework' assert cfg.option('gc.name').value.get() == 'framework'
# #
assert await cfg.option('objspace').value.get() == 'std' assert cfg.option('objspace').value.get() == 'std'
await cfg.option('objspace').value.set('thunk') cfg.option('objspace').value.set('thunk')
assert await cfg.option('objspace').value.get() == 'thunk' assert cfg.option('objspace').value.get() == 'thunk'
# #
assert await cfg.option('gc.float').value.get() == 2.3 assert cfg.option('gc.float').value.get() == 2.3
await cfg.option('gc.float').value.set(3.4) cfg.option('gc.float').value.set(3.4)
assert await cfg.option('gc.float').value.get() == 3.4 assert cfg.option('gc.float').value.get() == 3.4
# #
assert await cfg.option('int').value.get() == 0 assert cfg.option('int').value.get() == 0
await cfg.option('int').value.set(123) cfg.option('int').value.set(123)
assert await cfg.option('int').value.get() == 123 assert cfg.option('int').value.get() == 123
# #
assert await cfg.option('wantref').value.get() is False assert cfg.option('wantref').value.get() is False
await cfg.option('wantref').value.set(True) cfg.option('wantref').value.set(True)
assert await cfg.option('wantref').value.get() is True assert cfg.option('wantref').value.get() is True
# #
assert await cfg.option('str').value.get() == 'abc' assert cfg.option('str').value.get() == 'abc'
await cfg.option('str').value.set('def') cfg.option('str').value.set('def')
assert await cfg.option('str').value.get() == 'def' assert cfg.option('str').value.get() == 'def'
# #
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
await cfg.option('gc.foo').value.get() cfg.option('gc.foo').value.get()
## ##
async with await Config(descr) as cfg: cfg = Config(od1)
assert await cfg.option('bool').value.get() is True assert cfg.option('bool').value.get() is True
assert await cfg.option('gc.name').value.get() == 'ref' assert cfg.option('gc.name').value.get() == 'ref'
assert await cfg.option('wantframework').value.get() is False assert cfg.option('wantframework').value.get() is False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_not_valid_properties():
async def test_not_valid_properties():
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
stroption = StrOption('str', 'Test string option', default='abc', properties='mandatory') stroption = StrOption('str', 'Test string option', default='abc', properties='mandatory')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_information_config():
async def test_information_config(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg:
string = 'some informations' string = 'some informations'
# #
assert list(await cfg.information.list()) == ['doc'] assert list(cfg.information.list()) == ['doc']
await cfg.information.set('info', string) cfg.information.set('info', string)
assert await cfg.information.get('info') == string assert cfg.information.get('info') == string
assert set(await cfg.information.list()) == {'doc', 'info'} assert set(cfg.information.list()) == {'doc', 'info'}
# #
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.information.get('noinfo') cfg.information.get('noinfo')
assert await cfg.information.get('noinfo', 'default') == 'default' assert cfg.information.get('noinfo', 'default') == 'default'
await cfg.information.reset('info') cfg.information.reset('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.information.get('info') cfg.information.get('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.information.reset('noinfo') cfg.information.reset('noinfo')
assert list(await cfg.information.list()) == ['doc'] assert list(cfg.information.list()) == ['doc']
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_information_config_list():
async def test_information_option(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: string = 'some informations'
cfg.information.set('info', string)
#
assert cfg.information.exportation() == {None: {'info': string}}
assert set(cfg.information.list()) == {'info', 'doc'}
def test_information_exportation():
od1 = make_description()
cfg = Config(od1)
string = 'some informations'
cfg.information.set('info', string)
#
assert cfg.information.exportation() == {None: {'info': string}}
def test_information_importation():
od1 = make_description()
cfg = Config(od1)
string = 'some informations'
assert cfg.information.exportation() == {}
#
cfg.information.importation({None: {'info': string}})
assert cfg.information.exportation() == {None: {'info': string}}
def test_information_option():
od1 = make_description()
cfg = Config(od1)
string = 'some informations' string = 'some informations'
# #
assert list(await cfg.option('gc.name').information.list()) == ['doc'] assert list(cfg.option('gc.name').information.list()) == ['doc']
await cfg.option('gc.name').information.set('info', string) cfg.option('gc.name').information.set('info', string)
assert await cfg.option('gc.name').information.get('info') == string assert cfg.option('gc.name').information.get('info') == string
assert set(await cfg.option('gc.name').information.list()) == {'doc', 'info'} assert set(cfg.option('gc.name').information.list()) == {'doc', 'info'}
# #
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc.name').information.get('noinfo') cfg.option('gc.name').information.get('noinfo')
assert await cfg.option('gc.name').information.get('noinfo', 'default') == 'default' assert cfg.option('gc.name').information.get('noinfo', 'default') == 'default'
await cfg.option('gc.name').information.reset('info') cfg.option('gc.name').information.reset('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc.name').information.get('info') cfg.option('gc.name').information.get('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc.name').information.reset('noinfo') cfg.option('gc.name').information.reset('noinfo')
assert list(await cfg.option('gc.name').information.list()) == ['doc'] assert list(cfg.option('gc.name').information.list()) == ['doc']
# #
assert await cfg.option('wantref').information.get('info') == 'default value' assert cfg.option('wantref').information.get('info') == 'default value'
await cfg.option('wantref').information.set('info', 'default value') cfg.option('wantref').information.set('info', 'default value')
assert await cfg.option('wantref').information.get('info') == 'default value' assert cfg.option('wantref').information.get('info') == 'default value'
await cfg.option('wantref').information.reset('info') cfg.option('wantref').information.reset('info')
assert await cfg.option('wantref').information.get('info') == 'default value' assert cfg.option('wantref').information.get('info') == 'default value'
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_information_option_2():
async def test_information_optiondescription(): i1 = IntOption('test1', '')
descr = make_description() i1.impl_set_information('info', 'value')
async with await Config(descr) as cfg: # it's a dict
assert set(i1.impl_list_information()) == {'info', 'doc'}
od1 = OptionDescription('test', '', [i1])
cfg = Config(od1)
# it's tuples
assert set(cfg.option('test1').information.list()) == {'info', 'doc'}
# assert not list_sessions()
def test_information_optiondescription():
od1 = make_description()
cfg = Config(od1)
string = 'some informations' string = 'some informations'
# #
assert list(await cfg.option('gc').information.list()) == ['doc'] assert list(cfg.option('gc').information.list()) == ['doc']
await cfg.option('gc').information.set('info', string) cfg.option('gc').information.set('info', string)
assert await cfg.option('gc').information.get('info') == string assert cfg.option('gc').information.get('info') == string
assert set(await cfg.option('gc').information.list()) == {'doc', 'info'} assert set(cfg.option('gc').information.list()) == {'doc', 'info'}
# #
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc').information.get('noinfo') cfg.option('gc').information.get('noinfo')
assert await cfg.option('gc').information.get('noinfo', 'default') == 'default' assert cfg.option('gc').information.get('noinfo', 'default') == 'default'
await cfg.option('gc').information.reset('info') cfg.option('gc').information.reset('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc').information.get('info') cfg.option('gc').information.get('info')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('gc').information.reset('noinfo') cfg.option('gc').information.reset('noinfo')
assert list(await cfg.option('gc').information.list()) == ['doc'] assert list(cfg.option('gc').information.list()) == ['doc']
assert not await list_sessions() # assert not list_sessions()
def compare(val1, val2): def compare(val1, val2):
assert len(val1[0]) == len(val2[0]) assert val1 == val2
for idx1, val_1 in enumerate(val1[0]):
idx2 = val2[0].index(val_1)
assert val1[0][idx1] == val2[0][idx2]
assert val1[1][idx1] == val2[1][idx2]
if isinstance(val2[2][idx2], tuple):
assert val2[2][idx2] == tuple(val1[2][idx1])
else:
assert val2[2][idx2] == val1[2][idx1]
assert val1[3][idx1] == val2[3][idx2]
@pytest.mark.asyncio def test_get_modified_values():
async def test_get_modified_values():
g1 = IntOption('g1', '', 1) g1 = IntOption('g1', '', 1)
g2 = StrOption('g2', '', 'héhé') g2 = StrOption('g2', '', 'héhé')
g3 = StrOption('g3', '', 'héhé') g3 = StrOption('g3', '', 'héhé')
@ -245,211 +255,187 @@ async def test_get_modified_values():
g5 = StrOption('g5', '') g5 = StrOption('g5', '')
g6 = StrOption('g6', '', multi=True) g6 = StrOption('g6', '', multi=True)
d1 = OptionDescription('od', '', [g1, g2, g3, g4, g5, g6]) d1 = OptionDescription('od', '', [g1, g2, g3, g4, g5, g6])
root = OptionDescription('root', '', [d1]) od1 = OptionDescription('root', '', [d1])
async with await Config(root) as cfg: cfg = Config(od1)
compare(await cfg.value.exportation(), ((), (), (), ())) compare(cfg.value.exportation(), {})
assert not await cfg.option('od.g5').option.ismulti() assert not cfg.option('od.g5').ismulti()
assert not await cfg.option('od.g5').option.issubmulti() assert not cfg.option('od.g5').issubmulti()
await cfg.option('od.g5').value.set('yes') cfg.option('od.g5').value.set('yes')
compare(await cfg.value.exportation(), (('od.g5',), (None,), ('yes',), ('user',))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}})
await cfg.option('od.g4').value.set(False) cfg.option('od.g4').value.set(False)
compare(await cfg.value.exportation(), (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g4': {None: [False, 'user']}})
await cfg.option('od.g4').value.set(undefined) cfg.option('od.g4').value.set(True)
compare(await cfg.value.exportation(), (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g4': {None: [True, 'user']}})
await cfg.option('od.g4').value.reset() cfg.option('od.g4').value.reset()
compare(await cfg.value.exportation(), (('od.g5',), (None,), ('yes',), ('user',))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}})
assert await cfg.option('od.g6').option.ismulti() assert cfg.option('od.g6').ismulti()
await cfg.option('od.g6').value.set([undefined]) cfg.option('od.g6').value.set([None])
compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g6': {None: [[None], 'user']}})
await cfg.option('od.g6').value.set([]) cfg.option('od.g6').value.set([])
compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g6': {None: [[], 'user']}})
await cfg.option('od.g6').value.set(['3']) cfg.option('od.g6').value.set(['3'])
compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g6': {None: [['3'], 'user']}})
await cfg.option('od.g6').value.set([]) cfg.option('od.g6').value.set([])
compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))) compare(cfg.value.exportation(), {'od.g5': {None: ['yes', 'user']}, 'od.g6': {None: [[], 'user']}})
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_get_modified_values_not_modif(config_type):
async def test_get_modified_values_not_modif(config_type):
g1 = StrOption('g1', '', multi=True) g1 = StrOption('g1', '', multi=True)
d1 = OptionDescription('od', '', [g1]) d1 = OptionDescription('od', '', [g1])
root = OptionDescription('root', '', [d1]) od1 = OptionDescription('root', '', [d1])
async with await Config(root) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('od.g1').value.get() == [] assert cfg.option('od.g1').value.get() == []
value = await cfg.option('od.g1').value.get() value = cfg.option('od.g1').value.get()
value.append('val') value.append('val')
assert await cfg.option('od.g1').value.get() == [] assert cfg.option('od.g1').value.get() == []
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_duplicated_option():
async def test_duplicated_option():
g1 = IntOption('g1', '', 1) g1 = IntOption('g1', '', 1)
g1 g1
#in same OptionDescription #in same OptionDescription
with pytest.raises(ConflictError): with pytest.raises(ConflictError):
d1 = OptionDescription('od', '', [g1, g1]) d1 = OptionDescription('od', '', [g1, g1])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_duplicated_option_diff_od():
async def test_duplicated_option_diff_od():
g1 = IntOption('g1', '', 1) g1 = IntOption('g1', '', 1)
d1 = OptionDescription('od1', '', [g1]) d1 = OptionDescription('od1', '', [g1])
#in different OptionDescription #in different OptionDescription
d2 = OptionDescription('od2', '', [g1, d1]) d2 = OptionDescription('od2', '', [g1, d1])
d2 d2
with pytest.raises(ConflictError): with pytest.raises(ConflictError):
await Config(d2, session_id='error') Config(d2)
await delete_session('error')
assert not await list_sessions()
@pytest.mark.asyncio def test_cannot_assign_value_to_option_description():
async def test_cannot_assign_value_to_option_description(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: with pytest.raises(ConfigError):
with pytest.raises(APIError): cfg.option('gc').value.set(3)
await cfg.option('gc').value.set(3) # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_config_multi(config_type):
async def test_config_multi(config_type):
i1 = IntOption('test1', '', multi=True) i1 = IntOption('test1', '', multi=True)
i2 = IntOption('test2', '', multi=True, default_multi=1) i2 = IntOption('test2', '', multi=True, default_multi=1)
i3 = IntOption('test3', '', default=[2], multi=True, default_multi=1) i3 = IntOption('test3', '', default=[2], multi=True, default_multi=1)
od = OptionDescription('test', '', [i1, i2, i3]) od1 = OptionDescription('test', '', [i1, i2, i3])
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('test1').value.get() == [] assert cfg.option('test1').value.get() == []
assert await cfg.option('test2').value.get() == [] assert cfg.option('test2').value.get() == []
await cfg.option('test2').value.set([undefined]) cfg.option('test2').value.set([1])
assert await cfg.option('test2').value.get() == [1] assert cfg.option('test2').value.get() == [1]
assert await cfg.option('test3').value.get() == [2] assert cfg.option('test3').value.get() == [2]
await cfg.option('test3').value.set([undefined, undefined]) cfg.option('test3').value.set([2, 1])
assert await cfg.option('test3').value.get() == [2, 1] assert cfg.option('test3').value.get() == [2, 1]
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_prefix_error():
async def test_prefix_error():
i1 = IntOption('test1', '') i1 = IntOption('test1', '')
od = OptionDescription('test', '', [i1]) od1 = OptionDescription('test', '', [i1])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.option('test1').value.set(1) cfg.option('test1').value.set(1)
try: try:
await cfg.option('test1').value.set('yes') cfg.option('test1').value.set('yes')
except Exception as err: except Exception as err:
assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('yes', _('integer'), 'test1') assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('yes', _('integer'), 'test1')
try: try:
await cfg.option('test1').value.set('yes') cfg.option('test1').value.set('yes')
except Exception as err: except Exception as err:
err.prefix = '' err.prefix = ''
assert str(err) == _('invalid value') assert str(err) == _('invalid value')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_no_validation():
async def test_no_validation():
# FIXME # FIXME
config_type = 'tiramisu' config_type = 'tiramisu'
i1 = IntOption('test1', '') i1 = IntOption('test1', '')
od = OptionDescription('test', '', [i1]) od1 = OptionDescription('test', '', [i1])
async with await Config(od) as config: cfg = Config(od1)
await config.property.read_write() cfg.property.read_write()
cfg = await get_config(config, config_type) cfg = get_config(cfg, config_type)
await cfg.option('test1').value.set(1) cfg.option('test1').value.set(1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('test1').value.set('yes') cfg.option('test1').value.set('yes')
assert await cfg.option('test1').value.get() == 1 assert cfg.option('test1').value.get() == 1
await config.property.pop('validator') cfg.property.remove('validator')
cfg = await get_config(config, config_type) cfg = get_config(cfg, config_type)
await cfg.option('test1').value.set('yes') cfg.option('test1').value.set('yes')
assert await cfg.option('test1').value.get() == 'yes' assert cfg.option('test1').value.get() == 'yes'
await cfg.property.add('validator') cfg.property.add('validator')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('test1').value.get() cfg.option('test1').value.get()
await cfg.option('test1').value.reset() cfg.option('test1').value.reset()
assert await cfg.option('test1').value.get() is None assert cfg.option('test1').value.get() is None
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio #def test_subconfig():
async def test_subconfig(): # i = IntOption('i', '')
i = IntOption('i', '') # o = OptionDescription('val', '', [i])
o = OptionDescription('val', '', [i]) # od1 = OptionDescription('val', '', [o])
o2 = OptionDescription('val', '', [o]) # cfg = Config(od1)
async with await Config(o2) as cfg: # cfg
cfg # with pytest.raises(TypeError):
with pytest.raises(TypeError): # SubConfig(i, weakref.ref(cfg))
await SubConfig(i, weakref.ref(cfg)) # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_config_subconfig():
async def test_config_subconfig():
i1 = IntOption('i1', '') i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1) i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '') i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2) i4 = IntOption('i4', '', default=2)
od1 = OptionDescription('od1', '', [i1, i2, i3, i4]) od1 = OptionDescription('od1', '', [i1, i2, i3, i4])
od2 = OptionDescription('od2', '', [od1]) od2 = OptionDescription('od2', '', [od1])
async with await Config(od2, session_id='conf1') as cfg: cfg = Config(od2)
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
conf2 = await Config(od1, session_id='conf2') cfg2 = Config(od1)
await delete_session('conf2') # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_config_od_name(config_type):
async def test_config_invalidsession():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
with pytest.raises(ValueError):
await Config(o2, session_id=2)
assert not await list_sessions()
@pytest.mark.asyncio
async def test_config_od_name(config_type):
i = IntOption('i', '') i = IntOption('i', '')
s = SymLinkOption('s', i) s = SymLinkOption('s', i)
o = OptionDescription('val', '', [i, s]) o = OptionDescription('val', '', [i, s])
o2 = OptionDescription('val', '', [o]) o2 = OptionDescription('val', '', [o])
async with await Config(o2) as cfg: cfg = Config(o2)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('val.i').option.name() == 'i' assert cfg.option('val.i').name() == 'i'
assert await cfg.option('val.s').option.name() == 's' assert cfg.option('val.s').name() == 's'
assert await cfg.option('val.s').option.name(follow_symlink=True) == 'i' assert cfg.option('val.s').type() == _('integer')
assert not await list_sessions() assert cfg.option('val').type() == 'optiondescription'
# assert not list_sessions()
@pytest.mark.asyncio def test_config_od_type(config_type):
async def test_config_od_type(config_type):
i = IntOption('i', '') i = IntOption('i', '')
o = OptionDescription('val', '', [i]) o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o]) o2 = OptionDescription('val', '', [o])
async with await Config(o2) as cfg: cfg = Config(o2)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('val').option.type() == 'optiondescription' assert cfg.option('val').type() == 'optiondescription'
assert await cfg.option('val.i').option.type() == 'integer' assert cfg.option('val.i').type() == _('integer')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_config_default(config_type):
async def test_config_default(config_type):
i = IntOption('i', '', 8) i = IntOption('i', '', 8)
o = OptionDescription('val', '', [i]) o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o]) o2 = OptionDescription('val', '', [o])
async with await Config(o2) as cfg: cfg = Config(o2)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('val.i').value.default() == 8 assert cfg.option('val.i').value.default() == 8
await cfg.option('val.i').value.set(9) cfg.option('val.i').value.set(9)
assert await cfg.option('val.i').value.get() == 9 assert cfg.option('val.i').value.get() == 9
assert await cfg.option('val.i').value.default() == 8 assert cfg.option('val.i').value.default() == 8
assert not await list_sessions() # assert not list_sessions()

View file

@ -1,16 +1,15 @@
"configuration objects global API" "configuration objects global API"
import pytest from pytest import raises
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config, value_list, global_owner, event_loop from .config import config_type, get_config, value_list, global_owner
from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \ from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, FilenameOption, SymLinkOption, IPOption, \ BoolOption, FilenameOption, SymLinkOption, IPOption, \
PortOption, NetworkOption, NetmaskOption, BroadcastOption, \ PortOption, NetworkOption, NetmaskOption, BroadcastOption, \
DomainnameOption, OptionDescription DomainnameOption, OptionDescription
from tiramisu.error import PropertiesOptionError, ValueWarning from tiramisu.error import PropertiesOptionError, ValueWarning, ConfigError
from tiramisu.storage import list_sessions
import warnings import warnings
@ -52,50 +51,73 @@ def _is_same_opt(opt1, opt2):
assert opt1 == opt2 assert opt1 == opt2
@pytest.mark.asyncio def test_od_not_list():
async def test_od_not_list():
b = BoolOption('bool', '', multi=True) b = BoolOption('bool', '', multi=True)
with pytest.raises(AssertionError): with raises(AssertionError):
OptionDescription('od', '', b) OptionDescription('od', '', b)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_str():
async def test_str(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg:
cfg # does not crash cfg # does not crash
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_make_dict(config_type):
async def test_make_dict(config_type):
"serialization of the whole config to a dict" "serialization of the whole config to a dict"
descr = OptionDescription("opt", "", [ od1 = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('hidden',))]), BoolOption("b", "", default=False, properties=('hidden',))]),
IntOption("int", "", default=42)]) IntOption("int", "", default=42)])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.permissive.add('hidden') cfg.permissive.add('hidden')
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
d = await cfg.value.dict() d = cfg.value.dict()
assert d == {"s1.a": False, "int": 42} assert d == {"s1.a": False, "int": 42}
await cfg.option('int').value.set(43) cfg.option('int').value.set(43)
await cfg.option('s1.a').value.set(True) cfg.option('s1.a').value.set(True)
d = await cfg.value.dict() d = cfg.value.dict()
assert d == {"s1.a": True, "int": 43} assert d == {"s1.a": True, "int": 43}
d2 = await cfg.value.dict(flatten=True)
assert d2 == {'a': True, 'int': 43}
if config_type == 'tiramisu': if config_type == 'tiramisu':
assert await cfg.forcepermissive.value.dict() == {"s1.a": True, "s1.b": False, "int": 43} assert cfg.forcepermissive.value.dict() == {"s1.a": True, "s1.b": False, "int": 43}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_make_dict_sub(config_type):
async def test_make_dict_with_disabled(config_type): "serialization part of config to a dict"
descr = OptionDescription("opt", "", [ od1 = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('hidden',))]),
IntOption("int", "", default=42)])
cfg = Config(od1)
cfg.property.read_write()
cfg.permissive.add('hidden')
cfg = get_config(cfg, config_type)
assert cfg.option('s1').value.dict() == {'s1.a': False}
def test_make_dict_not_value(config_type):
"serialization part of config to a dict"
od1 = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('hidden',))]),
IntOption("int", "", default=42)])
cfg = Config(od1)
cfg.property.read_write()
cfg.permissive.add('hidden')
cfg = get_config(cfg, config_type)
with raises(ConfigError):
cfg.option('s1.a').value.dict()
def test_make_dict_with_disabled(config_type):
od1 = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]), BoolOption("b", "", default=False, properties=('disabled',))]),
@ -103,19 +125,18 @@ async def test_make_dict_with_disabled(config_type):
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)), BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)]) IntOption("int", "", default=42)])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_only() cfg.property.read_only()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.value.dict() == {"s1.a": False, "int": 42} assert cfg.value.dict() == {"s1.a": False, "int": 42}
if config_type == 'tiramisu': if config_type == 'tiramisu':
assert await cfg.forcepermissive.value.dict() == {"s1.a": False, "int": 42} assert cfg.forcepermissive.value.dict() == {"s1.a": False, "int": 42}
assert await cfg.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False} assert cfg.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_make_dict_with_disabled_in_callback(config_type):
async def test_make_dict_with_disabled_in_callback(config_type): od1 = OptionDescription("opt", "", [
descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]), BoolOption("b", "", default=False, properties=('disabled',))]),
@ -123,17 +144,16 @@ async def test_make_dict_with_disabled_in_callback(config_type):
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)), BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)]) IntOption("int", "", default=42)])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_only() cfg.property.read_only()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
d = await cfg.value.dict() d = cfg.value.dict()
assert d == {"s1.a": False, "int": 42} assert d == {"s1.a": False, "int": 42}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_make_dict_fullpath(config_type):
async def test_make_dict_fullpath(config_type): od1 = OptionDescription("root", "", [
descr = OptionDescription("root", "", [
OptionDescription("opt", "", [ OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
@ -143,328 +163,303 @@ async def test_make_dict_fullpath(config_type):
BoolOption("b", "", default=False)], properties=('disabled',)), BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)]), IntOption("int", "", default=42)]),
IntOption("introot", "", default=42)]) IntOption("introot", "", default=42)])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_only() cfg.property.read_only()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42} assert cfg.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
if config_type == 'tiramisu': assert cfg.option('opt').value.dict() == {"opt.s1.a": False, "opt.int": 42}
# FIXME # assert not list_sessions()
assert await cfg.option('opt').value.dict() == {"s1.a": False, "int": 42}
assert await cfg.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
if config_type == 'tiramisu':
# FIXME
assert await cfg.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42}
assert not await list_sessions()
@pytest.mark.asyncio def test_find_in_config():
async def test_find_in_config():
"finds option in config" "finds option in config"
descr = make_description() od1 = make_description()
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_only() cfg.property.read_only()
await cfg.permissive.add('hidden') cfg.permissive.add('hidden')
ret = list(await cfg.option.find('dummy')) ret = list(cfg.option.find('dummy'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.dummy').get())
# #
ret_find = await cfg.option.find('dummy', first=True) ret_find = cfg.option.find('dummy', first=True)
ret = await ret_find.option.get() ret = ret_find.get()
_is_same_opt(ret, await cfg.option('gc.dummy').option.get()) _is_same_opt(ret, cfg.option('gc.dummy').get())
# #
ret = list(await cfg.option.find('float')) ret = list(cfg.option.find('float'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.float').get())
_is_same_opt(await ret[1].option.get(), await cfg.option('float').option.get()) _is_same_opt(ret[1].get(), cfg.option('float').get())
# #
ret = await cfg.option.find('bool', first=True) ret = cfg.option.find('bool', first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) _is_same_opt(ret.get(), cfg.option('gc.gc2.bool').get())
ret = await cfg.option.find('bool', value=True, first=True) ret = cfg.option.find('bool', value=True, first=True)
_is_same_opt(await ret.option.get(), await cfg.option('bool').option.get()) _is_same_opt(ret.get(), cfg.option('bool').get())
ret = await cfg.option.find('dummy', first=True) ret = cfg.option.find('dummy', first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) _is_same_opt(ret.get(), cfg.option('gc.dummy').get())
ret = await cfg.option.find('float', first=True) ret = cfg.option.find('float', first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.float').option.get()) _is_same_opt(ret.get(), cfg.option('gc.float').get())
#FIXME cannot find an option without name ret = list(cfg.option.find('prop'))
#ret = await cfg.find(bytype=ChoiceOption)
#assert len(ret) == 2
#_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name'))
#_is_same_opt(ret[1], await cfg.unwrap_from_path('objspace'))
#
#_is_same_opt(await cfg.find_first(bytype=ChoiceOption), await cfg.unwrap_from_path('gc.name'))
#ret = await cfg.find(byvalue='ref')
#assert len(ret) == 1
#_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name'))
#_is_same_opt(await cfg.find_first(byvalue='ref'), await cfg.unwrap_from_path('gc.name'))
#
ret = list(await cfg.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.prop').get())
# #
ret = list(await cfg.option.find('prop', value=None)) ret = list(cfg.option.find('prop', value=None))
assert len(ret) == 1 assert len(ret) == 1
ret = list(await cfg.option.find('prop')) ret = list(cfg.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.prop').get())
# #
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(AttributeError): with raises(AttributeError):
ret = await cfg.option.find('prop') ret = cfg.option.find('prop')
assert await ret.option.get() assert ret.get()
ret = list(await cfg.unrestraint.option.find(name='prop')) ret = list(cfg.unrestraint.option.find(name='prop'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(ret[0].get(), cfg.unrestraint.option('gc.gc2.prop').get())
_is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) _is_same_opt(ret[1].get(), cfg.forcepermissive.option('gc.prop').get())
# #
ret = list(await cfg.forcepermissive.option.find('prop')) ret = list(cfg.forcepermissive.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) _is_same_opt(ret[0].get(), cfg.forcepermissive.option('gc.prop').get())
# #
ret = await cfg.forcepermissive.option.find('prop', first=True) ret = cfg.forcepermissive.option.find('prop', first=True)
_is_same_opt(await ret.option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) _is_same_opt(ret.get(), cfg.forcepermissive.option('gc.prop').get())
# combinaison of filters # combinaison of filters
ret = list(await cfg.unrestraint.option.find('prop', type=BoolOption)) ret = list(cfg.unrestraint.option.find('prop', type=BoolOption))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(ret[0].get(), cfg.unrestraint.option('gc.gc2.prop').get())
ret = await cfg.unrestraint.option.find('prop', type=BoolOption, first=True) ret = cfg.unrestraint.option.find('prop', type=BoolOption, first=True)
_is_same_opt(await ret.option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(ret.get(), cfg.unrestraint.option('gc.gc2.prop').get())
# #
ret = list(await cfg.option.find('dummy', value=False)) ret = list(cfg.option.find('dummy', value=False))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.dummy').get())
# #
ret = await cfg.option.find('dummy', value=False, first=True) ret = cfg.option.find('dummy', value=False, first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) _is_same_opt(ret.get(), cfg.option('gc.dummy').get())
#subcfgig #subcfgig
ret = list(await cfg.option('gc').find('dummy')) ret = list(cfg.option('gc').find('dummy'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.dummy').get())
# #
ret = list(await cfg.option('gc').find('float')) ret = list(cfg.option('gc').find('float'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.float').get())
# #
ret = list(await cfg.option('gc').find('bool')) ret = list(cfg.option('gc.gc2').find('bool'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.gc2.bool').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.gc2.bool').get())
ret = await cfg.option('gc').find('bool', value=False, first=True) ret = cfg.option('gc').find('bool', value=False, first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) _is_same_opt(ret.get(), cfg.option('gc.gc2.bool').get())
# #
with pytest.raises(AttributeError): with raises(AttributeError):
ret = await cfg.option('gc').find('bool', value=True, first=True) ret = cfg.option('gc').find('bool', value=True, first=True)
assert await ret.option.get() assert ret.get()
# #
with pytest.raises(AttributeError): with raises(AttributeError):
ret = await cfg.option('gc').find('wantref') ret = cfg.option('gc').find('wantref')
await ret.option.get() ret.get()
# #
ret = list(await cfg.unrestraint.option('gc').find('prop')) ret = list(cfg.unrestraint.option('gc').find('prop'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(ret[0].get(), cfg.unrestraint.option('gc.gc2.prop').get())
_is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) _is_same_opt(ret[1].get(), cfg.forcepermissive.option('gc.prop').get())
# #
await cfg.property.read_only() cfg.property.read_only()
ret = list(await cfg.option('gc').find('prop')) ret = list(cfg.option('gc').find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) _is_same_opt(ret[0].get(), cfg.option('gc.prop').get())
# not OptionDescription # not OptionDescription
with pytest.raises(AttributeError): with raises(AttributeError):
await cfg.option.find('gc', first=True) cfg.option.find('gc', first=True)
with pytest.raises(AttributeError): with raises(AttributeError):
await cfg.option.find('gc2', first=True) cfg.option.find('gc2', first=True)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_find_multi():
async def test_find_multi():
b = BoolOption('bool', '', multi=True, properties=('notunique',)) b = BoolOption('bool', '', multi=True, properties=('notunique',))
o = OptionDescription('od', '', [b]) od1 = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(od1)
# #
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True)) list(cfg.option.find('bool', value=True))
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True, first=True)) list(cfg.option.find('bool', value=True, first=True))
await cfg.option('bool').value.set([False]) cfg.option('bool').value.set([False])
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True)) list(cfg.option.find('bool', value=True))
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True, first=True)) list(cfg.option.find('bool', value=True, first=True))
await cfg.option('bool').value.set([False, False]) cfg.option('bool').value.set([False, False])
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True)) list(cfg.option.find('bool', value=True))
with pytest.raises(AttributeError): with raises(AttributeError):
list(await cfg.option.find('bool', value=True, first=True)) list(cfg.option.find('bool', value=True, first=True))
await cfg.option('bool').value.set([False, False, True]) cfg.option('bool').value.set([False, False, True])
ret = list(await cfg.option.find('bool', value=True)) ret = list(cfg.option.find('bool', value=True))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(await ret[0].option.get(), b) _is_same_opt(ret[0].get(), b)
ret = await cfg.option.find('bool', value=True, first=True) ret = cfg.option.find('bool', value=True, first=True)
_is_same_opt(await ret.option.get(), b) _is_same_opt(ret.get(), b)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_does_not_find_in_config():
async def test_does_not_find_in_config(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: with raises(AttributeError):
with pytest.raises(AttributeError): list(cfg.option.find('IDontExist'))
list(await cfg.option.find('IDontExist')) # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_filename(config_type):
async def test_filename(config_type):
a = FilenameOption('a', '') a = FilenameOption('a', '')
o = OptionDescription('o', '', [a]) od1 = OptionDescription('o', '', [a])
async with await Config(o) as cfg: cfg = Config(od1)
# FIXME cfg = await get_config(cfg, config_type) # FIXME cfg = get_config(cfg, config_type)
await cfg.option('a').value.set('/') cfg.option('a').value.set('/')
await cfg.option('a').value.set('/tmp') cfg.option('a').value.set('/tmp')
await cfg.option('a').value.set('/tmp/') cfg.option('a').value.set('/tmp/')
await cfg.option('a').value.set('/tmp/text.txt') cfg.option('a').value.set('/tmp/text.txt')
await cfg.option('a').value.set('/tmp/with space.txt') cfg.option('a').value.set('/tmp/with space.txt')
await cfg.option('a').value.set('/tmp/with$.txt') cfg.option('a').value.set('/tmp/with$.txt')
with pytest.raises(ValueError): with raises(ValueError):
await cfg.option('a').value.set('not starts with /') cfg.option('a').value.set('not starts with /')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_invalid_option():
async def test_invalid_option():
ChoiceOption('a', '', ('1', '2')) ChoiceOption('a', '', ('1', '2'))
with pytest.raises(TypeError): with raises(TypeError):
ChoiceOption('a', '', [1, 2]) ChoiceOption('a', '', [1, 2])
with pytest.raises(TypeError): with raises(TypeError):
ChoiceOption('a', '', 1) ChoiceOption('a', '', 1)
with pytest.raises(ValueError): with raises(ValueError):
ChoiceOption('a', '', (1,), 3) ChoiceOption('a', '', (1,), 3)
FloatOption('a', '') FloatOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
FloatOption('a', '', 'string') FloatOption('a', '', 'string')
StrOption('a', '') StrOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
StrOption('a', '', 1) StrOption('a', '', 1)
u = StrOption('a', '') u = StrOption('a', '')
SymLinkOption('a', u) SymLinkOption('a', u)
with pytest.raises(ValueError): with raises(ValueError):
SymLinkOption('a', 'string') SymLinkOption('a', 'string')
IPOption('a', '') IPOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
IPOption('a', '', 1) IPOption('a', '', 1)
with pytest.raises(ValueError): with raises(ValueError):
IPOption('a', '', 'string') IPOption('a', '', 'string')
PortOption('a', '') PortOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', 'string') PortOption('a', '', 'string')
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', '11:12:13', allow_range=True) PortOption('a', '', '11:12:13', allow_range=True)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', 11111111111111111111) PortOption('a', '', 11111111111111111111)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False) PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True) PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True) PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True) PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False) PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', 'tcp:80') PortOption('a', '', 'tcp:80')
NetworkOption('a', '') NetworkOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
NetworkOption('a', '', 'string') NetworkOption('a', '', 'string')
NetmaskOption('a', '') NetmaskOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
NetmaskOption('a', '', 'string') NetmaskOption('a', '', 'string')
BroadcastOption('a', '') BroadcastOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
BroadcastOption('a', '', 'string') BroadcastOption('a', '', 'string')
DomainnameOption('a', '') DomainnameOption('a', '')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', 'string') DomainnameOption('a', '', 'string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', type='string') DomainnameOption('a', '', type='string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', allow_ip='string') DomainnameOption('a', '', allow_ip='string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', allow_without_dot='string') DomainnameOption('a', '', allow_without_dot='string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', 1) DomainnameOption('a', '', 1)
# #
ChoiceOption('a', '', (1,), multi=True, default_multi=1) ChoiceOption('a', '', (1,), multi=True, default_multi=1)
with pytest.raises(ValueError): with raises(ValueError):
ChoiceOption('a', '', (1,), default_multi=1) ChoiceOption('a', '', (1,), default_multi=1)
with pytest.raises(ValueError): with raises(ValueError):
ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2) ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2)
with pytest.raises(ValueError): with raises(ValueError):
FloatOption('a', '', multi=True, default_multi='string') FloatOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
StrOption('a', '', multi=True, default_multi=1) StrOption('a', '', multi=True, default_multi=1)
with pytest.raises(ValueError): with raises(ValueError):
IPOption('a', '', multi=True, default_multi=1) IPOption('a', '', multi=True, default_multi=1)
with pytest.raises(ValueError): with raises(ValueError):
IPOption('a', '', multi=True, default_multi='string') IPOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', multi=True, default_multi='string') PortOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True) PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True)
with pytest.raises(ValueError): with raises(ValueError):
PortOption('a', '', multi=True, default_multi=11111111111111111111) PortOption('a', '', multi=True, default_multi=11111111111111111111)
with pytest.raises(ValueError): with raises(ValueError):
NetworkOption('a', '', multi=True, default_multi='string') NetworkOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
NetmaskOption('a', '', multi=True, default_multi='string') NetmaskOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
BroadcastOption('a', '', multi=True, default_multi='string') BroadcastOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', multi=True, default_multi='string') DomainnameOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError): with raises(ValueError):
DomainnameOption('a', '', multi=True, default_multi=1) DomainnameOption('a', '', multi=True, default_multi=1)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_help():
async def test_help():
stro = StrOption('s', '', multi=True) stro = StrOption('s', '', multi=True)
od1 = OptionDescription('o', '', [stro]) od1 = OptionDescription('o', '', [stro])
od2 = OptionDescription('o', '', [od1]) od2 = OptionDescription('o', '', [od1])
async with await Config(od2) as cfg: cfg = Config(od2)
cfg.help(_display=False) cfg.help(_display=False)
cfg.config.help(_display=False) cfg.config.help(_display=False)
cfg.option.help(_display=False) cfg.option.help(_display=False)
cfg.option('o').help(_display=False) cfg.option('o').help(_display=False)
cfg.option('o.s').help(_display=False) cfg.option('o.s').help(_display=False)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_config_reset():
async def test_config_reset(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.owner.set('test')
await cfg.owner.set('test') assert cfg.owner.get() == 'test'
assert await cfg.owner.get() == 'test' assert not cfg.option('gc.gc2.bool').value.get()
assert not await cfg.option('gc.gc2.bool').value.get() assert not cfg.option('boolop').property.get()
assert not await cfg.option('boolop').property.get() assert not cfg.option('boolop').permissive.get()
assert not await cfg.option('boolop').permissive.get() assert not cfg.option('wantref').information.get('info', None)
assert not await cfg.option('wantref').information.get('info', None)
# #
await cfg.option('gc.gc2.bool').value.set(True) cfg.option('gc.gc2.bool').value.set(True)
await cfg.option('boolop').property.add('test') cfg.option('boolop').property.add('test')
await cfg.option('float').permissive.set(frozenset(['test'])) cfg.option('float').permissive.set(frozenset(['test']))
await cfg.option('wantref').information.set('info', 'info') cfg.option('wantref').information.set('info', 'info')
assert await cfg.option('gc.gc2.bool').value.get() assert cfg.option('gc.gc2.bool').value.get()
assert await cfg.option('boolop').property.get() assert cfg.option('boolop').property.get()
assert await cfg.option('float').permissive.get() assert cfg.option('float').permissive.get()
assert await cfg.option('wantref').information.get('info', None) assert cfg.option('wantref').information.get('info', None)
# #
assert await cfg.owner.get() == 'test' assert cfg.owner.get() == 'test'
await cfg.config.reset() cfg.config.reset()
assert await cfg.owner.get() == 'test' assert cfg.owner.get() == 'test'
assert not await cfg.option('gc.gc2.bool').value.get() assert not cfg.option('gc.gc2.bool').value.get()
assert not await cfg.option('boolop').property.get() assert not cfg.option('boolop').property.get()
assert not await cfg.option('float').permissive.get() assert not cfg.option('float').permissive.get()
assert not await cfg.option('wantref').information.get('info', None) assert not cfg.option('wantref').information.get('info', None)
assert not await list_sessions() # assert not list_sessions()

View file

@ -8,83 +8,103 @@ import pytest
from tiramisu import Config, DomainnameOption, EmailOption, URLOption, OptionDescription from tiramisu import Config, DomainnameOption, EmailOption, URLOption, OptionDescription
from tiramisu.error import ValueWarning from tiramisu.error import ValueWarning
from tiramisu.i18n import _ from tiramisu.i18n import _
from tiramisu.storage import list_sessions
from .config import event_loop
@pytest.mark.asyncio def test_domainname(config_type):
async def test_domainname(config_type):
d = DomainnameOption('d', '') d = DomainnameOption('d', '')
f = DomainnameOption('f', '', allow_without_dot=True) f = DomainnameOption('f', '', allow_without_dot=True)
g = DomainnameOption('g', '', allow_ip=True) g = DomainnameOption('g', '', allow_ip=True)
h = DomainnameOption('h', '', allow_cidr_network=True) h = DomainnameOption('h', '', allow_cidr_network=True)
od = OptionDescription('a', '', [d, f, g, h]) i = DomainnameOption('i', '', allow_ip=True, allow_cidr_network=True)
async with await Config(od) as cfg: j = DomainnameOption('j', '', allow_startswith_dot=True)
await cfg.property.read_write() od1 = OptionDescription('a', '', [d, f, g, h, i, j])
cfg = await get_config(cfg, config_type) cfg = Config(od1)
cfg.property.read_write()
cfg = get_config(cfg, config_type)
# #
await cfg.option('d').value.set('toto.com') cfg.option('d').value.set('toto.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto') cfg.option('d').value.set('.toto.com')
await cfg.option('d').value.set('toto3.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto_super.com') cfg.option('d').value.set('toto')
await cfg.option('d').value.set('toto-.com') cfg.option('d').value.set('toto3.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto..com') cfg.option('d').value.set('toto_super.com')
cfg.option('d').value.set('toto-.com')
with pytest.raises(ValueError):
cfg.option('d').value.set('toto..com')
# #
await cfg.option('f').value.set('toto.com') cfg.option('f').value.set('toto.com')
await cfg.option('f').value.set('toto') cfg.option('f').value.set('toto')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien') cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien')
await cfg.option('f').value.set('d') cfg.option('f').value.set('d')
await cfg.option('f').value.set('d.t') cfg.option('f').value.set('d.t')
# #
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('192.168.1.1') cfg.option('f').value.set('192.168.1.1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('192.168.1.0/24') cfg.option('f').value.set('192.168.1.0/24')
# #
await cfg.option('g').value.set('toto.com') cfg.option('g').value.set('toto.com')
await cfg.option('g').value.set('192.168.1.0') cfg.option('g').value.set('192.168.1.0')
await cfg.option('g').value.set('192.168.1.29') cfg.option('g').value.set('192.168.1.29')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('g').value.set('192.168.1.0/24') cfg.option('g').value.set('192.168.1.0/24')
with pytest.raises(ValueError):
cfg.option('g').value.set('240.94.1.1')
# #
await cfg.option('h').value.set('toto.com') cfg.option('h').value.set('toto.com')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('h').value.set('192.168.1.0') cfg.option('h').value.set('192.168.1.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('h').value.set('192.168.1.29') cfg.option('h').value.set('192.168.1.29')
# it's a network address # it's a network address
await cfg.option('h').value.set('192.168.1.0/24') cfg.option('h').value.set('192.168.1.0/24')
# but not here # but not here
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('h').value.set('192.168.1.1/24') cfg.option('h').value.set('192.168.1.1/24')
assert not await list_sessions() #
cfg.option('i').value.set('toto.com')
cfg.option('i').value.set('192.168.1.0')
cfg.option('i').value.set('192.168.1.1')
cfg.option('i').value.set('192.168.1.0/24')
with pytest.raises(ValueError):
cfg.option('i').value.set('192.168.1.1/24')
with pytest.raises(ValueError):
cfg.option('i').value.set('240.94.1.1')
#
cfg.option('j').value.set('toto.com')
cfg.option('j').value.set('.toto.com')
# assert not list_sessions()
@pytest.mark.asyncio def test_domainname_invalid(config_type):
async def test_domainname_upper(config_type): with pytest.raises(ValueError):
DomainnameOption('a', '', allow_cidr_network='str')
with pytest.raises(ValueError):
DomainnameOption('a', '', allow_startswith_dot='str')
def test_domainname_upper(config_type):
d = DomainnameOption('d', '') d = DomainnameOption('d', '')
od = OptionDescription('a', '', [d]) od1 = OptionDescription('a', '', [d])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('d').value.set('toto.com') cfg.option('d').value.set('toto.com')
msg = _('some characters are uppercase') msg = _('some characters are uppercase')
has_error = False has_error = False
try: try:
await cfg.option('d').value.set('TOTO.COM') cfg.option('d').value.set('TOTO.COM')
except ValueError as err: except ValueError as err:
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
@ -93,171 +113,165 @@ async def test_domainname_upper(config_type):
assert has_error is True assert has_error is True
has_error = False has_error = False
try: try:
await cfg.option('d').value.set('toTo.com') cfg.option('d').value.set('toTo.com')
except ValueError as err: except ValueError as err:
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
assert msg in str(err) assert msg in str(err)
has_error = True has_error = True
assert has_error is True assert has_error is True
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_domainname_warning(config_type):
async def test_domainname_warning(config_type):
d = DomainnameOption('d', '', warnings_only=True) d = DomainnameOption('d', '', warnings_only=True)
f = DomainnameOption('f', '', allow_without_dot=True, warnings_only=True) f = DomainnameOption('f', '', allow_without_dot=True, warnings_only=True)
g = DomainnameOption('g', '', allow_ip=True, warnings_only=True) g = DomainnameOption('g', '', allow_ip=True, warnings_only=True)
od = OptionDescription('a', '', [d, f, g]) od1 = OptionDescription('a', '', [d, f, g])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('d').value.set('toto.com') cfg.option('d').value.set('toto.com')
await cfg.option('d').value.set('toto.com.') cfg.option('d').value.set('toto.com.')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto') cfg.option('d').value.set('toto')
await cfg.option('d').value.set('toto3.com') cfg.option('d').value.set('toto3.com')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
await cfg.option('d').value.set('toto_super.com') cfg.option('d').value.set('toto_super.com')
assert len(w) == 1 assert len(w) == 1
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
await cfg.option('d').value.set('toto-.com') cfg.option('d').value.set('toto-.com')
assert len(w) == 0 assert len(w) == 0
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto..com') cfg.option('d').value.set('toto..com')
# #
await cfg.option('f').value.set('toto.com') cfg.option('f').value.set('toto.com')
await cfg.option('f').value.set('toto') cfg.option('f').value.set('toto')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx') cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx')
await cfg.option('f').value.set('d') cfg.option('f').value.set('d')
await cfg.option('f').value.set('d.t') cfg.option('f').value.set('d.t')
# #
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('192.168.1.1') cfg.option('f').value.set('192.168.1.1')
await cfg.option('g').value.set('toto.com') cfg.option('g').value.set('toto.com')
await cfg.option('g').value.set('192.168.1.0') cfg.option('g').value.set('192.168.1.0')
await cfg.option('g').value.set('192.168.1.29') cfg.option('g').value.set('192.168.1.29')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_special_domain_name(config_type):
async def test_special_domain_name(config_type):
"""domain name option that starts with a number or not """domain name option that starts with a number or not
""" """
d = DomainnameOption('d', '') d = DomainnameOption('d', '')
e = DomainnameOption('e', '', type='netbios') e = DomainnameOption('e', '', type='netbios')
od = OptionDescription('a', '', [d, e]) od1 = OptionDescription('a', '', [d, e])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('d').value.set('1toto.com') cfg.option('d').value.set('1toto.com')
await cfg.option('d').value.set('123toto.com') cfg.option('d').value.set('123toto.com')
await cfg.option('e').value.set('toto') cfg.option('e').value.set('toto')
await cfg.option('e').value.set('1toto') cfg.option('e').value.set('1toto')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_domainname_netbios(config_type):
async def test_domainname_netbios(config_type):
d = DomainnameOption('d', '', type='netbios') d = DomainnameOption('d', '', type='netbios')
e = DomainnameOption('e', '', "toto", type='netbios') e = DomainnameOption('e', '', "toto", type='netbios')
od = OptionDescription('a', '', [d, e]) od1 = OptionDescription('a', '', [d, e])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto.com') cfg.option('d').value.set('toto.com')
await cfg.option('d').value.set('toto') cfg.option('d').value.set('toto')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('domainnametoolong') cfg.option('d').value.set('domainnametoolong')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_domainname_hostname(config_type):
async def test_domainname_hostname(config_type):
d = DomainnameOption('d', '', type='hostname') d = DomainnameOption('d', '', type='hostname')
e = DomainnameOption('e', '', "toto", type='hostname') e = DomainnameOption('e', '', "toto", type='hostname')
od = OptionDescription('a', '', [d, e]) od1 = OptionDescription('a', '', [d, e])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('toto.com') cfg.option('d').value.set('toto.com')
await cfg.option('d').value.set('toto') cfg.option('d').value.set('toto')
await cfg.option('d').value.set('domainnametoolong') cfg.option('d').value.set('domainnametoolong')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_email(config_type):
async def test_email(config_type):
e = EmailOption('e', '') e = EmailOption('e', '')
od = OptionDescription('a', '', [e]) od1 = OptionDescription('a', '', [e])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('e').value.set('foo-bar.baz@example.com') cfg.option('e').value.set('foo-bar.baz@example.com')
await cfg.option('e').value.set('root@foo.com') cfg.option('e').value.set('root@foo.com')
await cfg.option('e').value.set('root@domain') cfg.option('e').value.set('root@domain')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('e').value.set(1) cfg.option('e').value.set(1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('e').value.set('root') cfg.option('e').value.set('root')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('e').value.set('root[]@domain') cfg.option('e').value.set('root[]@domain')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_url(config_type):
async def test_url(config_type):
u = URLOption('u', '') u = URLOption('u', '')
od = OptionDescription('a', '', [u]) od1 = OptionDescription('a', '', [u])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('u').value.set('http://foo.com') cfg.option('u').value.set('http://foo.com')
await cfg.option('u').value.set('https://foo.com') cfg.option('u').value.set('https://foo.com')
await cfg.option('u').value.set('https://foo.com/') cfg.option('u').value.set('https://foo.com/')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set(1) cfg.option('u').value.set(1)
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('ftp://foo.com') cfg.option('u').value.set('ftp://foo.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('foo.com') cfg.option('u').value.set('foo.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set(':/foo.com') cfg.option('u').value.set(':/foo.com')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('foo.com/http://') cfg.option('u').value.set('foo.com/http://')
await cfg.option('u').value.set('https://foo.com/index.html') cfg.option('u').value.set('https://foo.com/index.html')
await cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2') cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('https://foo.com/index\\n.html') cfg.option('u').value.set('https://foo.com/index\\n.html')
await cfg.option('u').value.set('https://foo.com:8443') cfg.option('u').value.set('https://foo.com:8443')
await cfg.option('u').value.set('https://foo.com:8443/') cfg.option('u').value.set('https://foo.com:8443/')
await cfg.option('u').value.set('https://foo.com:8443/index.html') cfg.option('u').value.set('https://foo.com:8443/index.html')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('https://foo.com:84438989') cfg.option('u').value.set('https://foo.com:84438989')
await cfg.option('u').value.set('https://foo.com:8443/INDEX') cfg.option('u').value.set('https://foo.com:8443/INDEX')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('u').value.set('https://FOO.COM:8443') cfg.option('u').value.set('https://FOO.COM:8443')
assert not await list_sessions() # assert not list_sessions()

View file

@ -1,416 +1,413 @@
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config, value_list, global_owner, event_loop from .config import config_type, get_config, value_list, global_owner
import warnings import warnings
import pytest import pytest
from tiramisu import Config, IPOption, NetworkOption, NetmaskOption, \ from tiramisu import Config, IPOption, NetworkOption, NetmaskOption, \
PortOption, BroadcastOption, OptionDescription PortOption, BroadcastOption, OptionDescription
from tiramisu.error import ValueWarning from tiramisu.error import ValueWarning
from tiramisu.storage import list_sessions
@pytest.mark.asyncio def test_ip(config_type):
async def test_ip(config_type):
a = IPOption('a', '') a = IPOption('a', '')
b = IPOption('b', '', private_only=True) b = IPOption('b', '', private_only=True)
d = IPOption('d', '', warnings_only=True, private_only=True) d = IPOption('d', '', warnings_only=True, private_only=True)
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
od = OptionDescription('od', '', [a, b, d]) od1 = OptionDescription('od', '', [a, b, d])
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('a').value.set('192.168.1.1') cfg.option('a').value.set('192.168.1.1')
await cfg.option('a').value.set('192.168.1.0') cfg.option('a').value.set('192.168.1.0')
await cfg.option('a').value.set('88.88.88.88') cfg.option('a').value.set('88.88.88.88')
await cfg.option('a').value.set('0.0.0.0') cfg.option('a').value.set('0.0.0.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('255.255.255.0') cfg.option('a').value.set('255.255.255.0')
await cfg.option('b').value.set('192.168.1.1') cfg.option('b').value.set('192.168.1.1')
await cfg.option('b').value.set('192.168.1.0') cfg.option('b').value.set('192.168.1.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('88.88.88.88') cfg.option('b').value.set('88.88.88.88')
await cfg.option('b').value.set('0.0.0.0') cfg.option('b').value.set('0.0.0.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('255.255.255.0') cfg.option('b').value.set('255.255.255.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('333.0.1.20') cfg.option('a').value.set('333.0.1.20')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
IPOption('a', 'ip', default='192.000.023.01') IPOption('a', 'ip', default='192.000.023.01')
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
await cfg.option('d').value.set('88.88.88.88') cfg.option('d').value.set('88.88.88.88')
assert len(w) == 1 assert len(w) == 1
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_ip_cidr():
async def test_ip_cidr():
b = IPOption('b', '', private_only=True, cidr=True) b = IPOption('b', '', private_only=True, cidr=True)
c = IPOption('c', '', private_only=True) c = IPOption('c', '', private_only=True)
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
od = OptionDescription('od', '', [b, c]) od1 = OptionDescription('od', '', [b, c])
async with await Config(od) as cfg: cfg = Config(od1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('192.168.1.1') cfg.option('b').value.set('192.168.1.1')
await cfg.option('b').value.set('192.168.1.1/24') cfg.option('b').value.set('192.168.1.1/24')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('192.168.1.1/32') cfg.option('b').value.set('192.168.1.0/24')
with pytest.raises(ValueError):
cfg.option('b').value.set('192.168.1.255/24')
with pytest.raises(ValueError):
cfg.option('b').value.set('192.168.1.1/32')
with pytest.raises(ValueError):
cfg.option('b').value.set('192.168.1.1/33')
# #
await cfg.option('c').value.set('192.168.1.1') cfg.option('c').value.set('192.168.1.1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('192.168.1.1/24') cfg.option('c').value.set('192.168.1.1/24')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('192.168.1.1/32') cfg.option('c').value.set('192.168.1.1/32')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_ip_default():
async def test_ip_default():
a = IPOption('a', '', '88.88.88.88') a = IPOption('a', '', '88.88.88.88')
od = OptionDescription('od', '', [a]) od1 = OptionDescription('od', '', [a])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.option('a').value.get() == '88.88.88.88' cfg.option('a').value.get() == '88.88.88.88'
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_ip_reserved(config_type):
async def test_ip_reserved(config_type):
a = IPOption('a', '') a = IPOption('a', '')
b = IPOption('b', '', allow_reserved=True) b = IPOption('b', '', allow_reserved=True)
c = IPOption('c', '', warnings_only=True) c = IPOption('c', '', warnings_only=True)
od = OptionDescription('od', '', [a, b, c]) od1 = OptionDescription('od', '', [a, b, c])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('240.94.1.1') cfg.option('a').value.set('240.94.1.1')
await cfg.option('b').value.set('240.94.1.1') cfg.option('b').value.set('240.94.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
await cfg.option('c').value.set('240.94.1.1') cfg.option('c').value.set('240.94.1.1')
assert len(w) == 1 assert len(w) == 1
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_network(config_type):
async def test_network(config_type):
a = NetworkOption('a', '') a = NetworkOption('a', '')
b = NetworkOption('b', '', warnings_only=True) b = NetworkOption('b', '', warnings_only=True)
od = OptionDescription('od', '', [a, b]) od1 = OptionDescription('od', '', [a, b])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('a').value.set('192.168.1.1') cfg.option('a').value.set('192.168.1.1')
await cfg.option('a').value.set('192.168.1.0') cfg.option('a').value.set('192.168.1.0')
await cfg.option('a').value.set('88.88.88.88') cfg.option('a').value.set('88.88.88.88')
await cfg.option('a').value.set('0.0.0.0') cfg.option('a').value.set('0.0.0.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set(1) cfg.option('a').value.set(1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('1.1.1.1.1') cfg.option('a').value.set('1.1.1.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('255.255.255.0') cfg.option('a').value.set('255.255.255.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.001.0') cfg.option('a').value.set('192.168.001.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('333.168.1.1') cfg.option('a').value.set('333.168.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
await cfg.option('b').value.set('255.255.255.0') cfg.option('b').value.set('255.255.255.0')
assert len(w) == 1 assert len(w) == 1
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_network_cidr(config_type):
async def test_network_cidr(config_type):
a = NetworkOption('a', '', cidr=True) a = NetworkOption('a', '', cidr=True)
od = OptionDescription('od', '', [a]) od1 = OptionDescription('od', '', [a])
async with await Config(od) as cfg: cfg = Config(od1)
# FIXME cfg = await get_config(cfg, config_type) # FIXME cfg = get_config(cfg, config_type)
await cfg.option('a').value.set('192.168.1.1/32') cfg.option('a').value.set('192.168.1.1/32')
await cfg.option('a').value.set('192.168.1.0/24') cfg.option('a').value.set('192.168.1.0/24')
await cfg.option('a').value.set('88.88.88.88/32') cfg.option('a').value.set('88.88.88.88/32')
await cfg.option('a').value.set('0.0.0.0/0') cfg.option('a').value.set('0.0.0.0/0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1') cfg.option('a').value.set('192.168.1.1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1/24') cfg.option('a').value.set('192.168.1.1/24')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('2001:db00::0/24') cfg.option('a').value.set('2001:db00::0/24')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_network_invalid():
async def test_network_invalid():
with pytest.raises(ValueError): with pytest.raises(ValueError):
NetworkOption('a', '', default='toto') NetworkOption('a', '', default='toto')
@pytest.mark.asyncio def test_netmask(config_type):
async def test_netmask(config_type):
a = NetmaskOption('a', '') a = NetmaskOption('a', '')
od = OptionDescription('od', '', [a]) od1 = OptionDescription('od', '', [a])
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1.1') cfg.option('a').value.set('192.168.1.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1') cfg.option('a').value.set('192.168.1.1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.0') cfg.option('a').value.set('192.168.1.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('88.88.88.88') cfg.option('a').value.set('88.88.88.88')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('255.255.255.000') cfg.option('a').value.set('255.255.255.000')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set(2) cfg.option('a').value.set(2)
await cfg.option('a').value.set('0.0.0.0') cfg.option('a').value.set('0.0.0.0')
await cfg.option('a').value.set('255.255.255.0') cfg.option('a').value.set('255.255.255.0')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_broadcast(config_type):
async def test_broadcast(config_type):
a = BroadcastOption('a', '') a = BroadcastOption('a', '')
od = OptionDescription('od', '', [a]) od1 = OptionDescription('od', '', [a])
async with await Config(od) as cfg: cfg = Config(od1)
# FIXME cfg = await get_config(cfg, config_type) # FIXME cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.255.1') cfg.option('a').value.set('192.168.1.255.1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.001.255') cfg.option('a').value.set('192.168.001.255')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.0.300') cfg.option('a').value.set('192.168.0.300')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set(1) cfg.option('a').value.set(1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set(2) cfg.option('a').value.set(2)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('2001:db8::1') cfg.option('a').value.set('2001:db8::1')
await cfg.option('a').value.set('0.0.0.0') cfg.option('a').value.set('0.0.0.0')
await cfg.option('a').value.set('255.255.255.0') cfg.option('a').value.set('255.255.255.0')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_port(config_type):
async def test_port(config_type):
a = PortOption('a', '') a = PortOption('a', '')
b = PortOption('b', '', allow_zero=True) b = PortOption('b', '', allow_zero=True)
c = PortOption('c', '', allow_zero=True, allow_registred=False) c = PortOption('c', '', allow_zero=True, allow_registred=False)
d = PortOption('d', '', allow_zero=True, allow_wellknown=False, allow_registred=False) d = PortOption('d', '', allow_zero=True, allow_wellknown=False, allow_registred=False)
e = PortOption('e', '', allow_zero=True, allow_private=True) e = PortOption('e', '', allow_zero=True, allow_private=True)
f = PortOption('f', '', allow_private=True) f = PortOption('f', '', allow_private=True)
od = OptionDescription('od', '', [a, b, c, d, e, f]) g = PortOption('g', '', warnings_only=True)
async with await Config(od) as cfg: od1 = OptionDescription('od', '', [a, b, c, d, e, f, g])
# FIXME cfg = await get_config(cfg, config_type) cfg = Config(od1)
# FIXME cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('0') cfg.option('a').value.set('0')
await cfg.option('a').value.set('1') with warnings.catch_warnings(record=True) as w:
await cfg.option('a').value.set('1023') cfg.option('g').value.set('0')
await cfg.option('a').value.set('1024') assert len(w) == 1
await cfg.option('a').value.set('49151') cfg.option('a').value.set('1')
cfg.option('a').value.set('1023')
cfg.option('a').value.set('1024')
cfg.option('a').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('49152') cfg.option('a').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('65535') cfg.option('a').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('65536') cfg.option('a').value.set('65536')
await cfg.option('b').value.set('0') cfg.option('b').value.set('0')
await cfg.option('b').value.set('1') cfg.option('b').value.set('1')
await cfg.option('b').value.set('1023') cfg.option('b').value.set('1023')
await cfg.option('b').value.set('1024') cfg.option('b').value.set('1024')
await cfg.option('b').value.set('49151') cfg.option('b').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('49152') cfg.option('b').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('65535') cfg.option('b').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('65536') cfg.option('b').value.set('65536')
await cfg.option('c').value.set('0') cfg.option('c').value.set('0')
await cfg.option('c').value.set('1') cfg.option('c').value.set('1')
await cfg.option('c').value.set('1023') cfg.option('c').value.set('1023')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('1024') cfg.option('c').value.set('1024')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('49151') cfg.option('c').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('49152') cfg.option('c').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('65535') cfg.option('c').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('65536') cfg.option('c').value.set('65536')
await cfg.option('d').value.set('0') cfg.option('d').value.set('0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1') cfg.option('d').value.set('1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1023') cfg.option('d').value.set('1023')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1024') cfg.option('d').value.set('1024')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('49151') cfg.option('d').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('49152') cfg.option('d').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('65535') cfg.option('d').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('65536') cfg.option('d').value.set('65536')
await cfg.option('e').value.set('0') cfg.option('e').value.set('0')
await cfg.option('e').value.set('1') cfg.option('e').value.set('1')
await cfg.option('e').value.set('1023') cfg.option('e').value.set('1023')
await cfg.option('e').value.set('1024') cfg.option('e').value.set('1024')
await cfg.option('e').value.set('49151') cfg.option('e').value.set('49151')
await cfg.option('e').value.set('49152') cfg.option('e').value.set('49152')
await cfg.option('e').value.set('65535') cfg.option('e').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('0') cfg.option('f').value.set('0')
await cfg.option('f').value.set('1') cfg.option('f').value.set('1')
await cfg.option('f').value.set('1023') cfg.option('f').value.set('1023')
await cfg.option('f').value.set('1024') cfg.option('f').value.set('1024')
await cfg.option('f').value.set('49151') cfg.option('f').value.set('49151')
await cfg.option('f').value.set('49152') cfg.option('f').value.set('49152')
await cfg.option('f').value.set('65535') cfg.option('f').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('65536') cfg.option('f').value.set('65536')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_port_protocol(config_type):
async def test_port_protocol(config_type):
a = PortOption('a', '', allow_protocol=True) a = PortOption('a', '', allow_protocol=True)
od = OptionDescription('od', '', [a]) od1 = OptionDescription('od', '', [a])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.option('a').value.set('80') cfg.option('a').value.set('80')
await cfg.option('a').value.set('tcp:80') cfg.option('a').value.set('tcp:80')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_port_range(config_type):
async def test_port_range(config_type):
a = PortOption('a', '', allow_range=True) a = PortOption('a', '', allow_range=True)
b = PortOption('b', '', allow_range=True, allow_zero=True) b = PortOption('b', '', allow_range=True, allow_zero=True)
c = PortOption('c', '', allow_range=True, allow_zero=True, allow_registred=False) c = PortOption('c', '', allow_range=True, allow_zero=True, allow_registred=False)
d = PortOption('d', '', allow_range=True, allow_zero=True, allow_wellknown=False, allow_registred=False) d = PortOption('d', '', allow_range=True, allow_zero=True, allow_wellknown=False, allow_registred=False)
e = PortOption('e', '', allow_range=True, allow_zero=True, allow_private=True) e = PortOption('e', '', allow_range=True, allow_zero=True, allow_private=True)
f = PortOption('f', '', allow_range=True, allow_private=True) f = PortOption('f', '', allow_range=True, allow_private=True)
od = OptionDescription('od', '', [a, b, c, d, e, f]) od1 = OptionDescription('od', '', [a, b, c, d, e, f])
async with await Config(od) as cfg: cfg = Config(od1)
# FIXME cfg = await get_config(cfg, config_type) # FIXME cfg = get_config(cfg, config_type)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('0') cfg.option('a').value.set('0')
await cfg.option('a').value.set('1') cfg.option('a').value.set('1')
await cfg.option('a').value.set('1023') cfg.option('a').value.set('1023')
await cfg.option('a').value.set('1024') cfg.option('a').value.set('1024')
await cfg.option('a').value.set('49151') cfg.option('a').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('49152') cfg.option('a').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('65535') cfg.option('a').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('65536') cfg.option('a').value.set('65536')
await cfg.option('a').value.set('1:49151') cfg.option('a').value.set('1:49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('0:49151') cfg.option('a').value.set('0:49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('a').value.set('1:49152') cfg.option('a').value.set('1:49152')
await cfg.option('b').value.set('0') cfg.option('b').value.set('0')
await cfg.option('b').value.set('1') cfg.option('b').value.set('1')
await cfg.option('b').value.set('1023') cfg.option('b').value.set('1023')
await cfg.option('b').value.set('1024') cfg.option('b').value.set('1024')
await cfg.option('b').value.set('49151') cfg.option('b').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('49152') cfg.option('b').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('65535') cfg.option('b').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('65536') cfg.option('b').value.set('65536')
await cfg.option('b').value.set('0:49151') cfg.option('b').value.set('0:49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('b').value.set('0:49152') cfg.option('b').value.set('0:49152')
await cfg.option('c').value.set('0') cfg.option('c').value.set('0')
await cfg.option('c').value.set('1') cfg.option('c').value.set('1')
await cfg.option('c').value.set('1023') cfg.option('c').value.set('1023')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('1024') cfg.option('c').value.set('1024')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('49151') cfg.option('c').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('49152') cfg.option('c').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('65535') cfg.option('c').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('65536') cfg.option('c').value.set('65536')
await cfg.option('c').value.set('0:1023') cfg.option('c').value.set('0:1023')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('c').value.set('0:1024') cfg.option('c').value.set('0:1024')
await cfg.option('d').value.set('0') cfg.option('d').value.set('0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1') cfg.option('d').value.set('1')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1023') cfg.option('d').value.set('1023')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('1024') cfg.option('d').value.set('1024')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('49151') cfg.option('d').value.set('49151')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('49152') cfg.option('d').value.set('49152')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('65535') cfg.option('d').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('65536') cfg.option('d').value.set('65536')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('0:0') cfg.option('d').value.set('0:0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('d').value.set('0:1') cfg.option('d').value.set('0:1')
await cfg.option('e').value.set('0') cfg.option('e').value.set('0')
await cfg.option('e').value.set('1') cfg.option('e').value.set('1')
await cfg.option('e').value.set('1023') cfg.option('e').value.set('1023')
await cfg.option('e').value.set('1024') cfg.option('e').value.set('1024')
await cfg.option('e').value.set('49151') cfg.option('e').value.set('49151')
await cfg.option('e').value.set('49152') cfg.option('e').value.set('49152')
await cfg.option('e').value.set('65535') cfg.option('e').value.set('65535')
await cfg.option('e').value.set('0:65535') cfg.option('e').value.set('0:65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('e').value.set('0:65536') cfg.option('e').value.set('0:65536')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('0') cfg.option('f').value.set('0')
await cfg.option('f').value.set('1') cfg.option('f').value.set('1')
await cfg.option('f').value.set('1023') cfg.option('f').value.set('1023')
await cfg.option('f').value.set('1024') cfg.option('f').value.set('1024')
await cfg.option('f').value.set('49151') cfg.option('f').value.set('49151')
await cfg.option('f').value.set('49152') cfg.option('f').value.set('49152')
await cfg.option('f').value.set('65535') cfg.option('f').value.set('65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('65536') cfg.option('f').value.set('65536')
await cfg.option('f').value.set('1:65535') cfg.option('f').value.set('1:65535')
await cfg.option('f').value.set('3:4') cfg.option('f').value.set('3:4')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('0:65535') cfg.option('f').value.set('0:65535')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('f').value.set('4:3') cfg.option('f').value.set('4:3')
assert not await list_sessions() # assert not list_sessions()

View file

@ -7,64 +7,40 @@ import pytest
from tiramisu import BoolOption, IntOption, StrOption, IPOption, NetmaskOption, \ from tiramisu import BoolOption, IntOption, StrOption, IPOption, NetmaskOption, \
SymLinkOption, OptionDescription, DynOptionDescription, submulti, \ SymLinkOption, OptionDescription, DynOptionDescription, submulti, \
Config, GroupConfig, MetaConfig, Params, ParamOption, Calculation Config, GroupConfig, MetaConfig, Params, ParamOption, Calculation
from tiramisu.storage import list_sessions
from .config import event_loop
IS_DEREFABLE = True
def funcname(*args, **kwargs): def funcname(*args, **kwargs):
return value return value
@pytest.mark.asyncio def test_deref_value():
async def test_deref_storage():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(o)
w = weakref.ref(cfg._config_bag.context.cfgimpl_get_values()._p_) w = weakref.ref(cfg._config_bag.context.get_values())
del cfg del cfg
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_setting():
async def test_deref_value():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(o)
w = weakref.ref(cfg._config_bag.context.cfgimpl_get_values()) w = weakref.ref(cfg._config_bag.context.get_settings())
del cfg del cfg
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_config():
async def test_deref_setting():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(o)
w = weakref.ref(cfg._config_bag.context.cfgimpl_get_settings())
del cfg
assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio
async def test_deref_config():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
async with await Config(o) as cfg:
w = weakref.ref(cfg) w = weakref.ref(cfg)
del cfg del cfg
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_option():
async def test_deref_option():
global IS_DEREFABLE
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
w = weakref.ref(b) w = weakref.ref(b)
@ -72,17 +48,12 @@ async def test_deref_option():
try: try:
assert w() is not None assert w() is not None
except AssertionError: except AssertionError:
IS_DEREFABLE = False
return return
del(o) del(o)
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_optiondescription():
async def test_deref_optiondescription():
if not IS_DEREFABLE:
return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
w = weakref.ref(o) w = weakref.ref(o)
@ -90,46 +61,34 @@ async def test_deref_optiondescription():
assert w() is not None assert w() is not None
del(o) del(o)
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_option_cache():
async def test_deref_option_cache():
if not IS_DEREFABLE:
return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
await o._build_cache() o._build_cache()
w = weakref.ref(b) w = weakref.ref(b)
del(b) del(b)
assert w() is not None assert w() is not None
del(o) del(o)
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_optiondescription_cache():
async def test_deref_optiondescription_cache():
if not IS_DEREFABLE:
return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
await o._build_cache() o._build_cache()
w = weakref.ref(o) w = weakref.ref(o)
del(b) del(b)
assert w() is not None assert w() is not None
del(o) del(o)
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_option_config():
async def test_deref_option_config():
if not IS_DEREFABLE:
return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(o)
w = weakref.ref(b) w = weakref.ref(b)
del(b) del(b)
assert w() is not None assert w() is not None
@ -137,16 +96,12 @@ async def test_deref_option_config():
assert w() is not None assert w() is not None
del cfg del cfg
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_optiondescription_config():
async def test_deref_optiondescription_config():
if not IS_DEREFABLE:
return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
async with await Config(o) as cfg: cfg = Config(o)
w = weakref.ref(o) w = weakref.ref(o)
del(b) del(b)
assert w() is not None assert w() is not None
@ -154,20 +109,16 @@ async def test_deref_optiondescription_config():
assert w() is not None assert w() is not None
del cfg del cfg
assert w() is None assert w() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_validator():
async def test_deref_validator():
if not IS_DEREFABLE:
return
a = StrOption('a', '', default='yes') a = StrOption('a', '', default='yes')
b = StrOption('b', '', validators=[Calculation(funcname, Params(ParamOption(a)))], default='val') b = StrOption('b', '', validators=[Calculation(funcname, Params(ParamOption(a)))], default='val')
od = OptionDescription('root', '', [a, b]) o = OptionDescription('root', '', [a, b])
async with await Config(od) as cfg: cfg = Config(o)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(o)
z = weakref.ref(cfg) z = weakref.ref(cfg)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
@ -179,7 +130,7 @@ async def test_deref_validator():
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
del(od) del(o)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
@ -187,20 +138,16 @@ async def test_deref_validator():
del cfg del cfg
assert y() is None assert y() is None
assert z() is None assert z() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_callback():
async def test_deref_callback():
if not IS_DEREFABLE:
return
a = StrOption('a', "", 'val') a = StrOption('a', "", 'val')
b = StrOption('b', "", Calculation(funcname, Params((ParamOption(a),)))) b = StrOption('b', "", Calculation(funcname, Params((ParamOption(a),))))
od = OptionDescription('root', '', [a, b]) o = OptionDescription('root', '', [a, b])
async with await Config(od) as cfg: cfg = Config(o)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(o)
z = weakref.ref(cfg) z = weakref.ref(cfg)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
@ -212,7 +159,7 @@ async def test_deref_callback():
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
del(od) del(o)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
@ -220,20 +167,16 @@ async def test_deref_callback():
del cfg del cfg
assert y() is None assert y() is None
assert z() is None assert z() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_symlink():
async def test_deref_symlink():
if not IS_DEREFABLE:
return
a = BoolOption("a", "", default=False) a = BoolOption("a", "", default=False)
b = SymLinkOption("b", a) b = SymLinkOption("b", a)
od = OptionDescription('root', '', [a, b]) o = OptionDescription('root', '', [a, b])
async with await Config(od) as cfg: cfg = Config(o)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(o)
z = weakref.ref(cfg) z = weakref.ref(cfg)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
@ -245,7 +188,7 @@ async def test_deref_symlink():
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
del(od) del(o)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
@ -253,21 +196,17 @@ async def test_deref_symlink():
del cfg del cfg
assert y() is None assert y() is None
assert z() is None assert z() is None
assert not await list_sessions()
@pytest.mark.asyncio def test_deref_dyn():
async def test_deref_dyn():
if not IS_DEREFABLE:
return
a = StrOption('a', '', ['val1', 'val2'], multi=True) a = StrOption('a', '', ['val1', 'val2'], multi=True)
b = StrOption('b', '') b = StrOption('b', '')
dod = DynOptionDescription('dod', '', [b], suffixes=Calculation(funcname, Params((ParamOption(a),)))) dod = DynOptionDescription('dod', '', [b], suffixes=Calculation(funcname, Params((ParamOption(a),))))
od = OptionDescription('od', '', [dod, a]) o = OptionDescription('od', '', [dod, a])
async with await Config(od) as cfg: cfg = Config(o)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(o)
z = weakref.ref(cfg) z = weakref.ref(cfg)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
@ -279,7 +218,7 @@ async def test_deref_dyn():
assert x() is not None assert x() is not None
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
del(od) del(o)
del(dod) del(dod)
assert w() is not None assert w() is not None
assert x() is not None assert x() is not None
@ -288,4 +227,3 @@ async def test_deref_dyn():
del cfg del cfg
assert y() is None assert y() is None
assert z() is None assert z() is None
assert not await list_sessions()

View file

@ -6,8 +6,6 @@ import pytest
from tiramisu.setting import groups from tiramisu.setting import groups
from tiramisu import Config, MetaConfig, ChoiceOption, BoolOption, IntOption, \ from tiramisu import Config, MetaConfig, ChoiceOption, BoolOption, IntOption, \
StrOption, OptionDescription, groups StrOption, OptionDescription, groups
from tiramisu.storage import list_sessions
from .config import event_loop
def make_description(): def make_description():
@ -43,62 +41,54 @@ def make_description():
return descr return descr
def to_tuple(val): def test_copy():
return tuple([tuple(v) for v in val]) od1 = make_description()
cfg = Config(od1)
ncfg = cfg.config.copy()
assert cfg.option('creole.general.numero_etab').value.get() == None
cfg.option('creole.general.numero_etab').value.set('oui')
assert cfg.option('creole.general.numero_etab').value.get() == 'oui'
assert ncfg.option('creole.general.numero_etab').value.get() == None
# assert not list_sessions()
@pytest.mark.asyncio def test_copy_information():
async def test_copy(): od1 = make_description()
od = make_description() cfg = Config(od1)
async with await Config(od) as cfg: cfg.information.set('key', 'value')
async with await cfg.config.copy() as ncfg: ncfg = cfg.config.copy()
assert await cfg.option('creole.general.numero_etab').value.get() == None assert ncfg.information.get('key') == 'value'
await cfg.option('creole.general.numero_etab').value.set('oui') # assert not list_sessions()
assert await cfg.option('creole.general.numero_etab').value.get() == 'oui'
assert await ncfg.option('creole.general.numero_etab').value.get() == None
assert not await list_sessions()
@pytest.mark.asyncio def test_copy_force_store_value():
async def test_copy_information(): od1 = make_description()
od = make_description() conf = Config(od1)
async with await Config(od) as cfg: conf2 = Config(od1)
await cfg.information.set('key', 'value') assert conf.value.exportation() == {}
async with await cfg.config.copy() as ncfg: assert conf2.value.exportation() == {}
assert await ncfg.information.get('key') == 'value'
assert not await list_sessions()
@pytest.mark.asyncio
async def test_copy_force_store_value():
od = make_description()
async with await Config(od) as conf:
async with await Config(od) as conf2:
assert to_tuple(await conf.value.exportation()) == ((), (), (), ())
assert to_tuple(await conf2.value.exportation()) == ((), (), (), ())
# #
await conf.property.read_write() conf.property.read_write()
assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert conf.value.exportation() == {'creole.general.wantref': {None: [False, 'forced']}}
assert to_tuple(await conf2.value.exportation()) == ((), (), (), ()) assert conf2.value.exportation() == {}
# #
await conf2.property.read_only() conf2.property.read_only()
assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert conf.value.exportation() == {'creole.general.wantref': {None: [False, 'forced']}}
assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert conf2.value.exportation() == {'creole.general.wantref': {None: [False, 'forced']}}
# #
await conf.option('creole.general.wantref').value.set(True) conf.option('creole.general.wantref').value.set(True)
assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',)) assert conf.value.exportation() == {'creole.general.wantref': {None: [True, 'user']}}
assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert conf2.value.exportation() == {'creole.general.wantref': {None: [False, 'forced']}}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_copy_force_store_value_metaconfig():
async def test_copy_force_store_value_metaconfig(): od1 = make_description()
descr = make_description() meta = MetaConfig([], optiondescription=od1)
async with await MetaConfig([], optiondescription=descr) as meta: conf = meta.config.new()
async with await meta.config.new(session_id='conf') as conf: assert meta.property.get() == conf.property.get()
assert await meta.property.get() == await conf.property.get() assert meta.permissive.get() == conf.permissive.get()
assert await meta.permissive.get() == await conf.permissive.get() conf.property.read_write()
await conf.property.read_write() assert conf.value.exportation() == {'creole.general.wantref': {None: [False, 'forced']}}
assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert meta.value.exportation() == {}
assert to_tuple(await meta.value.exportation()) == ((), (), (), ()) # assert not list_sessions()
assert not await list_sessions()

File diff suppressed because it is too large Load diff

View file

@ -8,22 +8,12 @@ import pytest
from tiramisu.setting import owners, groups from tiramisu.setting import owners, groups
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription, SymLinkOption, Leadership, Config, \ StrOption, OptionDescription, SymLinkOption, Leadership, Config, \
Calculation, Params, ParamOption, ParamValue, calc_value, delete_session Calculation, Params, ParamOption, ParamValue, calc_value
from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.storage import list_sessions
from .config import event_loop
def compare(calculated, expected): def compare(calculated, expected):
def convert_list(val): assert calculated == expected
if isinstance(val, list):
val = tuple(val)
return val
# convert to tuple
for idx in range(len(calculated[0])):
right_idx = expected[0].index(calculated[0][idx])
for typ in range(4):
assert convert_list(calculated[typ][idx]) == expected[typ][right_idx]
#____________________________________________________________ #____________________________________________________________
@ -76,151 +66,151 @@ def return_val3(context, value):
return value return value
@pytest.mark.asyncio def test_freeze_whole_config():
async def test_freeze_whole_config(): od1 = make_description_freeze()
descr = make_description_freeze() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() cfg.property.add('everything_frozen')
await cfg.property.add('everything_frozen') assert cfg.option('gc.dummy').value.get() is False
assert await cfg.option('gc.dummy').value.get() is False
prop = [] prop = []
try: try:
await cfg.option('gc.dummy').value.set(True) cfg.option('gc.dummy').value.set(True)
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert await cfg.option('gc.dummy').value.get() is False assert cfg.option('gc.dummy').value.get() is False
# #
await cfg.property.pop('everything_frozen') cfg.property.remove('everything_frozen')
await cfg.option('gc.dummy').value.set(True) cfg.option('gc.dummy').value.set(True)
assert await cfg.option('gc.dummy').value.get() is True assert cfg.option('gc.dummy').value.get() is True
# #
await cfg.property.add('everything_frozen') cfg.property.add('everything_frozen')
owners.addowner("everythingfrozen2") owners.addowner("everythingfrozen2")
prop = [] prop = []
try: try:
await cfg.option('gc.dummy').owner.set('everythingfrozen2') cfg.option('gc.dummy').owner.set('everythingfrozen2')
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_freeze_one_option():
async def test_freeze_one_option():
"freeze an option " "freeze an option "
descr = make_description_freeze() od1 = make_description_freeze()
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
#freeze only one option #freeze only one option
await cfg.option('gc.dummy').property.add('frozen') cfg.option('gc.dummy').property.add('frozen')
assert await cfg.option('gc.dummy').value.get() is False assert cfg.option('gc.dummy').value.get() is False
prop = [] prop = []
try: try:
await cfg.option('gc.dummy').value.set(True) cfg.option('gc.dummy').value.set(True)
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_frozen_value():
async def test_frozen_value():
"setattr a frozen value at the config level" "setattr a frozen value at the config level"
s = StrOption("string", "", default="string") s = StrOption("string", "", default="string")
descr = OptionDescription("options", "", [s]) od1 = OptionDescription("options", "", [s])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.property.add('frozen') cfg.property.add('frozen')
await cfg.option('string').property.add('frozen') cfg.option('string').property.add('frozen')
prop = [] prop = []
try: try:
await cfg.option('string').value.set('egg') cfg.option('string').value.set('egg')
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_freeze():
async def test_freeze():
"freeze a whole configuration object" "freeze a whole configuration object"
descr = make_description_freeze() od1 = make_description_freeze()
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.property.add('frozen') cfg.property.add('frozen')
await cfg.option('gc.name').property.add('frozen') cfg.option('gc.name').property.add('frozen')
prop = [] prop = []
try: try:
await cfg.option('gc.name').value.set('framework') cfg.option('gc.name').value.set('framework')
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_freeze_multi():
async def test_freeze_multi(): od1 = make_description_freeze()
descr = make_description_freeze() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() cfg.property.add('frozen')
await cfg.property.add('frozen') cfg.option('boolop').property.add('frozen')
await cfg.option('boolop').property.add('frozen')
prop = [] prop = []
try: try:
await cfg.option('boolop').value.set([True]) cfg.option('boolop').value.set([True])
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'frozen' in prop assert 'frozen' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_store_value():
async def test_force_store_value(): od1 = make_description_freeze()
descr = make_description_freeze() cfg = Config(od1)
async with await Config(descr) as cfg: compare(cfg.value.exportation(), {})
compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) cfg.property.read_write()
await cfg.option('wantref').value.set(True) compare(cfg.value.exportation(), {'wantref': {None: [False, 'forced']}, 'wantref2': {None: [False, 'forced']}, 'wantref3': {None: [[False], 'forced']}})
compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced'))) cfg.option('bool').value.set(False)
await cfg.option('wantref').value.reset() cfg.option('wantref').value.set(True)
compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) cfg.option('bool').value.reset()
assert not await list_sessions() compare(cfg.value.exportation(), {'wantref': {None: [True, 'user']}, 'wantref2': {None: [False, 'forced']}, 'wantref3': {None: [[False], 'forced']}})
cfg.option('bool').value.set(False)
cfg.option('wantref').value.reset()
cfg.option('bool').value.reset()
compare(cfg.value.exportation(), {'wantref': {None: [False, 'forced']}, 'wantref2': {None: [False, 'forced']}, 'wantref3': {None: [[False], 'forced']}})
# assert not list_sessions()
@pytest.mark.asyncio def test_force_store_value_leadership_sub():
async def test_force_store_value_leadership_sub():
b = IntOption('int', 'Test int option', multi=True, properties=('force_store_value',)) b = IntOption('int', 'Test int option', multi=True, properties=('force_store_value',))
c = StrOption('str', 'Test string option', multi=True) c = StrOption('str', 'Test string option', multi=True)
descr = Leadership("int", "", [b, c]) descr = Leadership("int", "", [b, c])
odr = OptionDescription('odr', '', [descr]) od1 = OptionDescription('odr', '', [descr])
async with await Config(odr) as cfg: cfg = Config(od1)
compare(await cfg.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',))) cfg.property.read_only()
assert not await list_sessions() compare(cfg.value.exportation(), {'int.int': {None: [[], 'forced']}})
# assert not list_sessions()
@pytest.mark.asyncio def test_force_store_value_callback():
async def test_force_store_value_callback():
b = IntOption('int', 'Test int option', Calculation(return_val), properties=('force_store_value',)) b = IntOption('int', 'Test int option', Calculation(return_val), properties=('force_store_value',))
descr = OptionDescription("int", "", [b]) od1 = OptionDescription("int", "", [b])
async with await Config(descr) as cfg: cfg = Config(od1)
compare(await cfg.value.exportation(), (('int',), (None,), (1,), ('forced',))) cfg.property.read_only()
assert not await list_sessions() compare(cfg.value.exportation(), {'int': {None: [1, 'forced']}})
# assert not list_sessions()
@pytest.mark.asyncio def test_force_store_value_callback_params():
async def test_force_store_value_callback_params():
b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamValue(2)})), properties=('force_store_value',)) b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamValue(2)})), properties=('force_store_value',))
descr = OptionDescription("int", "", [b]) od1 = OptionDescription("int", "", [b])
async with await Config(descr) as cfg: cfg = Config(od1)
compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) cfg.property.read_only()
assert not await list_sessions() compare(cfg.value.exportation(), {'int': {None: [2, 'forced']}})
# assert not list_sessions()
@pytest.mark.asyncio def test_force_store_value_callback_params_with_opt():
async def test_force_store_value_callback_params_with_opt():
a = IntOption('val1', "", 2) a = IntOption('val1', "", 2)
b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamOption(a)})), properties=('force_store_value',)) b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamOption(a)})), properties=('force_store_value',))
descr = OptionDescription("int", "", [a, b]) od1 = OptionDescription("int", "", [a, b])
async with await Config(descr) as cfg: cfg = Config(od1)
compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) cfg.property.read_only()
assert not await list_sessions() compare(cfg.value.exportation(), {'int': {None: [2, 'forced']}})
# assert not list_sessions()

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,9 @@
from tiramisu import IntOption, OptionDescription, MetaConfig, list_sessions from tiramisu import IntOption, OptionDescription, MetaConfig
from tiramisu.error import ConfigError from tiramisu.error import ConfigError
import pytest import pytest
from .config import delete_sessions, event_loop
async def make_metaconfig(): def make_metaconfig():
i1 = IntOption('i1', '') i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1) i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '') i3 = IntOption('i3', '')
@ -13,85 +12,79 @@ async def make_metaconfig():
i6 = IntOption('i6', '', properties=('disabled',)) i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6]) od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1]) od2 = OptionDescription('od2', '', [od1])
return await MetaConfig([], optiondescription=od2, session_id='metacfg1', delete_old_session=True) return MetaConfig([], optiondescription=od2, name='metacfg1')
@pytest.mark.asyncio def test_multi_parents_path():
async def test_multi_parents_path():
""" """
metacfg1 (1) --- metacfg1 (1) ---
| -- cfg1 | -- cfg1
metacfg2 (2) --- metacfg2 (2) ---
""" """
metacfg1 = await make_metaconfig() metacfg1 = make_metaconfig()
cfg1 = await metacfg1.config.new(type='config', session_id="cfg1") cfg1 = metacfg1.config.new(type='config', name="cfg1")
metacfg2 = await MetaConfig([cfg1], session_id='metacfg2', delete_old_session=True) metacfg2 = MetaConfig([cfg1], name='metacfg2')
# #
assert await metacfg1.config.path() == 'metacfg1' assert metacfg1.config.path() == 'metacfg1'
assert await metacfg2.config.path() == 'metacfg2' assert metacfg2.config.path() == 'metacfg2'
assert await cfg1.config.path() == 'metacfg2.metacfg1.cfg1' assert cfg1.config.path() == 'metacfg2.metacfg1.cfg1'
await delete_sessions([metacfg1, metacfg2])
@pytest.mark.asyncio def test_multi_parents_path_same():
async def test_multi_parents_path_same():
""" """
--- metacfg2 (1) --- --- metacfg2 (1) ---
metacfg1 --| | -- cfg1 metacfg1 --| | -- cfg1
--- metacfg3 (2) --- --- metacfg3 (2) ---
""" """
metacfg1 = await make_metaconfig() metacfg1 = make_metaconfig()
metacfg2 = await metacfg1.config.new(type='metaconfig', session_id="metacfg2") metacfg2 = metacfg1.config.new(type='metaconfig', name="metacfg2")
metacfg3 = await metacfg1.config.new(type='metaconfig', session_id="metacfg3") metacfg3 = metacfg1.config.new(type='metaconfig', name="metacfg3")
cfg1 = await metacfg2.config.new(type='config', session_id="cfg1") cfg1 = metacfg2.config.new(type='config', name="cfg1")
await metacfg3.config.add(cfg1) metacfg3.config.add(cfg1)
# #
assert await metacfg2.config.path() == 'metacfg1.metacfg2' assert metacfg2.config.path() == 'metacfg1.metacfg2'
assert await metacfg3.config.path() == 'metacfg1.metacfg3' assert metacfg3.config.path() == 'metacfg1.metacfg3'
assert await cfg1.config.path() == 'metacfg1.metacfg3.metacfg1.metacfg2.cfg1' assert cfg1.config.path() == 'metacfg1.metacfg3.metacfg1.metacfg2.cfg1'
await metacfg1.option('od1.i1').value.set(1) metacfg1.option('od1.i1').value.set(1)
await metacfg3.option('od1.i1').value.set(2) metacfg3.option('od1.i1').value.set(2)
assert await cfg1.option('od1.i1').value.get() == 1 assert cfg1.option('od1.i1').value.get() == 1
orideep = await cfg1.config.deepcopy(metaconfig_prefix="test_", session_id='test_cfg1') orideep = cfg1.config.deepcopy(metaconfig_prefix="test_", name='test_cfg1')
deep = orideep deep = orideep
while True: while True:
try: try:
children = list(await deep.config.list()) children = list(deep.config.list())
except: except:
break break
assert len(children) < 2 assert len(children) < 2
deep = children[0] deep = children[0]
assert await deep.config.path() == 'test_metacfg3.test_metacfg1.test_metacfg2.test_cfg1' assert deep.config.path() == 'test_metacfg3.test_metacfg1.test_metacfg2.test_cfg1'
assert await cfg1.option('od1.i1').value.get() == 1 assert cfg1.option('od1.i1').value.get() == 1
await delete_sessions([metacfg1, orideep])
@pytest.mark.asyncio def test_multi_parents_value():
async def test_multi_parents_value(): metacfg1 = make_metaconfig()
metacfg1 = await make_metaconfig() cfg1 = metacfg1.config.new(type='config', name="cfg1")
cfg1 = await metacfg1.config.new(type='config', session_id="cfg1") metacfg2 = MetaConfig([cfg1], name='metacfg2')
metacfg2 = await MetaConfig([cfg1], session_id='metacfg2', delete_old_session=True)
# #
assert await cfg1.option('od1.i1').value.get() == None assert cfg1.option('od1.i1').value.get() == None
assert await cfg1.option('od1.i2').value.get() == 1 assert cfg1.option('od1.i2').value.get() == 1
assert await cfg1.option('od1.i3').value.get() == None assert cfg1.option('od1.i3').value.get() == None
# #
assert await metacfg1.option('od1.i1').value.get() == None assert metacfg1.option('od1.i1').value.get() == None
assert await metacfg1.option('od1.i2').value.get() == 1 assert metacfg1.option('od1.i2').value.get() == 1
assert await metacfg1.option('od1.i3').value.get() == None assert metacfg1.option('od1.i3').value.get() == None
# #
assert await metacfg2.option('od1.i1').value.get() == None assert metacfg2.option('od1.i1').value.get() == None
assert await metacfg2.option('od1.i2').value.get() == 1 assert metacfg2.option('od1.i2').value.get() == 1
assert await metacfg2.option('od1.i3').value.get() == None assert metacfg2.option('od1.i3').value.get() == None
# #
await metacfg1.option('od1.i3').value.set(3) metacfg1.option('od1.i3').value.set(3)
assert await metacfg1.option('od1.i3').value.get() == 3 assert metacfg1.option('od1.i3').value.get() == 3
assert await cfg1.option('od1.i3').value.get() == 3 assert cfg1.option('od1.i3').value.get() == 3
assert await metacfg2.option('od1.i2').value.get() == 1 assert metacfg2.option('od1.i2').value.get() == 1
# #
await metacfg2.option('od1.i2').value.set(4) metacfg2.option('od1.i2').value.set(4)
assert await metacfg2.option('od1.i2').value.get() == 4 assert metacfg2.option('od1.i2').value.get() == 4
assert await metacfg1.option('od1.i2').value.get() == 1 assert metacfg1.option('od1.i2').value.get() == 1
assert await cfg1.option('od1.i2').value.get() == 4 assert cfg1.option('od1.i2').value.get() == 4
await delete_sessions([metacfg1, metacfg2])

View file

@ -6,24 +6,25 @@ do_autopath()
import pytest import pytest
import warnings import warnings
from tiramisu.error import ConfigError, ValueWarning
from tiramisu.error import APIError, ConfigError from tiramisu import IntOption, SymLinkOption, OptionDescription, Config, Calculation, groups
from tiramisu import IntOption, SymLinkOption, OptionDescription, Config, Calculation, groups, list_sessions
from tiramisu.i18n import _ from tiramisu.i18n import _
from .config import event_loop
try: try:
groups.family groups.family
except: except:
groups.family = groups.GroupType('family') groups.addgroup('family')
def a_func(): def a_func():
return None return None
@pytest.mark.asyncio def display_name(*args):
async def test_option_valid_name(): return 'display_name'
def test_option_valid_name():
IntOption('test', '') IntOption('test', '')
with pytest.raises(ValueError): with pytest.raises(ValueError):
IntOption(1, "") IntOption(1, "")
@ -31,22 +32,9 @@ async def test_option_valid_name():
with pytest.raises(ValueError): with pytest.raises(ValueError):
SymLinkOption(1, i) SymLinkOption(1, i)
i = SymLinkOption("test1", i) i = SymLinkOption("test1", i)
#
#
#@pytest.mark.asyncio
#async def test_option_unvalid_name():
# with pytest.raises(ValueError):
# IntOption('test.', '')
# with pytest.raises(ValueError):
# IntOption('test.val', '')
# with pytest.raises(ValueError):
# IntOption('.test', '')
# with pytest.raises(ValueError):
# OptionDescription('.test', '', [])
@pytest.mark.asyncio def test_option_get_information():
async def test_option_get_information():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
i = IntOption('test', description) i = IntOption('test', description)
@ -60,14 +48,12 @@ async def test_option_get_information():
assert i.impl_get_information('doc') == description assert i.impl_get_information('doc') == description
@pytest.mark.asyncio def test_option_get_information_config():
async def test_option_get_information_config():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
i = IntOption('test', description) i = IntOption('test', description)
od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [i])
async with await Config(od) as cfg: cfg = Config(od)
pass
with pytest.raises(ValueError): with pytest.raises(ValueError):
i.impl_get_information('noinfo') i.impl_get_information('noinfo')
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
@ -76,34 +62,56 @@ async def test_option_get_information_config():
i.impl_get_information('noinfo') i.impl_get_information('noinfo')
assert i.impl_get_information('noinfo', 'default') == 'default' assert i.impl_get_information('noinfo', 'default') == 'default'
assert i.impl_get_information('doc') == description assert i.impl_get_information('doc') == description
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_option_unknown():
async def test_option_get_information_default():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
i = IntOption('test', description) i = IntOption('test', description)
i.impl_set_information('noinfo', 'optdefault') i.impl_set_information('noinfo', 'optdefault')
od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [i])
async with await Config(od) as cfg: cfg = Config(od)
# #
assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault' with pytest.raises(ConfigError):
# cfg.option('test').unknown.get()
await cfg.option('test').information.set('noinfo', 'notdefault') with pytest.raises(ConfigError):
assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault' # only choice
assert not await list_sessions() cfg.option('test').value.list()
@pytest.mark.asyncio def test_option_description():
async def test_option_get_information_config2(): description = "it's ok"
i = IntOption('test', description)
od = OptionDescription('od', 'od', [i])
od2 = OptionDescription('od', '', [od])
cfg = Config(od2)
assert cfg.option('od').description() == 'od'
assert cfg.option('od.test').description() == description
def test_option_get_information_default():
description = "it's ok"
string = 'some informations'
i = IntOption('test', description)
i.impl_set_information('noinfo', 'optdefault')
od = OptionDescription('od', '', [i])
cfg = Config(od)
#
assert cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault'
#
cfg.option('test').information.set('noinfo', 'notdefault')
assert cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault'
# assert not list_sessions()
def test_option_get_information_config2():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
i = IntOption('test', description) i = IntOption('test', description)
i.impl_set_information('info', string) i.impl_set_information('info', string)
od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [i])
async with await Config(od) as cfg: cfg = Config(od)
pass
with pytest.raises(ValueError): with pytest.raises(ValueError):
i.impl_get_information('noinfo') i.impl_get_information('noinfo')
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
@ -113,11 +121,10 @@ async def test_option_get_information_config2():
i.impl_get_information('noinfo') i.impl_get_information('noinfo')
assert i.impl_get_information('noinfo', 'default') == 'default' assert i.impl_get_information('noinfo', 'default') == 'default'
assert i.impl_get_information('doc') == description assert i.impl_get_information('doc') == description
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_optiondescription_get_information():
async def test_optiondescription_get_information():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
o = OptionDescription('test', description, []) o = OptionDescription('test', description, [])
@ -127,34 +134,31 @@ async def test_optiondescription_get_information():
o.impl_get_information('noinfo') o.impl_get_information('noinfo')
assert o.impl_get_information('noinfo', 'default') == 'default' assert o.impl_get_information('noinfo', 'default') == 'default'
assert o.impl_get_information('doc') == description assert o.impl_get_information('doc') == description
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_option_isoptiondescription():
async def test_option_isoptiondescription():
i = IntOption('test', '') i = IntOption('test', '')
od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [i])
od = OptionDescription('od', '', [od]) od = OptionDescription('od', '', [od])
async with await Config(od) as cfg: cfg = Config(od)
assert await cfg.option('od').option.isoptiondescription() assert cfg.option('od').isoptiondescription()
assert not await cfg.option('od.test').option.isoptiondescription() assert not cfg.option('od.test').isoptiondescription()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_option_double():
async def test_option_double():
i = IntOption('test', '') i = IntOption('test', '')
od = OptionDescription('od1', '', [i]) od = OptionDescription('od1', '', [i])
od = OptionDescription('od2', '', [od]) od = OptionDescription('od2', '', [od])
od = OptionDescription('od3', '', [od]) od = OptionDescription('od3', '', [od])
async with await Config(od) as cfg: cfg = Config(od)
assert await cfg.option('od2.od1.test').value.get() is None assert cfg.option('od2.od1.test').value.get() is None
assert await cfg.option('od2').option('od1').option('test').value.get() is None assert cfg.option('od2').option('od1').option('test').value.get() is None
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_option_multi():
async def test_option_multi():
IntOption('test', '', multi=True) IntOption('test', '', multi=True)
IntOption('test', '', multi=True, default_multi=1) IntOption('test', '', multi=True, default_multi=1)
IntOption('test', '', default=[1], multi=True, default_multi=1) IntOption('test', '', default=[1], multi=True, default_multi=1)
@ -164,40 +168,31 @@ async def test_option_multi():
#unvalid default_multi #unvalid default_multi
with pytest.raises(ValueError): with pytest.raises(ValueError):
IntOption('test', '', multi=True, default_multi='yes') IntOption('test', '', multi=True, default_multi='yes')
assert not await list_sessions() # assert not list_sessions()
#@pytest.mark.asyncio def test_unknown_option():
#async def test_option_multi_legacy():
# #not default_multi with callback
# #with pytest.raises(ValueError):
# IntOption('test', '', multi=True, default_multi=1, callback=a_func)")
@pytest.mark.asyncio
async def test_unknown_option():
i = IntOption('test', '') i = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
od2 = OptionDescription('od', '', [od1]) od2 = OptionDescription('od', '', [od1])
async with await Config(od2) as cfg: cfg = Config(od2)
# test is an option, not an optiondescription # test is an option, not an optiondescription
with pytest.raises(TypeError): with pytest.raises(TypeError):
await cfg.option('od.test.unknown').value.get() cfg.option('od.test.unknown').value.get()
# unknown is an unknown option # unknown is an unknown option
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
await cfg.option('unknown').value.get() cfg.option('unknown').value.get()
# unknown is an unknown option # unknown is an unknown option
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
await cfg.option('od.unknown').value.get() cfg.option('od.unknown').value.get()
# unknown is an unknown optiondescription # unknown is an unknown optiondescription
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
await cfg.option('od.unknown.suboption').value.get() cfg.option('od.unknown.suboption').value.get()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_optiondescription_list():
async def test_optiondescription_list(): groups.addgroup('notfamily1')
groups.notfamily1 = groups.GroupType('notfamily1')
i = IntOption('test', '') i = IntOption('test', '')
i2 = IntOption('test', '') i2 = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
@ -206,31 +201,30 @@ async def test_optiondescription_list():
od3.impl_set_group_type(groups.notfamily1) od3.impl_set_group_type(groups.notfamily1)
od2 = OptionDescription('od', '', [od1, od3]) od2 = OptionDescription('od', '', [od1, od3])
od4 = OptionDescription('od', '', [od2]) od4 = OptionDescription('od', '', [od2])
async with await Config(od4) as cfg: cfg = Config(od4)
assert len(list(await cfg.option('od').list('option'))) == 0 assert len(list(cfg.option('od').list('option'))) == 0
assert len(list(await cfg.option('od').list('optiondescription'))) == 2 assert len(list(cfg.option('od').list('optiondescription'))) == 2
assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.family))) == 1 assert len(list(cfg.option('od').list('optiondescription', group_type=groups.family))) == 1
assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1 assert len(list(cfg.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1
assert len(list(await cfg.option('od.od').list('option'))) == 1 assert len(list(cfg.option('od.od').list('option'))) == 1
assert len(list(await cfg.option('od.od2').list('option'))) == 1 assert len(list(cfg.option('od.od2').list('option'))) == 1
try: try:
list(await cfg.option('od').list('unknown')) list(cfg.option('od').list('unknown'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
try: try:
list(await cfg.option('od').list('option', group_type='toto')) list(cfg.option('od').list('option', group_type='toto'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_optiondescription_group():
async def test_optiondescription_group(): groups.addgroup('notfamily')
groups.notfamily = groups.GroupType('notfamily')
i = IntOption('test', '') i = IntOption('test', '')
i2 = IntOption('test', '') i2 = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
@ -238,30 +232,29 @@ async def test_optiondescription_group():
od3 = OptionDescription('od2', '', [i2]) od3 = OptionDescription('od2', '', [i2])
od3.impl_set_group_type(groups.notfamily) od3.impl_set_group_type(groups.notfamily)
od2 = OptionDescription('od', '', [od1, od3]) od2 = OptionDescription('od', '', [od1, od3])
async with await Config(od2) as cfg: cfg = Config(od2)
assert len(list(await cfg.option.list('option'))) == 0 assert len(list(cfg.option.list('option'))) == 0
assert len(list(await cfg.option.list('optiondescription'))) == 2 assert len(list(cfg.option.list('optiondescription'))) == 2
assert len(list(await cfg.option.list('optiondescription', group_type=groups.family))) == 1 assert len(list(cfg.option.list('optiondescription', group_type=groups.family))) == 1
assert len(list(await cfg.option.list('optiondescription', group_type=groups.notfamily))) == 1 assert len(list(cfg.option.list('optiondescription', group_type=groups.notfamily))) == 1
try: try:
list(await cfg.option.list('unknown')) list(cfg.option.list('unknown'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
try: try:
list(await cfg.option.list('option', group_type='toto')) list(cfg.option.list('option', group_type='toto'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_optiondescription_group_redefined():
async def test_optiondescription_group_redefined():
try: try:
groups.notfamily = groups.GroupType('notfamily') groups.addgroup('notfamily')
except: except:
pass pass
i = IntOption('test', '') i = IntOption('test', '')
@ -269,59 +262,93 @@ async def test_optiondescription_group_redefined():
od1.impl_set_group_type(groups.family) od1.impl_set_group_type(groups.family)
with pytest.raises(ValueError): with pytest.raises(ValueError):
od1.impl_set_group_type(groups.notfamily) od1.impl_set_group_type(groups.notfamily)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_optiondescription_group_leadership():
async def test_optiondescription_group_leadership():
i = IntOption('test', '') i = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
od1.impl_set_group_type(groups.leadership) od1.impl_set_group_type(groups.leadership)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_asign_optiondescription():
async def test_asign_optiondescription():
i = IntOption('test', '') i = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
od2 = OptionDescription('od', '', [od1]) od2 = OptionDescription('od', '', [od1])
async with await Config(od2) as cfg: cfg = Config(od2)
with pytest.raises(APIError): with pytest.raises(ConfigError):
await cfg.option('od').value.set('test') cfg.option('od').value.set('test')
with pytest.raises(APIError): with pytest.raises(ConfigError):
await cfg.option('od').value.reset() cfg.option('od').value.reset()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_intoption():
async def test_intoption():
i1 = IntOption('test1', 'description', min_number=3) i1 = IntOption('test1', 'description', min_number=3)
i2 = IntOption('test2', 'description', max_number=3) i2 = IntOption('test2', 'description', max_number=3)
od = OptionDescription('od', '', [i1, i2]) i3 = IntOption('test3', 'description', min_number=3, max_number=6, warnings_only=True)
async with await Config(od) as cfg: od = OptionDescription('od', '', [i1, i2, i3])
cfg = Config(od)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('test1').value.set(2) cfg.option('test1').value.set(2)
await cfg.option('test1').value.set(3) cfg.option('test1').value.set(3)
await cfg.option('test1').value.set(4) assert cfg.option('test1').value.valid() is True
await cfg.option('test2').value.set(2) cfg.option('test1').value.set(4)
await cfg.option('test2').value.set(3) cfg.option('test2').value.set(2)
cfg.option('test2').value.set(3)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('test2').value.set(4) cfg.option('test2').value.set(4)
assert not await list_sessions() warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
cfg.option('test3').value.set(2)
assert cfg.option('test3').value.valid() is True
assert len(w) == 1
with warnings.catch_warnings(record=True) as w:
cfg.option('test3').value.set(7)
assert cfg.option('test3').value.valid() is True
cfg.option('test3').value.set(4)
assert cfg.option('test3').value.valid() is True
assert len(w) == 1
# assert not list_sessions()
@pytest.mark.asyncio def test_option_not_in_config():
async def test_get_display_type():
i1 = IntOption('test1', 'description', min_number=3)
assert i1.get_display_type() == _('integer')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_option_not_in_config():
i1 = IntOption('test1', 'description', min_number=3) i1 = IntOption('test1', 'description', min_number=3)
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
i1.impl_getpath() i1.impl_getpath()
assert not await list_sessions() # assert not list_sessions()
def test_option_unknown_func():
i1 = IntOption('test1', 'description', min_number=3)
i2 = IntOption('test2', 'description', max_number=3)
i3 = IntOption('test3', 'description', min_number=3, max_number=6, warnings_only=True)
od = OptionDescription('od', '', [i1, i2, i3])
cfg = Config(od)
with pytest.raises(ConfigError):
cfg.option('test1').value.unknown()
def test_option_with_index():
i1 = IntOption('test1', 'description', [4, 5], min_number=3, multi=True)
i2 = IntOption('test2', 'description', max_number=3)
i3 = IntOption('test3', 'description', min_number=3, max_number=6, warnings_only=True)
od = OptionDescription('od', '', [i1, i2, i3])
cfg = Config(od)
with pytest.raises(ConfigError):
cfg.option('test1', 0).value.get()
def test_option_display_name():
i1 = IntOption('test1', 'description', min_number=3)
i2 = IntOption('test2', 'description', max_number=3)
i3 = IntOption('test3', 'description', min_number=3, max_number=6, warnings_only=True)
od = OptionDescription('od', '', [i1, i2, i3])
cfg = Config(od,
display_name=display_name,
)
assert cfg.option('test1').name() == 'test1'
assert cfg.option('test1').doc() == 'display_name'

File diff suppressed because it is too large Load diff

View file

@ -6,9 +6,8 @@ import pytest
from tiramisu.setting import owners from tiramisu.setting import owners
from tiramisu.error import PropertiesOptionError, ConfigError, LeadershipError from tiramisu.error import PropertiesOptionError, ConfigError, LeadershipError
from tiramisu import IntOption, FloatOption, StrOption, ChoiceOption, \ from tiramisu import IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, OptionDescription, Leadership, Config, undefined, delete_session BoolOption, OptionDescription, Leadership, Config, undefined
from tiramisu.storage import list_sessions from .config import config_type, get_config
from .config import config_type, get_config, event_loop
owners.addowner("frozenmultifollower") owners.addowner("frozenmultifollower")
@ -40,8 +39,7 @@ def make_description():
#____________________________________________________________ #____________________________________________________________
# default values # default values
@pytest.mark.asyncio def test_default_is_none(config_type):
async def test_default_is_none(config_type):
""" """
Most constructors take a ``default`` argument that specifies the default Most constructors take a ``default`` argument that specifies the default
value of the option. If this argument is not supplied the default value is value of the option. If this argument is not supplied the default value is
@ -49,246 +47,235 @@ async def test_default_is_none(config_type):
""" """
dummy1 = BoolOption('dummy1', 'doc dummy') dummy1 = BoolOption('dummy1', 'doc dummy')
dummy2 = BoolOption('dummy2', 'doc dummy') dummy2 = BoolOption('dummy2', 'doc dummy')
group = OptionDescription('group', '', [dummy1, dummy2]) od1 = OptionDescription('group', '', [dummy1, dummy2])
async with await Config(group) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
# so when the default value is not set, there is actually a default value # so when the default value is not set, there is actually a default value
assert await cfg.option('dummy1').value.get() is None assert cfg.option('dummy1').value.get() is None
assert await cfg.option('dummy2').value.get() is None assert cfg.option('dummy2').value.get() is None
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_set_defaut_value_from_option_object():
async def test_set_defaut_value_from_option_object():
"""Options have an available default setting and can give it back""" """Options have an available default setting and can give it back"""
b = BoolOption("boolean", "", default=False) b = BoolOption("boolean", "", default=False)
assert b.impl_getdefault() is False assert b.impl_getdefault() is False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_default_on_freeze():
async def test_force_default_on_freeze():
"a frozen option wich is forced returns his default" "a frozen option wich is forced returns his default"
dummy1 = BoolOption('dummy1', 'doc dummy', default=False, properties=('force_default_on_freeze',)) dummy1 = BoolOption('dummy1', 'doc dummy', default=False, properties=('force_default_on_freeze',))
dummy2 = BoolOption('dummy2', 'doc dummy', default=True) dummy2 = BoolOption('dummy2', 'doc dummy', default=True)
group = OptionDescription('group', '', [dummy1, dummy2]) od1 = OptionDescription('group', '', [dummy1, dummy2])
async with await Config(group) as cfg_ori: cfg_ori = Config(od1)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = cfg_ori cfg = cfg_ori
# FIXME cfg = await get_config(cfg_ori, config_type) # FIXME cfg = get_config(cfg_ori, config_type)
owner = await cfg.owner.get() owner = cfg.owner.get()
await cfg.option('dummy1').value.set(True) cfg.option('dummy1').value.set(True)
await cfg.option('dummy2').value.set(False) cfg.option('dummy2').value.set(False)
assert await cfg.option('dummy1').owner.get() == owner assert cfg.option('dummy1').owner.get() == owner
assert await cfg.option('dummy2').owner.get() == owner assert cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
await cfg_ori.option('dummy1').property.add('frozen') cfg_ori.option('dummy1').property.add('frozen')
await cfg_ori.option('dummy2').property.add('frozen') cfg_ori.option('dummy2').property.add('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy1').value.get() is False assert cfg.option('dummy1').value.get() is False
assert await cfg.option('dummy2').value.get() is False assert cfg.option('dummy2').value.get() is False
assert await cfg.option('dummy1').owner.isdefault() assert cfg.option('dummy1').owner.isdefault()
assert await cfg.option('dummy2').owner.get() == owner assert cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg_ori.option('dummy2').owner.set('frozen') cfg_ori.option('dummy2').owner.set('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('dummy1').value.reset() cfg.option('dummy1').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
await cfg_ori.option('dummy1').property.pop('frozen') cfg_ori.option('dummy1').property.remove('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy1').value.reset() cfg.option('dummy1').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
await cfg.option('dummy1').property.add('frozen') cfg.option('dummy1').property.add('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('dummy2').owner.set('frozen') cfg.option('dummy2').owner.set('frozen')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_default_on_freeze_multi():
async def test_force_default_on_freeze_multi():
dummy1 = BoolOption('dummy1', 'doc dummy', default=[False], properties=('force_default_on_freeze',), multi=True) dummy1 = BoolOption('dummy1', 'doc dummy', default=[False], properties=('force_default_on_freeze',), multi=True)
dummy2 = BoolOption('dummy2', 'doc dummy', default=[True], multi=True) dummy2 = BoolOption('dummy2', 'doc dummy', default=[True], multi=True)
group = OptionDescription('group', '', [dummy1, dummy2]) od1 = OptionDescription('group', '', [dummy1, dummy2])
async with await Config(group) as cfg_ori: cfg_ori = Config(od1)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = cfg_ori cfg = cfg_ori
# FIXME cfg = await get_config(cfg_ori, config_type) # FIXME cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy1').value.set([undefined, True]) default = cfg.option('dummy1').value.default()[0]
await cfg.option('dummy2').value.set([undefined, False]) cfg.option('dummy1').value.set([default, True])
owner = await cfg.owner.get() default = cfg.option('dummy2').value.default()[0]
assert await cfg.option('dummy1').owner.get() == owner cfg.option('dummy2').value.set([default, False])
assert await cfg.option('dummy2').owner.get() == owner owner = cfg.owner.get()
assert cfg.option('dummy1').owner.get() == owner
assert cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
await cfg_ori.option('dummy1').property.add('frozen') cfg_ori.option('dummy1').property.add('frozen')
await cfg_ori.option('dummy2').property.add('frozen') cfg_ori.option('dummy2').property.add('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy1').value.get() == [False] assert cfg.option('dummy1').value.get() == [False]
assert await cfg.option('dummy2').value.get() == [True, False] assert cfg.option('dummy2').value.get() == [True, False]
assert await cfg.option('dummy1').owner.isdefault() assert cfg.option('dummy1').owner.isdefault()
assert await cfg.option('dummy2').owner.get() == owner assert cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg_ori.option('dummy2').owner.set('owner') cfg_ori.option('dummy2').owner.set('owner')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('dummy2').value.reset() cfg.option('dummy2').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# await cfg.send() # cfg.send()
await cfg_ori.option('dummy1').property.pop('frozen') cfg_ori.option('dummy1').property.remove('frozen')
# cfg = await get_config(cfg_ori, config_type) # cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy1').value.reset() cfg.option('dummy1').value.reset()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_default_on_freeze_leader():
async def test_force_default_on_freeze_leader():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze',)) dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze',))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True) dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr]) od1 = OptionDescription("root", "", [descr])
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await Config(descr, session_id='error') Config(od1)
await delete_session('error') # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_force_metaconfig_on_freeze_leader():
async def test_force_metaconfig_on_freeze_leader():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze',)) dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze',))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True) dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr]) od1 = OptionDescription("root", "", [descr])
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await Config(descr, session_id='error') Config(od1)
await delete_session('error') # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_force_default_on_freeze_leader_frozen():
async def test_force_default_on_freeze_leader_frozen():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze', 'frozen')) dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze', 'frozen'))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True) dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr]) od1 = OptionDescription("root", "", [descr])
async with await Config(descr) as cfg: cfg = Config(od1)
with pytest.raises(LeadershipError): with pytest.raises(LeadershipError):
await cfg.option('dummy1.dummy1').property.pop('frozen') cfg.option('dummy1.dummy1').property.remove('frozen')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_metaconfig_on_freeze_leader_frozen():
async def test_force_metaconfig_on_freeze_leader_frozen():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze', 'frozen')) dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze', 'frozen'))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True) dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr]) od1 = OptionDescription("root", "", [descr])
async with await Config(descr) as cfg: cfg = Config(od1)
with pytest.raises(LeadershipError): with pytest.raises(LeadershipError):
await cfg.option('dummy1.dummy1').property.pop('frozen') cfg.option('dummy1.dummy1').property.remove('frozen')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_force_default_on_freeze_follower(config_type):
async def test_force_default_on_freeze_follower(config_type):
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('notunique',)) dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('notunique',))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True, properties=('force_default_on_freeze',)) dummy2 = BoolOption('dummy2', 'Test string option', multi=True, properties=('force_default_on_freeze',))
descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr]) od1 = OptionDescription("root", "", [descr])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy1.dummy1').value.set([True]) cfg.option('dummy1.dummy1').value.set([True])
await cfg.option('dummy1.dummy2', 0).value.set(False) cfg.option('dummy1.dummy2', 0).value.set(False)
assert await cfg.option('dummy1.dummy1').value.get() == [True] assert cfg.option('dummy1.dummy1').value.get() == [True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == False assert cfg.option('dummy1.dummy2', 0).value.get() == False
assert await cfg.option('dummy1.dummy1').owner.get() == 'user' assert cfg.option('dummy1.dummy1').owner.get() == 'user'
assert await cfg.option('dummy1.dummy2', 0).owner.get() == 'user' assert cfg.option('dummy1.dummy2', 0).owner.get() == 'user'
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('dummy1.dummy2').property.add('frozen') cfg_ori.option('dummy1.dummy2').property.add('frozen')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy1.dummy1').value.get() == [True] assert cfg.option('dummy1.dummy1').value.get() == [True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == None assert cfg.option('dummy1.dummy2', 0).value.get() == None
assert await cfg.option('dummy1.dummy1').owner.get() == 'user' assert cfg.option('dummy1.dummy1').owner.get() == 'user'
assert await cfg.option('dummy1.dummy2', 0).owner.isdefault() assert cfg.option('dummy1.dummy2', 0).owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower') cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('dummy1.dummy2').property.pop('frozen') cfg_ori.option('dummy1.dummy2').property.remove('frozen')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy1.dummy1').value.set([True, True]) cfg.option('dummy1.dummy1').value.set([True, True])
await cfg.option('dummy1.dummy2', 1).value.set(False) cfg.option('dummy1.dummy2', 1).value.set(False)
assert await cfg.option('dummy1.dummy1').value.get() == [True, True] assert cfg.option('dummy1.dummy1').value.get() == [True, True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == False assert cfg.option('dummy1.dummy2', 0).value.get() == False
assert await cfg.option('dummy1.dummy2', 1).value.get() == False assert cfg.option('dummy1.dummy2', 1).value.get() == False
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('dummy1.dummy2').property.add('frozen') cfg_ori.option('dummy1.dummy2').property.add('frozen')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy1.dummy1').value.get() == [True, True] assert cfg.option('dummy1.dummy1').value.get() == [True, True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == None assert cfg.option('dummy1.dummy2', 0).value.get() == None
assert await cfg.option('dummy1.dummy2', 1).value.get() == None assert cfg.option('dummy1.dummy2', 1).value.get() == None
# #
await cfg.option('dummy1.dummy1').value.pop(1) cfg.option('dummy1.dummy1').value.pop(1)
assert await cfg.option('dummy1.dummy1').value.get() == [True] assert cfg.option('dummy1.dummy1').value.get() == [True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == None assert cfg.option('dummy1.dummy2', 0).value.get() == None
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('dummy1.dummy2').property.pop('frozen') cfg_ori.option('dummy1.dummy2').property.remove('frozen')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy1.dummy1').value.get() == [True] assert cfg.option('dummy1.dummy1').value.get() == [True]
assert await cfg.option('dummy1.dummy2', 0).value.get() == False assert cfg.option('dummy1.dummy2', 0).value.get() == False
# #
await cfg.option('dummy1.dummy1').value.set([True, True]) cfg.option('dummy1.dummy1').value.set([True, True])
assert await cfg.option('dummy1.dummy2', 0).value.get() == False assert cfg.option('dummy1.dummy2', 0).value.get() == False
assert await cfg.option('dummy1.dummy2', 1).value.get() == None assert cfg.option('dummy1.dummy2', 1).value.get() == None
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_overrides_changes_option_value(config_type):
async def test_overrides_changes_option_value(config_type):
"with config.override(), the default is changed and the value is changed" "with config.override(), the default is changed and the value is changed"
descr = OptionDescription("test", "", [ od1 = OptionDescription("test", "", [
BoolOption("b", "", default=False)]) BoolOption("b", "", default=False)])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('b').value.set(True) cfg.option('b').value.set(True)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choice_with_no_default(config_type):
async def test_choice_with_no_default(config_type): od1 = OptionDescription("test", "", [
descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"))]) ChoiceOption("backend", "", ("c", "cli"))])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('backend').value.get() is None assert cfg.option('backend').value.get() is None
await cfg.option('backend').value.set('c') cfg.option('backend').value.set('c')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_choice_with_default(config_type):
async def test_choice_with_default(config_type): od1 = OptionDescription("test", "", [
descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"), default="cli")]) ChoiceOption("backend", "", ("c", "cli"), default="cli")])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('backend').value.get() == 'cli' assert cfg.option('backend').value.get() == 'cli'
assert not await list_sessions() # assert not list_sessions()

View file

@ -6,9 +6,8 @@ import pytest
from tiramisu.setting import owners, groups from tiramisu.setting import owners, groups
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription, SymLinkOption, Leadership, Config StrOption, OptionDescription, SymLinkOption, Leadership, Config
from tiramisu.error import ConfigError, ConstError, PropertiesOptionError, APIError from tiramisu.error import ConfigError, ConstError, PropertiesOptionError
from tiramisu.storage import list_sessions from .config import config_type, get_config
from .config import config_type, get_config, event_loop
owners.addowner("readonly2") owners.addowner("readonly2")
@ -37,217 +36,214 @@ def make_description():
return descr return descr
@pytest.mark.asyncio def test_default_owner(config_type):
async def test_default_owner(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
await cfg.option('dummy').value.set(True) cfg.option('dummy').value.set(True)
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('dummy').owner.get() == owner assert cfg.option('dummy').owner.get() == owner
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_owner_unknown_func(config_type):
async def test_hidden_owner(): gcdummy = BoolOption('dummy', 'dummy', default=False)
od1 = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(od1)
cfg = get_config(cfg, config_type)
with pytest.raises(ConfigError):
owner = cfg.option('dummy').owner.unknown()
# assert not list_sessions()
def test_hidden_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',)) gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',))
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
#with pytest.raises(PropertiesOptionError): #with pytest.raises(PropertiesOptionError):
# await cfg.forcepermissive.option('dummy').owner.get() # cfg.forcepermissive.option('dummy').owner.get()
#with pytest.raises(PropertiesOptionError): #with pytest.raises(PropertiesOptionError):
# await cfg.option('dummy').owner.isdefault() # cfg.option('dummy').owner.isdefault()
#with pytest.raises(PropertiesOptionError): #with pytest.raises(PropertiesOptionError):
# await cfg.forcepermissive.option('dummy').owner.isdefault() # cfg.forcepermissive.option('dummy').owner.isdefault()
await cfg.permissive.add('hidden') cfg.permissive.add('hidden')
await cfg.forcepermissive.option('dummy').value.get() cfg.forcepermissive.option('dummy').value.get()
await cfg.forcepermissive.option('dummy').owner.isdefault() cfg.forcepermissive.option('dummy').owner.isdefault()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_addowner(config_type):
async def test_addowner(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
assert await cfg.option('dummy').owner.isdefault() assert cfg.option('dummy').owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.owner.set('gen_config') cfg_ori.owner.set('gen_config')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy').value.set(True) cfg.option('dummy').value.set(True)
assert await cfg.option('dummy').owner.get() == owners.gen_config assert cfg.option('dummy').owner.get() == owners.gen_config
assert not await cfg.option('dummy').owner.isdefault() assert not cfg.option('dummy').owner.isdefault()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_addowner_multiple_time():
async def test_addowner_multiple_time():
owners.addowner("testowner2") owners.addowner("testowner2")
with pytest.raises(ConstError): with pytest.raises(ConstError):
owners.addowner("testowner2") owners.addowner("testowner2")
@pytest.mark.asyncio def test_delete_owner():
async def test_delete_owner():
owners.addowner('deleted2') owners.addowner('deleted2')
with pytest.raises(ConstError): with pytest.raises(ConstError):
del(owners.deleted2) del(owners.deleted2)
@pytest.mark.asyncio def test_owner_is_not_a_string(config_type):
async def test_owner_is_not_a_string(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == owners.default assert cfg.option('dummy').owner.get() == owners.default
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu': if config_type == 'tiramisu':
assert isinstance(await cfg.option('dummy').owner.get(), owners.Owner) assert isinstance(cfg.option('dummy').owner.get(), owners.Owner)
await cfg.option('dummy').value.set(True) cfg.option('dummy').value.set(True)
assert await cfg.option('dummy').owner.get() == 'user' assert cfg.option('dummy').owner.get() == 'user'
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_without_valid_owner(config_type):
async def test_setowner_without_valid_owner(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_for_value(config_type):
async def test_setowner_for_value(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg_ori.option('dummy').owner.set('new2') cfg_ori.option('dummy').owner.set('new2')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy').value.set(False) cfg.option('dummy').value.set(False)
assert await cfg.option('dummy').owner.get() == owners.user assert cfg.option('dummy').owner.get() == owners.user
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('dummy').owner.set('new2') cfg_ori.option('dummy').owner.set('new2')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').owner.get() == owners.new2 assert cfg.option('dummy').owner.get() == owners.new2
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_forbidden(config_type):
async def test_setowner_forbidden(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg_ori.owner.set('default') cfg_ori.owner.set('default')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('dummy').value.set(False) cfg.option('dummy').value.set(False)
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg_ori.option('dummy').owner.set('default') cfg_ori.option('dummy').owner.set('default')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_read_only(config_type):
async def test_setowner_read_only(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) od1 = OptionDescription('tiramisu', '', [gcdummy])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('dummy').owner.get() == 'default' assert cfg.option('dummy').owner.get() == 'default'
await cfg.option('dummy').value.set(False) cfg.option('dummy').value.set(False)
assert await cfg.option('dummy').owner.get() == owners.user assert cfg.option('dummy').owner.get() == owners.user
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.property.read_only() cfg_ori.property.read_only()
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg_ori.option('dummy').owner.set('readonly2') cfg_ori.option('dummy').owner.set('readonly2')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('dummy').owner.get() == owners.user assert cfg.option('dummy').owner.get() == owners.user
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_optiondescription(config_type):
async def test_setowner_optiondescription(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr1 = OptionDescription('tiramisu', '', [gcdummy]) descr1 = OptionDescription('tiramisu', '', [gcdummy])
descr = OptionDescription('tiramisu', '', [descr1]) od1 = OptionDescription('tiramisu', '', [descr1])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(APIError): with pytest.raises(ConfigError):
await cfg.option('tiramisu').owner.get() cfg.option('tiramisu').owner.get()
with pytest.raises(APIError): with pytest.raises(ConfigError):
await cfg.option('tiramisu').owner.set('user') cfg.option('tiramisu').owner.set('user')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_setowner_symlinkoption(config_type):
async def test_setowner_symlinkoption(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
s = SymLinkOption('symdummy', gcdummy) s = SymLinkOption('symdummy', gcdummy)
descr1 = OptionDescription('tiramisu', '', [gcdummy, s]) descr1 = OptionDescription('tiramisu', '', [gcdummy, s])
descr = OptionDescription('tiramisu', '', [descr1]) od1 = OptionDescription('tiramisu', '', [descr1])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od1)
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('tiramisu.symdummy').owner.isdefault() assert cfg.option('tiramisu.symdummy').owner.isdefault()
await cfg.option('tiramisu.dummy').value.set(True) cfg.option('tiramisu.dummy').value.set(True)
assert not await cfg.option('tiramisu.symdummy').owner.isdefault() assert not cfg.option('tiramisu.symdummy').owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg_ori.option('tiramisu.symdummy').owner.set('user') cfg_ori.option('tiramisu.symdummy').owner.set('user')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_owner_leadership(config_type):
async def test_owner_leadership(config_type):
b = IntOption('int', 'Test int option', default=[0], multi=True) b = IntOption('int', 'Test int option', default=[0], multi=True)
c = StrOption('str', 'Test string option', multi=True) c = StrOption('str', 'Test string option', multi=True)
descr = Leadership("int", "", [b, c]) descr = Leadership("int", "", [b, c])
od = OptionDescription('od', '', [descr]) od1 = OptionDescription('od', '', [descr])
async with await Config(od) as cfg_ori: cfg_ori = Config(od1)
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg_ori.option('int.str', 0).owner.set('user') cfg_ori.option('int.str', 0).owner.set('user')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('int.int').value.set([0, 1]) cfg.option('int.int').value.set([0, 1])
await cfg.option('int.str', 0).value.set('yes') cfg.option('int.str', 0).value.set('yes')
assert not await cfg.option('int.str', 0).owner.isdefault() assert not cfg.option('int.str', 0).owner.isdefault()
assert await cfg.option('int.str', 1).owner.isdefault() assert cfg.option('int.str', 1).owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('int.str', 0).owner.set('user') cfg_ori.option('int.str', 0).owner.set('user')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('int.str', 0).owner.get() == owners.user assert cfg.option('int.str', 0).owner.get() == owners.user
assert await cfg.option('int.str', 1).owner.isdefault() assert cfg.option('int.str', 1).owner.isdefault()
assert await cfg.option('int.str', 0).value.get() == 'yes' assert cfg.option('int.str', 0).value.get() == 'yes'
assert await cfg.option('int.str', 1).value.get() == None assert cfg.option('int.str', 1).value.get() == None
assert not await list_sessions() # assert not list_sessions()

File diff suppressed because it is too large Load diff

View file

@ -9,8 +9,7 @@ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
PasswordOption, StrOption, DateOption, OptionDescription, Config, \ PasswordOption, StrOption, DateOption, OptionDescription, Config, \
Calculation, Params, ParamOption, ParamValue, calc_value Calculation, Params, ParamOption, ParamValue, calc_value
from tiramisu.error import PropertiesOptionError from tiramisu.error import PropertiesOptionError
from tiramisu.storage import list_sessions from .config import config_type, get_config
from .config import config_type, get_config, event_loop
def make_description(): def make_description():
@ -49,73 +48,70 @@ def make_description():
# ____________________________________________________________ # ____________________________________________________________
@pytest.mark.asyncio def test_is_hidden(config_type):
async def test_is_hidden(config_type): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() assert not 'frozen' in cfg.forcepermissive.option('gc.dummy').property.get()
assert not 'frozen' in await cfg.forcepermissive.option('gc.dummy').property.get() cfg = get_config(cfg, config_type)
cfg = await get_config(cfg, config_type)
# setattr # setattr
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() == False cfg.option('gc.dummy').value.get() == False
# getattr # getattr
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() cfg.option('gc.dummy').value.get()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_group_is_hidden(config_type):
async def test_group_is_hidden(config_type): od1 = make_description()
descr = make_description() cfg_ori = Config(od1)
async with await Config(descr) as cfg_ori: cfg_ori.property.read_write()
await cfg_ori.property.read_write() cfg_ori.option('gc').property.add('hidden')
await cfg_ori.option('gc').property.add('hidden') cfg = get_config(cfg_ori, config_type)
cfg = await get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() cfg.option('gc.dummy').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
assert 'hidden' in await cfg_ori.forcepermissive.option('gc').property.get() assert 'hidden' in cfg_ori.forcepermissive.option('gc').property.get()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('gc.float').value.get() cfg.option('gc.float').value.get()
# manually set the subconfigs to "show" # manually set the subconfigs to "show"
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('gc').property.pop('hidden') cfg_ori.forcepermissive.option('gc').property.remove('hidden')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert not 'hidden' in await cfg.option('gc').property.get() assert not 'hidden' in cfg.option('gc').property.get()
assert await cfg.option('gc.float').value.get() == 2.3 assert cfg.option('gc.float').value.get() == 2.3
#dummy est en hide #dummy est en hide
prop = [] prop = []
try: try:
await cfg.option('gc.dummy').value.set(False) cfg.option('gc.dummy').value.set(False)
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
assert 'disabled' in prop assert 'disabled' in prop
else: else:
assert 'hidden' in prop assert 'hidden' in prop
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_group_is_hidden_multi(config_type):
async def test_group_is_hidden_multi(config_type): od1 = make_description()
descr = make_description() cfg_ori = Config(od1)
async with await Config(descr) as cfg_ori: cfg_ori.property.read_write()
await cfg_ori.property.read_write() cfg_ori.option('objspace').property.add('hidden')
await cfg_ori.option('objspace').property.add('hidden') cfg = get_config(cfg_ori, config_type)
cfg = await get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('objspace').value.get() cfg.option('objspace').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
assert 'hidden' in await cfg_ori.forcepermissive.option('objspace').property.get() assert 'hidden' in cfg_ori.forcepermissive.option('objspace').property.get()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
prop = [] prop = []
try: try:
await cfg.option('objspace').value.set(['std']) cfg.option('objspace').value.set(['std'])
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
@ -123,76 +119,72 @@ async def test_group_is_hidden_multi(config_type):
else: else:
assert 'hidden' in prop assert 'hidden' in prop
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('objspace').property.pop('hidden') cfg_ori.forcepermissive.option('objspace').property.remove('hidden')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert not 'hidden' in await cfg.option('objspace').property.get() assert not 'hidden' in cfg.option('objspace').property.get()
await cfg.option('objspace').value.set(['std', 'thunk']) cfg.option('objspace').value.set(['std', 'thunk'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_global_show(config_type):
async def test_global_show(config_type): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() cfg.forcepermissive.option('gc.dummy').property.add('hidden')
await cfg.forcepermissive.option('gc.dummy').property.add('hidden') assert 'hidden' in cfg.forcepermissive.option('gc.dummy').property.get()
assert 'hidden' in await cfg.forcepermissive.option('gc.dummy').property.get() cfg = get_config(cfg, config_type)
cfg = await get_config(cfg, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() == False cfg.option('gc.dummy').value.get() == False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_with_many_subgroups(config_type):
async def test_with_many_subgroups(config_type): od1 = make_description()
descr = make_description() cfg_ori = Config(od1)
async with await Config(descr) as cfg_ori:
#booltwo = config.unwrap_from_path('gc.subgroup.booltwo') #booltwo = config.unwrap_from_path('gc.subgroup.booltwo')
#setting = config.cfgimpl_get_settings() #setting = config.cfgimpl_get_settings()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert not 'hidden' in await cfg.option('gc.subgroup.booltwo').property.get() assert not 'hidden' in cfg.option('gc.subgroup.booltwo').property.get()
assert await cfg.option('gc.subgroup.booltwo').value.get() is False assert cfg.option('gc.subgroup.booltwo').value.get() is False
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.option('gc.subgroup.booltwo').property.add('hidden') cfg_ori.option('gc.subgroup.booltwo').property.add('hidden')
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_password_option(config_type):
async def test_password_option(config_type):
o = PasswordOption('o', '') o = PasswordOption('o', '')
d = OptionDescription('d', '', [o]) od1 = OptionDescription('d', '', [o])
async with await Config(d) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('o').value.set('a_valid_password') cfg.option('o').value.set('a_valid_password')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set(1) cfg.option('o').value.set(1)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_date_option(config_type):
async def test_date_option(config_type):
o = DateOption('o', '') o = DateOption('o', '')
d = OptionDescription('d', '', [o]) od1 = OptionDescription('d', '', [o])
async with await Config(d) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
await cfg.option('o').value.set('2017-02-04') cfg.option('o').value.set('2017-02-04')
await cfg.option('o').value.set('2017-2-4') cfg.option('o').value.set('2017-2-4')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set(1) cfg.option('o').value.set(1)
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-13-20') cfg.option('o').value.set('2017-13-20')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-11-31') cfg.option('o').value.set('2017-11-31')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-12-32') cfg.option('o').value.set('2017-12-32')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-2-29') cfg.option('o').value.set('2017-2-29')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2-2-2017') cfg.option('o').value.set('2-2-2017')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('o').value.set('2017/2/2') cfg.option('o').value.set('2017/2/2')
assert not await list_sessions() # assert not list_sessions()

File diff suppressed because it is too large Load diff

View file

@ -5,8 +5,7 @@ do_autopath()
import pytest import pytest
from tiramisu import BoolOption, OptionDescription, ChoiceOption,\ from tiramisu import BoolOption, OptionDescription, ChoiceOption,\
IntOption, FloatOption, StrOption, Config IntOption, FloatOption, StrOption, Config
from tiramisu.storage import list_sessions from .config import config_type, get_config
from .config import config_type, get_config, event_loop
def make_description(): def make_description():
@ -32,34 +31,26 @@ def make_description():
return descr return descr
@pytest.mark.asyncio def test_root_config_answers_ok(config_type):
async def test_root_config_answers_ok(config_type):
"if you hide the root config, the options in this namespace behave normally" "if you hide the root config, the options in this namespace behave normally"
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
boolop = BoolOption('boolop', 'Test boolean option op', default=True) boolop = BoolOption('boolop', 'Test boolean option op', default=True)
descr = OptionDescription('tiramisu', '', [gcdummy, boolop]) od1 = OptionDescription('tiramisu', '', [gcdummy, boolop])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
#settings = await cfg.cfgimpl_get_settings() #settings = cfg.cfgimpl_get_settings()
#settings.append('hidden') #settings.append('hidden')
assert await cfg.option('dummy').value.get() is False assert cfg.option('dummy').value.get() is False
assert await cfg.option('boolop').value.get() is True assert cfg.option('boolop').value.get() is True
assert not await list_sessions() # assert not list_sessions()
#@pytest.mark.asyncio def test_option_has_an_api_name(config_type):
# async def test_optname_shall_not_start_with_numbers():
# raises(ValueError, "gcdummy = BoolOption('123dummy', 'dummy', default=False)")
# raises(ValueError, "descr = OptionDescription('123tiramisu', '', [])")
#
#
@pytest.mark.asyncio
async def test_option_has_an_api_name(config_type):
b = BoolOption('impl_has_dependency', 'dummy', default=True) b = BoolOption('impl_has_dependency', 'dummy', default=True)
descr = OptionDescription('tiramisu', '', [b]) od1 = OptionDescription('tiramisu', '', [b])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('impl_has_dependency').value.get() is True assert cfg.option('impl_has_dependency').value.get() is True
assert b.impl_has_dependency() is False assert b.impl_has_dependency() is False
assert not await list_sessions() # assert not list_sessions()

View file

@ -6,8 +6,7 @@ do_autopath()
import pytest import pytest
from tiramisu import IntOption, StrOption, OptionDescription, Config from tiramisu import IntOption, StrOption, OptionDescription, Config
from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.storage import list_sessions, delete_session from .config import config_type, get_config
from .config import config_type, get_config, event_loop
def make_description(): def make_description():
@ -16,428 +15,414 @@ def make_description():
return OptionDescription('od1', '', [u1, u2]) return OptionDescription('od1', '', [u1, u2])
@pytest.mark.asyncio def test_forcepermissive_and_unrestraint(config_type):
async def test_permissive(config_type): od1 = make_description()
descr = make_description() cfg_ori = Config(od1)
async with await Config(descr) as cfg_ori: cfg_ori.property.read_write()
await cfg_ori.property.read_write() cfg_ori.property.read_write()
await cfg_ori.property.read_write() cfg = get_config(cfg_ori, config_type)
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.unrestraint.permissive.add('disabled')
await cfg_ori.unrestraint.permissive.pop('hidden')
assert await cfg_ori.unrestraint.permissive.get() == frozenset(['disabled'])
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.property.add('permissive')
cfg = await get_config(cfg_ori, config_type)
await cfg.option('u1').value.get()
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.property.pop('permissive')
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
assert not await list_sessions()
@pytest.mark.asyncio
async def test_permissive_add(config_type):
descr = make_description()
async with await Config(descr) as cfg_ori:
await cfg_ori.property.read_write()
await cfg_ori.property.read_write()
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.unrestraint.permissive.add('disabled')
assert await cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.property.add('permissive')
cfg = await get_config(cfg_ori, config_type)
await cfg.option('u1').value.get()
if config_type == 'tiramisu-api':
await cfg.send()
await cfg_ori.property.pop('permissive')
cfg = await get_config(cfg_ori, config_type)
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
assert not await list_sessions()
@pytest.mark.asyncio
async def test_permissive_pop():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_write()
await cfg.property.read_write()
props = frozenset()
try:
await cfg.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
await cfg.unrestraint.permissive.add('disabled')
assert await cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
await cfg.forcepermissive.option('u1').value.get()
await cfg.unrestraint.permissive.pop('disabled')
props = frozenset()
try:
await cfg.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
assert not await list_sessions()
@pytest.mark.asyncio
async def test_permissive_reset():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_write()
assert await cfg.unrestraint.permissive.get() == frozenset(['hidden'])
#
await cfg.unrestraint.permissive.add('disabled')
await cfg.unrestraint.permissive.pop('hidden')
assert await cfg.unrestraint.permissive.get() == frozenset(['disabled'])
#
await cfg.unrestraint.permissive.reset()
assert await cfg.unrestraint.permissive.get() == frozenset()
assert not await list_sessions()
@pytest.mark.asyncio
async def test_permissive_mandatory():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_only()
props = frozenset()
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
await cfg.unrestraint.permissive.add('mandatory')
await cfg.unrestraint.permissive.add('disabled')
assert await cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled'])
await cfg.property.add('permissive')
await cfg.option('u1').value.get()
await cfg.property.pop('permissive')
try:
await cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
assert not await list_sessions()
@pytest.mark.asyncio
async def test_permissive_frozen():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_write()
await cfg.unrestraint.permissive.pop('hidden')
await cfg.unrestraint.permissive.add('frozen')
await cfg.unrestraint.permissive.add('disabled')
assert await cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled'])
assert await cfg.permissive.get() == frozenset(['frozen', 'disabled'])
try:
await cfg.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
await cfg.property.add('permissive')
await cfg.option('u1').value.set(1)
assert await cfg.option('u1').value.get() == 1
await cfg.property.pop('permissive')
try:
await cfg.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
assert not await list_sessions()
@pytest.mark.asyncio
async def test_invalid_permissive():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_write()
# FIXME with pytest.raises(TypeError):
# await cfg.unrestraint.permissive.set(['frozen', 'disabled'])")
assert not await list_sessions()
@pytest.mark.asyncio
async def test_forbidden_permissive():
descr = make_description()
async with await Config(descr) as cfg:
await cfg.property.read_write()
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg.permissive.add('force_default_on_freeze') cfg_ori.unrestraint.forcepermissive.add('disabled')
def test_permissive(config_type):
od1 = make_description()
cfg_ori = Config(od1)
cfg_ori.property.read_write()
cfg_ori.property.read_write()
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.unrestraint.permissive.add('disabled')
cfg_ori.unrestraint.permissive.remove('hidden')
assert cfg_ori.unrestraint.permissive.get() == frozenset(['disabled'])
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.property.add('permissive')
cfg = get_config(cfg_ori, config_type)
cfg.option('u1').value.get()
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.property.remove('permissive')
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
# assert not list_sessions()
def test_permissive_add(config_type):
od1 = make_description()
cfg_ori = Config(od1)
cfg_ori.property.read_write()
cfg_ori.property.read_write()
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.unrestraint.permissive.add('disabled')
assert cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.property.add('permissive')
cfg = get_config(cfg_ori, config_type)
cfg.option('u1').value.get()
if config_type == 'tiramisu-api':
cfg.send()
cfg_ori.property.remove('permissive')
cfg = get_config(cfg_ori, config_type)
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
# assert not list_sessions()
def test_permissive_pop():
od1 = make_description()
cfg = Config(od1)
cfg.property.read_write()
cfg.property.read_write()
props = frozenset()
try:
cfg.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
cfg.forcepermissive.option('u1').value.get()
cfg.unrestraint.permissive.remove('disabled')
props = frozenset()
try:
cfg.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
# assert not list_sessions()
def test_permissive_reset():
od1 = make_description()
cfg = Config(od1)
cfg.property.read_write()
assert cfg.unrestraint.permissive.get() == frozenset(['hidden'])
#
cfg.unrestraint.permissive.add('disabled')
cfg.unrestraint.permissive.remove('hidden')
assert cfg.unrestraint.permissive.get() == frozenset(['disabled'])
#
cfg.unrestraint.permissive.reset()
assert cfg.unrestraint.permissive.get() == frozenset()
# assert not list_sessions()
def test_permissive_mandatory():
od1 = make_description()
cfg = Config(od1)
cfg.property.read_only()
props = frozenset()
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
cfg.unrestraint.permissive.add('mandatory')
cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled'])
cfg.property.add('permissive')
cfg.option('u1').value.get()
cfg.property.remove('permissive')
try:
cfg.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
# assert not list_sessions()
def test_permissive_frozen():
od1 = make_description()
cfg = Config(od1)
cfg.property.read_write()
cfg.unrestraint.permissive.remove('hidden')
cfg.unrestraint.permissive.add('frozen')
cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled'])
assert cfg.permissive.get() == frozenset(['frozen', 'disabled'])
try:
cfg.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
cfg.property.add('permissive')
cfg.option('u1').value.set(1)
assert cfg.option('u1').value.get() == 1
cfg.property.remove('permissive')
try:
cfg.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
# assert not list_sessions()
def test_forbidden_permissive():
od1 = make_description()
cfg = Config(od1)
cfg.property.read_write()
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg.permissive.add('force_metaconfig_on_freeze') cfg.permissive.add('force_default_on_freeze')
assert not await list_sessions() with pytest.raises(ConfigError):
cfg.permissive.add('force_metaconfig_on_freeze')
# assert not list_sessions()
@pytest.mark.asyncio def test_permissive_option(config_type):
async def test_permissive_option(config_type): od1 = make_description()
descr = make_description() cfg_ori = Config(od1)
async with await Config(descr) as cfg_ori: cfg_ori.property.read_write()
await cfg_ori.property.read_write() cfg = get_config(cfg_ori, config_type)
cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset() assert frozenset(props) == frozenset()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.property.add('permissive') cfg_ori.property.add('permissive')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
await cfg.option('u1').value.get() cfg.option('u1').value.get()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.property.pop('permissive') cfg_ori.property.remove('permissive')
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset() assert frozenset(props) == frozenset()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_permissive_option_cache():
async def test_permissive_option_cache(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
await cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset() assert frozenset(props) == frozenset()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
await cfg.property.add('permissive') cfg.property.add('permissive')
await cfg.option('u1').value.get() cfg.option('u1').value.get()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
await cfg.property.pop('permissive') cfg.property.remove('permissive')
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset() assert frozenset(props) == frozenset()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u2').value.get() cfg.option('u2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert set(props) == {'disabled'} assert set(props) == {'disabled'}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_permissive_option_mandatory():
async def test_permissive_option_mandatory(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_only()
await cfg.property.read_only()
props = frozenset() props = frozenset()
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset(['disabled']) assert frozenset(props) == frozenset(['disabled'])
await cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled'])) cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled']))
assert await cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled']) assert cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled'])
await cfg.property.add('permissive') cfg.property.add('permissive')
await cfg.option('u1').value.get() cfg.option('u1').value.get()
await cfg.property.pop('permissive') cfg.property.remove('permissive')
try: try:
await cfg.option('u1').value.get() cfg.option('u1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset(['disabled']) assert frozenset(props) == frozenset(['disabled'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_permissive_option_frozen():
async def test_permissive_option_frozen(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write() cfg.unrestraint.option('u1').permissive.set(frozenset(['frozen', 'disabled']))
await cfg.unrestraint.option('u1').permissive.set(frozenset(['frozen', 'disabled'])) cfg.option('u1').value.set(1)
await cfg.option('u1').value.set(1) assert cfg.option('u1').value.get() == 1
assert await cfg.option('u1').value.get() == 1 cfg.property.add('permissive')
await cfg.property.add('permissive') assert cfg.option('u1').value.get() == 1
assert await cfg.option('u1').value.get() == 1 cfg.property.remove('permissive')
await cfg.property.pop('permissive') assert cfg.option('u1').value.get() == 1
assert await cfg.option('u1').value.get() == 1 # assert not list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio def test_invalid_option_permissive():
async def test_invalid_option_permissive(): od1 = make_description()
descr = make_description() cfg = Config(od1)
async with await Config(descr) as cfg: cfg.property.read_write()
await cfg.property.read_write()
with pytest.raises(TypeError): with pytest.raises(TypeError):
await cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled']) cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_remove_option_permissive(config_type):
async def test_remove_option_permissive(config_type):
var1 = StrOption('var1', '', u'value', properties=('hidden',)) var1 = StrOption('var1', '', u'value', properties=('hidden',))
od1 = OptionDescription('od1', '', [var1]) od1 = OptionDescription('od1', '', [var1])
descr = OptionDescription('rootod', '', [od1]) od2 = OptionDescription('rootod', '', [od1])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od2)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get() cfg.option('od1.var1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('od1.var1').value.get() == 'value' assert cfg.option('od1.var1').value.get() == 'value'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset()) cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset())
assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get() cfg.option('od1.var1').value.get()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_reset_option_permissive(config_type):
async def test_reset_option_permissive(config_type):
var1 = StrOption('var1', '', u'value', properties=('hidden',)) var1 = StrOption('var1', '', u'value', properties=('hidden',))
od1 = OptionDescription('od1', '', [var1]) od1 = OptionDescription('od1', '', [var1])
descr = OptionDescription('rootod', '', [od1]) od2 = OptionDescription('rootod', '', [od1])
async with await Config(descr) as cfg_ori: cfg_ori = Config(od2)
await cfg_ori.property.read_write() cfg_ori.property.read_write()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get() cfg.option('od1.var1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
assert await cfg.option('od1.var1').value.get() == 'value' assert cfg.option('od1.var1').value.get() == 'value'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
await cfg.send() cfg.send()
await cfg_ori.forcepermissive.option('od1.var1').permissive.reset() cfg_ori.forcepermissive.option('od1.var1').permissive.reset()
assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset()
cfg = await get_config(cfg_ori, config_type) cfg = get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError): with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get() cfg.option('od1.var1').value.get()
assert not await list_sessions() # assert not list_sessions()

File diff suppressed because it is too large Load diff

View file

@ -11,13 +11,10 @@ try:
except: except:
tiramisu_version = 2 tiramisu_version = 2
from tiramisu import Config from tiramisu import Config
from tiramisu.config import SubConfig
from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption,\ from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption,\
StrOption, SymLinkOption, StrOption, IPOption, OptionDescription, \ StrOption, SymLinkOption, StrOption, IPOption, OptionDescription, \
PortOption, NetworkOption, NetmaskOption, DomainnameOption, EmailOption, \ PortOption, NetworkOption, NetmaskOption, DomainnameOption, EmailOption, \
URLOption, FilenameOption URLOption, FilenameOption
from tiramisu.storage import list_sessions, delete_session
from .config import event_loop
def test_slots_option(): def test_slots_option():
@ -86,8 +83,7 @@ def test_slots_option():
del c del c
@pytest.mark.asyncio def test_slots_option_readonly():
async def test_slots_option_readonly():
a = ChoiceOption('a', '', ('a',)) a = ChoiceOption('a', '', ('a',))
b = BoolOption('b', '') b = BoolOption('b', '')
c = IntOption('c', '') c = IntOption('c', '')
@ -118,8 +114,7 @@ async def test_slots_option_readonly():
o._name = 'o' o._name = 'o'
p._name = 'p' p._name = 'p'
q._name = 'q' q._name = 'q'
async with await Config(m) as cfg: Config(m)
pass
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
a._requires = 'a' a._requires = 'a'
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
@ -150,7 +145,7 @@ async def test_slots_option_readonly():
p._requires = 'p' p._requires = 'p'
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
q._requires = 'q' q._requires = 'q'
assert not await list_sessions() # assert not list_sessions()
#def test_slots_description(): #def test_slots_description():
@ -162,47 +157,23 @@ async def test_slots_option_readonly():
# assert slots == set(OptionDescription.__slots__) # assert slots == set(OptionDescription.__slots__)
@pytest.mark.asyncio def test_slots_setting():
async def test_slots_config():
od1 = OptionDescription('a', '', []) od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1]) od2 = OptionDescription('a', '', [od1])
async with await Config(od2) as c: cfg = Config(od2)
with pytest.raises(AttributeError): s = cfg._config_bag.context.get_settings()
c._config_bag.context.x = 1
with pytest.raises(AttributeError):
c._config_bag.context.cfgimpl_x = 1
option_bag = OptionBag()
option_bag.set_option(od2,
'a',
ConfigBag(c._config_bag.context, None, None))
sc = await c._config_bag.context.get_subconfig(option_bag)
assert isinstance(sc, SubConfig)
with pytest.raises(AttributeError):
sc.x = 1
with pytest.raises(AttributeError):
sc.cfgimpl_x = 1
assert not await list_sessions()
@pytest.mark.asyncio
async def test_slots_setting():
od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1])
async with await Config(od2) as c:
s = c._config_bag.context.cfgimpl_get_settings()
s s
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
s.x = 1 s.x = 1
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_slots_value():
async def test_slots_value():
od1 = OptionDescription('a', '', []) od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1]) od2 = OptionDescription('a', '', [od1])
async with await Config(od2) as c: cfg = Config(od2)
v = c._config_bag.context.cfgimpl_get_values() v = cfg._config_bag.context.get_values()
v v
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
v.x = 1 v.x = 1
assert not await list_sessions() # assert not list_sessions()

View file

@ -1,47 +0,0 @@
from .autopath import do_autopath
do_autopath()
from tiramisu import BoolOption, StrOption, SymLinkOption, OptionDescription, DynOptionDescription, \
Calculation, Params, ParamOption, ParamValue, calc_value, Config
from pickle import dumps
import pytest
import sys, warnings
from tiramisu.storage import list_sessions
from .config import event_loop
def test_diff_opt():
b = BoolOption('b', '')
disabled_property = Calculation(calc_value,
Params(ParamValue('disabled'),
kwargs={'condition': ParamOption(b),
'expected': ParamValue(True),
'reverse_condition': ParamValue(True)}))
u = StrOption('u', '', properties=(disabled_property,))
s = SymLinkOption('s', u)
o = OptionDescription('o', '', [b, u, s])
o1 = OptionDescription('o1', '', [o])
with pytest.raises(NotImplementedError):
dumps(o1)
@pytest.mark.asyncio
async def test_diff_information_config():
b = BoolOption('b', '')
b.impl_set_information('info', 'oh')
b.impl_set_information('info1', 'oh')
b.impl_set_information('info2', 'oh')
o = OptionDescription('o', '', [b])
o1 = OptionDescription('o1', '', [o])
async with await Config(o1) as cfg:
c = cfg._config_bag.context
with pytest.raises(NotImplementedError):
dumps(c)
assert not await list_sessions()
def test_only_optiondescription():
b = BoolOption('b', '')
b
with pytest.raises(NotImplementedError):
dumps(b)

View file

@ -1,333 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
import pytest
from tiramisu.error import ConfigError
from tiramisu import Config, BoolOption, OptionDescription, Leadership, \
list_sessions, delete_session, default_storage, MetaConfig
from tiramisu.setting import groups, owners
from .config import event_loop
@pytest.mark.asyncio
async def test_non_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
async with await Config(o, session_id='test_non_persistent', delete_old_session=True) as cfg:
pass
assert not await list_sessions()
@pytest.mark.asyncio
async def test_list():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
async with await Config(o, session_id='test_non_persistent') as cfg:
await cfg.option('b').value.set(True)
assert 'test_non_persistent' in await list_sessions()
assert 'test_non_persistent' not in await list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
await Config(o, session_id='test_persistent')
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_list_sessions_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.option('b').value.set(True)
assert 'test_persistent' in await list_sessions()
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_delete_session_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
await Config(o, session_id='test_persistent')
assert 'test_persistent' in await list_sessions()
await delete_session('test_persistent')
assert 'test_persistent' not in await list_sessions()
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_retrieve():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
assert await cfg.option('b').value.get() is None
await cfg.option('b').value.set(True)
assert await cfg.option('b').value.get() is True
del cfg
cfg = await Config(o, session_id='test_persistent')
assert await cfg.option('b').value.get() is True
assert 'test_persistent' in await list_sessions()
await delete_session(await cfg.session.id())
del cfg
cfg = await Config(o, session_id='test_persistent')
assert await cfg.option('b').value.get() is None
await delete_session(await cfg.session.id())
del cfg
assert not await list_sessions()
@pytest.mark.asyncio
async def test_two_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
cfg2 = await Config(o, session_id='test_persistent')
await cfg2.property.pop('cache')
assert await cfg.option('b').value.get() is None
assert await cfg2.option('b').value.get() is None
#
await cfg.option('b').value.set(False)
assert await cfg.option('b').value.get() is False
assert await cfg2.option('b').value.get() is False
#
await cfg.option('b').value.set(True)
assert await cfg.option('b').value.get() is True
assert await cfg2.option('b').value.get() is True
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_retrieve_owner():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
assert await cfg.option('b').owner.isdefault()
await cfg.option('b').value.set(True)
assert await cfg.option('b').value.get()
assert await cfg.option('b').owner.get() == 'user'
##owners.addowner('persistentowner')
await cfg.option('b').owner.set('persistentowner')
assert await cfg.option('b').owner.get() == 'persistentowner'
del cfg
#
cfg = await Config(o, session_id='test_persistent')
await cfg.option('b').owner.set('persistentowner')
await delete_session(await cfg.session.id())
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert await cfg.option('b').value.get() is None
assert await cfg.option('b').owner.isdefault()
await delete_session(await cfg.session.id())
del cfg
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_retrieve_owner_leadership():
a = BoolOption('a', '', multi=True)
b = BoolOption('b', '', multi=True)
o = Leadership('a', '', [a, b])
o1 = OptionDescription('a', '', [o])
cfg = await Config(o1, session_id='test_persistent')
assert await cfg.option('a.a').owner.isdefault()
await cfg.option('a.a').value.set([True, False])
await cfg.option('a.b', 1).value.set(True)
assert await cfg.option('a.a').owner.get() == 'user'
assert await cfg.option('a.b', 0).owner.isdefault()
assert await cfg.option('a.b', 1).owner.get() == 'user'
#owners.addowner('persistentowner2')
await cfg.option('a.b', 1).owner.set('persistentowner2')
await cfg.option('a.b', 0).value.set(True)
assert await cfg.option('a.b', 0).owner.get() == 'user'
assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2'
assert await cfg.option('a.a').value.get() == [True, False]
del cfg
#
cfg = await Config(o1, session_id='test_persistent')
assert await cfg.option('a.a').value.get() == [True, False]
assert await cfg.option('a.b', 0).owner.get() == 'user'
assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2'
await delete_session(await cfg.session.id())
del cfg
#
cfg = await Config(o1, session_id='test_persistent')
assert await cfg.option('a.a').value.get() == []
await delete_session(await cfg.session.id())
del cfg
assert not await list_sessions()
@pytest.mark.asyncio
async def test_two_persistent_owner():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.property.pop('cache')
cfg2 = await Config(o, session_id='test_persistent')
await cfg2.property.pop('cache')
assert await cfg.option('b').owner.isdefault()
assert await cfg2.option('b').owner.isdefault()
await cfg.option('b').value.set(False)
assert await cfg.option('b').owner.get() == 'user'
assert await cfg2.option('b').owner.get() == 'user'
await cfg.option('b').owner.set('persistent')
assert await cfg.option('b').owner.get() == 'persistent'
assert await cfg2.option('b').owner.get() == 'persistent'
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_retrieve_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.information.set('info', 'string')
assert await cfg.information.get('info') == 'string'
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert await cfg.information.get('info') == 'string'
await delete_session(await cfg.session.id())
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert await cfg.information.get('info', None) is None
await delete_session(await cfg.session.id())
del cfg
assert not await list_sessions()
@pytest.mark.asyncio
async def test_two_persistent_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.property.pop('cache')
await cfg.information.set('info', 'string')
assert await cfg.information.get('info') == 'string'
cfg2 = await Config(o, session_id='test_persistent')
await cfg2.property.pop('cache')
assert await cfg2.information.get('info') == 'string'
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_two_different_persistents():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.property.pop('cache')
cfg2 = await Config(o, session_id='test_persistent2')
await cfg2.property.pop('cache')
await cfg.option('b').property.add('test')
assert await cfg.option('b').property.get() == {'test'}
assert await cfg2.option('b').property.get() == set()
assert await cfg.option('b').value.get() is None
assert await cfg2.option('b').value.get() is None
await cfg.option('b').value.set(True)
assert await cfg.option('b').value.get() == True
assert await cfg2.option('b').value.get() is None
await delete_session('test_persistent')
await delete_session('test_persistent2')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_two_different_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.information.set('a', 'a')
cfg2 = await Config(o, session_id='test_persistent2')
await cfg2.information.set('a', 'b')
assert await cfg.information.get('a') == 'a'
assert await cfg2.information.get('a') == 'b'
await delete_session('test_persistent')
await delete_session('test_persistent2')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_exportation_importation():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
cfg2 = await Config(o, session_id='test_persistent2')
cfg3 = await Config(o, session_id='test_persistent3')
await cfg.owner.set('export')
assert await cfg.option('b').value.get() is None
await cfg.option('b').value.set(True)
assert await cfg.option('b').value.get() is True
assert await cfg.owner.get() == 'export'
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert await cfg.owner.get() == 'export'
assert await cfg.value.exportation() == [['b'], [None], [True], ['export']]
await cfg2.value.importation(await cfg.value.exportation())
assert await cfg.value.exportation() == [['b'], [None], [True], ['export']]
assert await cfg.owner.get() == 'export'
assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']]
assert await cfg2.owner.get() == 'user'
del cfg2
#
cfg2 = await Config(o, session_id='test_persistent2')
assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']]
assert await cfg2.owner.get() == 'user'
#
await cfg3.value.importation(await cfg.value.exportation(with_default_owner=True))
assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']]
assert await cfg3.owner.get() == 'export'
del cfg3
#
cfg3 = await Config(o, session_id='test_persistent3')
assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']]
assert await cfg3.owner.get() == 'export'
#
await delete_session('test_persistent')
await delete_session('test_persistent2')
await delete_session('test_persistent3')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_context_property():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.property.add('persistent')
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert 'persistent' in await cfg.property.get()
del cfg
await delete_session('test_persistent')
assert not await list_sessions()
@pytest.mark.asyncio
async def test_create_persistent_property():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
cfg = await Config(o, session_id='test_persistent')
await cfg.option('b').property.add('persistent')
del cfg
#
cfg = await Config(o, session_id='test_persistent')
assert 'persistent' in await cfg.option('b').property.get()
del cfg
await delete_session('test_persistent')

View file

@ -7,10 +7,8 @@ import warnings
from tiramisu.setting import groups, owners from tiramisu.setting import groups, owners
from tiramisu import StrOption, IntOption, OptionDescription, submulti, Leadership, Config, \ from tiramisu import StrOption, IntOption, OptionDescription, submulti, Leadership, Config, \
MetaConfig, undefined, Params, ParamOption, Calculation MetaConfig, Params, ParamOption, Calculation
from tiramisu.error import LeadershipError from tiramisu.error import LeadershipError, PropertiesOptionError
from tiramisu.storage import list_sessions
from .config import event_loop
def return_val(val=None): def return_val(val=None):
@ -28,481 +26,545 @@ def return_list2(value=None):
return [['val', 'val']] return [['val', 'val']]
@pytest.mark.asyncio def test_unknown_multi():
async def test_unknown_multi():
with pytest.raises(ValueError): with pytest.raises(ValueError):
StrOption('multi', '', multi='unknown') StrOption('multi', '', multi='unknown')
@pytest.mark.asyncio def test_submulti():
async def test_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti) multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od1 = OptionDescription('od', '', [multi, multi2, multi3])
async with await Config(od) as cfg: cfg = Config(od1)
assert await cfg.option('multi').option.ismulti() assert cfg.option('multi').ismulti()
assert await cfg.option('multi').option.issubmulti() assert cfg.option('multi').issubmulti()
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi3').value.get() == [['yes']] assert cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_submulti_mandatory():
async def test_submulti_default_multi_not_list(): multi = StrOption('multi', '', multi=submulti, properties=('mandatory',))
od1 = OptionDescription('od', '', [multi])
cfg = Config(od1)
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
#
cfg.property.read_write()
cfg.option('multi').value.set([['val']])
cfg.property.read_only()
assert cfg.option('multi').value.get() == [['val']]
#
cfg.property.read_write()
cfg.option('multi').value.set([['val'], ['']])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
#
cfg.property.read_write()
cfg.option('multi').value.set([['val'], [None]])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
#
cfg.property.read_write()
cfg.option('multi').value.set([['val'], []])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
#
cfg.property.read_write()
cfg.option('multi').value.set([['val'], ['val1', '']])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
#
cfg.property.read_write()
cfg.option('multi').value.set([['val'], ['val1', '', 'val2']])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('multi').value.get()
# assert not list_sessions()
def test_submulti_default_multi_not_list():
with pytest.raises(ValueError): with pytest.raises(ValueError):
StrOption('multi2', '', default_multi='yes', multi=submulti) StrOption('multi2', '', default_multi='yes', multi=submulti)
@pytest.mark.asyncio def test_append_submulti():
async def test_append_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti) multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od1 = OptionDescription('od', '', [multi, multi2, multi3])
async with await Config(od) as cfg: cfg = Config(od1)
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
await cfg.option('multi').value.set([undefined]) cfg.option('multi').value.set([[]])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi').value.get() == [[]] assert cfg.option('multi').value.get() == [[]]
await cfg.option('multi').value.set([undefined, ['no']]) cfg.option('multi').value.set([[], ['no']])
assert await cfg.option('multi').value.get() == [[], ['no']] assert cfg.option('multi').value.get() == [[], ['no']]
# #
assert await cfg.option('multi2').value.get() == [] assert cfg.option('multi2').value.get() == []
assert await cfg.option('multi2').owner.get() == owners.default assert cfg.option('multi2').owner.get() == owners.default
await cfg.option('multi2').value.set([undefined]) cfg.option('multi2').value.set([cfg.option('multi2').defaultmulti()])
assert await cfg.option('multi2').owner.get() == owner assert cfg.option('multi2').owner.get() == owner
assert await cfg.option('multi2').value.get() == [['yes']] assert cfg.option('multi2').value.get() == [['yes']]
await cfg.option('multi2').value.set([undefined, ['no']]) cfg.option('multi2').value.set([cfg.option('multi2').defaultmulti(), ['no']])
assert await cfg.option('multi2').value.get() == [['yes'], ['no']] assert cfg.option('multi2').value.get() == [['yes'], ['no']]
# #
assert await cfg.option('multi3').value.get() == [['yes']] assert cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
await cfg.option('multi3').value.set([undefined, undefined]) cfg.option('multi3').value.set([cfg.option('multi2').defaultmulti(), []])
assert await cfg.option('multi3').owner.get() == owner assert cfg.option('multi3').owner.get() == owner
assert await cfg.option('multi3').value.get() == [['yes'], []] assert cfg.option('multi3').value.get() == [['yes'], []]
await cfg.option('multi3').value.set([undefined, undefined, ['no']]) cfg.option('multi3').value.set([cfg.option('multi2').defaultmulti(), [], ['no']])
assert await cfg.option('multi3').value.get() == [['yes'], [], ['no']] assert cfg.option('multi3').value.get() == [['yes'], [], ['no']]
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_append_unvalide_submulti():
async def test_append_unvalide_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti) multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od1 = OptionDescription('od', '', [multi, multi2, multi3])
async with await Config(od) as cfg: cfg = Config(od1)
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('multi').value.set([[1]]) cfg.option('multi').value.set([[1]])
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
# #
assert await cfg.option('multi2').value.get() == [] assert cfg.option('multi2').value.get() == []
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('multi2').value.set(['no']) cfg.option('multi2').value.set(['no'])
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi2').value.get() == [] assert cfg.option('multi2').value.get() == []
# #
assert await cfg.option('multi3').value.get() == [['yes']] assert cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('multi3').value.set([[1]]) cfg.option('multi3').value.set([[1]])
assert await cfg.option('multi3').value.get() == [['yes']] assert cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_pop_submulti():
async def test_pop_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti) multi2 = StrOption('multi2', '', default_multi=['yes'], multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od1 = OptionDescription('od', '', [multi, multi2, multi3])
async with await Config(od) as cfg: cfg = Config(od1)
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
await cfg.option('multi').value.set([['no', 'yes'], ['peharps']]) cfg.option('multi').value.set([['no', 'yes'], ['peharps']])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi').value.get() == [['no', 'yes'], ['peharps']] assert cfg.option('multi').value.get() == [['no', 'yes'], ['peharps']]
# #
assert await cfg.option('multi3').value.get() == [['yes']] assert cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
await cfg.option('multi3').value.set([]) cfg.option('multi3').value.set([])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi3').value.get() == [] assert cfg.option('multi3').value.get() == []
await cfg.option('multi3').value.reset() cfg.option('multi3').value.reset()
assert await cfg.option('multi3').owner.get() == owners.default assert cfg.option('multi3').owner.get() == owners.default
await cfg.option('multi3').value.set([[]]) cfg.option('multi3').value.set([[]])
assert await cfg.option('multi3').owner.get() == owner assert cfg.option('multi3').owner.get() == owner
assert await cfg.option('multi3').value.get() == [[]] assert cfg.option('multi3').value.get() == [[]]
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_submulti_str():
async def test_callback_submulti_str():
multi = StrOption('multi', '', [[Calculation(return_val)]], multi=submulti, default_multi=[Calculation(return_val)]) multi = StrOption('multi', '', [[Calculation(return_val)]], multi=submulti, default_multi=[Calculation(return_val)])
od = OptionDescription('od', '', [multi]) od1 = OptionDescription('od', '', [multi])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi').value.get() == [['val']] assert cfg.option('multi').value.get() == [['val']]
await cfg.option('multi').value.set([['val'], undefined]) cfg.option('multi').value.set([['val'], cfg.option('multi').defaultmulti()])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi').value.get() == [['val'], ['val']] assert cfg.option('multi').value.get() == [['val'], ['val']]
await cfg.option('multi').value.reset() cfg.option('multi').value.reset()
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_submulti_list():
async def test_callback_submulti_list():
multi = StrOption('multi', '', [Calculation(return_list)], multi=submulti, default_multi=Calculation(return_list), properties=('notunique',)) multi = StrOption('multi', '', [Calculation(return_list)], multi=submulti, default_multi=Calculation(return_list), properties=('notunique',))
od = OptionDescription('od', '', [multi]) od1 = OptionDescription('od', '', [multi])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').value.get() == [['val', 'val']] assert cfg.option('multi').value.get() == [['val', 'val']]
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
await cfg.option('multi').value.set([['val', 'val'], undefined]) cfg.option('multi').value.set([['val', 'val'], cfg.option('multi').defaultmulti()])
#assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
#assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val']] assert cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val']]
#await cfg.option('multi').value.set([['val', 'val'], undefined, undefined]) cfg.option('multi').value.set([['val', 'val'], cfg.option('multi').defaultmulti(), cfg.option('multi').defaultmulti()])
#assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']] assert cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']]
#await cfg.option('multi').value.reset() cfg.option('multi').value.reset()
#assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_submulti_list_list():
async def test_callback_submulti_list_list():
multi = StrOption('multi', '', Calculation(return_list2), multi=submulti, properties=('notunique',)) multi = StrOption('multi', '', Calculation(return_list2), multi=submulti, properties=('notunique',))
od = OptionDescription('od', '', [multi]) od1 = OptionDescription('od', '', [multi])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').value.get() == [['val', 'val']] assert cfg.option('multi').value.get() == [['val', 'val']]
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
await cfg.option('multi').value.set([['val', 'val'], undefined]) cfg.option('multi').value.set([['val', 'val'], cfg.option('multi').defaultmulti()])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi').value.get() == [['val', 'val'], []] assert cfg.option('multi').value.get() == [['val', 'val'], []]
await cfg.option('multi').value.reset() cfg.option('multi').value.reset()
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_groups_with_leader_submulti():
async def test_groups_with_leader_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
@pytest.mark.asyncio def test_groups_with_leader_in_config_submulti():
async def test_groups_with_leader_in_config_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1]) od1 = OptionDescription('root', '', [interface1])
async with await Config(od) as cfg: cfg = Config(od1)
pass
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_and_followers_submulti():
async def test_values_with_leader_and_followers_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']]) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_and_followers_submulti_mandatory():
async def test_values_with_leader_and_followers_submulti_default_multi(): 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=submulti, properties=('mandatory',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od1 = OptionDescription('toto', '', [interface1])
cfg = Config(od1)
cfg.property.read_only()
owner = cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
with pytest.raises(PropertiesOptionError):
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
#
cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(["255.255.255.0"])
cfg.property.read_only()
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ["255.255.255.0"]
#
cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(["255.255.255.0", None])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
#
cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(["255.255.255.0", ''])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
#
cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(["255.255.255.0", '', "255.255.255.0"])
cfg.property.read_only()
with pytest.raises(PropertiesOptionError):
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
# assert not list_sessions()
def test_values_with_leader_and_followers_submulti_default_multi():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti, default_multi=['255.255.0.0', '0.0.0.0']) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti, default_multi=['255.255.0.0', '0.0.0.0'])
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.0.0', '0.0.0.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.0.0', '0.0.0.0']
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.0.0', '0.0.0.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.0.0', '0.0.0.0']
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_reset_values_with_leader_and_followers_submulti():
async def test_reset_values_with_leader_and_followers_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
# #
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_and_followers_follower_submulti():
async def test_values_with_leader_and_followers_follower_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',)) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',))
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(LeadershipError): with pytest.raises(LeadershipError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0', '255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0', '255.255.255.0'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_and_leadership_submulti():
async def test_values_with_leader_and_leadership_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',)) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',))
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0'])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0']
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_owner_submulti():
async def test_values_with_leader_owner_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_values_with_leader_disabled_submulti():
async def test_values_with_leader_disabled_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',)) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('notunique',))
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
await cfg.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') cfg.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
#delete with value in disabled var #delete with value in disabled var
await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.remove('disabled')
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145'])
await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_leader_is_submulti():
async def test_leader_is_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=submulti) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=submulti)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1]) od1 = OptionDescription('toto', '', [interface1])
async with await Config(maconfig) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"]]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"]])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]]
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]])
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]])
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]] assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_submulti():
async def test_callback_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', Calculation(return_val, Params(ParamOption(multi))), multi=submulti) multi2 = StrOption('multi2', '', Calculation(return_val, Params(ParamOption(multi))), multi=submulti)
od = OptionDescription('multi', '', [multi, multi2]) od1 = OptionDescription('multi', '', [multi, multi2])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
owner = await cfg.owner.get() owner = cfg.owner.get()
assert await cfg.option('multi').owner.get() == owners.default assert cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi').value.get() == [] assert cfg.option('multi').value.get() == []
assert await cfg.option('multi2').value.get() == [] assert cfg.option('multi2').value.get() == []
await cfg.option('multi').value.set([['val']]) cfg.option('multi').value.set([['val']])
assert await cfg.option('multi').owner.get() == owner assert cfg.option('multi').owner.get() == owner
assert await cfg.option('multi2').owner.get() == owners.default assert cfg.option('multi2').owner.get() == owners.default
assert await cfg.option('multi').value.get() == [['val']] assert cfg.option('multi').value.get() == [['val']]
assert await cfg.option('multi2').value.get() == [['val']] assert cfg.option('multi2').value.get() == [['val']]
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_callback_submulti_follower():
async def test_callback_submulti_follower():
multi = StrOption('multi', '', multi=True) multi = StrOption('multi', '', multi=True)
multi2 = StrOption('multi2', '', Calculation(return_list), multi=submulti) multi2 = StrOption('multi2', '', Calculation(return_list), multi=submulti)
od = Leadership('multi', '', [multi, multi2]) od = Leadership('multi', '', [multi, multi2])
od = OptionDescription('multi', '', [od]) od1 = OptionDescription('multi', '', [od])
async with await Config(od) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
assert await cfg.option('multi.multi').value.get() == [] assert cfg.option('multi.multi').value.get() == []
await cfg.option('multi.multi').value.set(['val']) cfg.option('multi.multi').value.set(['val'])
assert await cfg.option('multi.multi2', 0).value.get() == ['val', 'val'] assert cfg.option('multi.multi2', 0).value.get() == ['val', 'val']
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_submulti_unique():
async def test_submulti_unique():
i = IntOption('int', '', multi=submulti, properties=('unique',)) i = IntOption('int', '', multi=submulti, properties=('unique',))
o = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
async with await Config(o) as cfg: cfg = Config(od1)
assert await cfg.option('int').value.get() == [] assert cfg.option('int').value.get() == []
await cfg.option('int').value.set([[0]]) cfg.option('int').value.set([[0]])
assert await cfg.option('int').value.get() == [[0]] assert cfg.option('int').value.get() == [[0]]
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('int').value.set([[0, 0]]) cfg.option('int').value.set([[0, 0]])
await cfg.option('int').value.set([[0], [0]]) cfg.option('int').value.set([[0], [0]])
with pytest.raises(ValueError): with pytest.raises(ValueError):
await cfg.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]]) cfg.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]])
await cfg.option('int').value.set([[0, 4, 5, 6], [0]]) cfg.option('int').value.set([[0, 4, 5, 6], [0]])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_multi_submulti_meta():
async def test_multi_submulti_meta():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
od = OptionDescription('od', '', [multi]) od1 = OptionDescription('od', '', [multi])
async with await Config(od, session_id='cfg') as cfg: cfg = Config(od1, name='cfg')
await cfg.property.read_write() cfg.property.read_write()
async with await Config(od, session_id='cfg2') as cfg2: cfg2 = Config(od1)
await cfg2.property.read_write() cfg2.property.read_write()
async with await MetaConfig([cfg, cfg2]) as meta: meta = MetaConfig([cfg, cfg2])
await meta.property.read_write() meta.property.read_write()
await meta.option('multi').value.set([['val']]) meta.option('multi').value.set([['val']])
assert await meta.option('multi').value.get() == [['val']] assert meta.option('multi').value.get() == [['val']]
newcfg = await meta.config('cfg') newcfg = meta.config('cfg')
await newcfg.option('multi').value.set([['val', None]]) newcfg.option('multi').value.set([['val', None]])
assert await cfg.option('multi').value.get() == [['val', None]] assert cfg.option('multi').value.get() == [['val', None]]
newcfg = await meta.config('cfg') newcfg = meta.config('cfg')
assert await newcfg.option('multi').value.get() == [['val', None]] assert newcfg.option('multi').value.get() == [['val', None]]
assert await meta.option('multi').value.get() == [['val']] assert meta.option('multi').value.get() == [['val']]
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_multi_submulti_meta_no_cache():
async def test_multi_submulti_meta_no_cache():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
od = OptionDescription('od', '', [multi]) od1 = OptionDescription('od', '', [multi])
async with await Config(od, session_id='cfg') as cfg: cfg = Config(od1, name='cfg')
await cfg.property.read_write() cfg.property.read_write()
async with await Config(od, session_id='cfg2') as cfg2: cfg2 = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
async with await MetaConfig([cfg, cfg2]) as meta: meta = MetaConfig([cfg, cfg2])
await meta.property.read_write() meta.property.read_write()
await meta.property.pop('cache') meta.property.remove('cache')
await meta.option('multi').value.set([['val']]) meta.option('multi').value.set([['val']])
assert await meta.option('multi').value.get() == [['val']] assert meta.option('multi').value.get() == [['val']]
newcfg = await meta.config('cfg') newcfg = meta.config('cfg')
await newcfg.option('multi').value.set([['val', None]]) newcfg.option('multi').value.set([['val', None]])
assert await cfg.option('multi').value.get() == [['val', None]] assert cfg.option('multi').value.get() == [['val', None]]
newcfg = await meta.config('cfg') newcfg = meta.config('cfg')
assert await newcfg.option('multi').value.get() == [['val', None]] assert newcfg.option('multi').value.get() == [['val', None]]
assert await meta.option('multi').value.get() == [['val']] assert meta.option('multi').value.get() == [['val']]
assert not await list_sessions() # assert not list_sessions()

View file

@ -4,12 +4,11 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from tiramisu import BoolOption, StrOption, SymLinkOption, \ from tiramisu import BoolOption, StrOption, SymLinkOption, submulti, \
OptionDescription, Leadership, Config, Calculation, calc_value, Params, ParamOption, ParamValue OptionDescription, Leadership, Config, Calculation, calc_value, Params, ParamOption, ParamValue
from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.setting import groups, owners from tiramisu.setting import groups, owners
from tiramisu.storage import list_sessions from tiramisu.i18n import _
from .config import event_loop
def return_value(): def return_value():
@ -17,129 +16,173 @@ def return_value():
#____________________________________________________________ #____________________________________________________________
@pytest.mark.asyncio def test_symlink_option(config_type):
async def test_symlink_option(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])],
async with await Config(descr) as cfg: )
cfg = await get_config(cfg, config_type) cfg = Config(od1)
assert await cfg.option('s1.b').value.get() is False cfg = get_config(cfg, config_type)
await cfg.option("s1.b").value.set(True) assert not cfg.option('s1.b').issymlinkoption()
await cfg.option("s1.b").value.set(False) assert cfg.option('c').issymlinkoption()
assert await cfg.option('s1.b').value.get() is False assert cfg.option('s1.b').type() == _('boolean')
assert await cfg.option('c').value.get() is False assert cfg.option('c').type() == _('boolean')
await cfg.option('s1.b').value.set(True) assert cfg.option('s1.b').value.get() is False
assert await cfg.option('s1.b').value.get() is True cfg.option("s1.b").value.set(True)
assert await cfg.option('c').value.get() is True cfg.option("s1.b").value.set(False)
await cfg.option('s1.b').value.set(False) assert cfg.option('s1.b').value.get() is False
assert await cfg.option('s1.b').value.get() is False assert cfg.option('c').value.get() is False
assert await cfg.option('c').value.get() is False cfg.option('s1.b').value.set(True)
assert not await list_sessions() assert cfg.option('s1.b').value.get() is True
assert cfg.option('c').value.get() is True
cfg.option('s1.b').value.set(False)
assert cfg.option('s1.b').value.get() is False
assert cfg.option('c').value.get() is False
# assert not list_sessions()
@pytest.mark.asyncio def test_symlink_default(config_type):
async def test_symlink_assign_option(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])],
async with await Config(descr) as cfg: )
cfg = await get_config(cfg, config_type) cfg = Config(od1)
cfg = get_config(cfg, config_type)
assert not cfg.option('s1.b').ismulti()
assert not cfg.option('c').ismulti()
assert not cfg.option('s1.b').issubmulti()
assert not cfg.option('c').issubmulti()
assert not cfg.option('s1.b').default()
assert not cfg.option('c').default()
assert not cfg.option('s1.b').value.default()
assert not cfg.option('c').value.default()
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg.option('c').value.set(True) assert not cfg.option('s1.b').defaultmulti()
assert not await list_sessions() with pytest.raises(ConfigError):
assert not cfg.option('c').defaultmulti()
cfg.option("s1.b").value.set(True)
assert not cfg.option('s1.b').default()
assert not cfg.option('c').default()
assert not cfg.option('s1.b').value.default()
assert not cfg.option('c').value.default()
## assert not list_sessions()
@pytest.mark.asyncio def test_symlink_default_multi(config_type):
async def test_symlink_del_option(config_type): boolopt = BoolOption("b", "", default=[False], default_multi=True, multi=True)
linkopt = SymLinkOption("c", boolopt)
od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])],
)
cfg = Config(od1)
cfg = get_config(cfg, config_type)
assert cfg.option('s1.b').ismulti()
assert cfg.option('c').ismulti()
assert not cfg.option('s1.b').issubmulti()
assert not cfg.option('c').issubmulti()
assert cfg.option('s1.b').default() == [False]
assert cfg.option('c').default() == [False]
assert cfg.option('s1.b').value.default() == [False]
assert cfg.option('c').value.default() == [False]
assert cfg.option('s1.b').defaultmulti()
assert cfg.option('c').defaultmulti()
cfg.option("s1.b").value.set([True])
assert cfg.option('s1.b').default() == [False]
assert cfg.option('c').default() == [False]
assert cfg.option('s1.b').value.default() == [False]
assert cfg.option('c').value.default() == [False]
assert cfg.option('s1.b').defaultmulti()
assert cfg.option('c').defaultmulti()
## assert not list_sessions()
def test_symlink_assign_option(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg.option('c').value.reset() cfg.option('c').value.set(True)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_del_option(config_type):
async def test_symlink_addproperties(): boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(od1)
cfg = get_config(cfg, config_type)
with pytest.raises(ConfigError):
cfg.option('c').value.reset()
# assert not list_sessions()
def test_symlink_addproperties():
boolopt = BoolOption('b', '', default=True, properties=('test',)) boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(TypeError): with pytest.raises(ConfigError):
await cfg.option('c').property.add('new') cfg.option('c').property.add('new')
try: with pytest.raises(ConfigError):
await cfg.option('c').property.reset() cfg.option('c').property.reset()
except AssertionError: # assert not list_sessions()
pass
else:
raise Exception('must raise')
assert not await list_sessions()
@pytest.mark.asyncio def test_symlink_getpermissive():
async def test_symlink_getpermissive():
boolopt = BoolOption('b', '', default=True, properties=('test',)) boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
await cfg.option('b').permissive.set(frozenset(['perm'])) cfg.option('b').permissive.set(frozenset(['perm']))
await cfg.option('c').permissive.get() == frozenset(['perm']) cfg.option('c').permissive.get() == frozenset(['perm'])
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_addpermissives():
async def test_symlink_addpermissives():
boolopt = BoolOption('b', '', default=True, properties=('test',)) boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
with pytest.raises(TypeError): with pytest.raises(ConfigError):
await cfg.option('c').permissive.set(frozenset(['new'])) cfg.option('c').permissive.set(frozenset(['new']))
try: with pytest.raises(ConfigError):
await cfg.option('c').permissive.reset() cfg.option('c').permissive.reset()
except AssertionError: # assert not list_sessions()
pass
else:
raise Exception('must raise')
assert not await list_sessions()
@pytest.mark.asyncio def test_symlink_getproperties():
async def test_symlink_getproperties():
boolopt = BoolOption('b', '', default=True, properties=('test',)) boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == {'test'} assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == {'test'}
assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False # assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_getcallback():
async def test_symlink_getcallback():
boolopt = BoolOption('b', '', Calculation(return_value)) boolopt = BoolOption('b', '', Calculation(return_value))
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
#assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == True #assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == True
#assert boolopt.impl_get_callback() == linkopt.impl_get_callback() == (return_value, None) #assert boolopt.impl_get_callback() == linkopt.impl_get_callback() == (return_value, None)
assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False # assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_requires(config_type):
async def test_symlink_requires(config_type):
boolopt = BoolOption('b', '', default=True) boolopt = BoolOption('b', '', default=True)
disabled_property = Calculation(calc_value, disabled_property = Calculation(calc_value,
Params(ParamValue('disabled'), Params(ParamValue('disabled'),
@ -147,86 +190,82 @@ async def test_symlink_requires(config_type):
'expected': ParamValue(False)})) 'expected': ParamValue(False)}))
stropt = StrOption('s', '', properties=(disabled_property,)) stropt = StrOption('s', '', properties=(disabled_property,))
linkopt = SymLinkOption("c", stropt) linkopt = SymLinkOption("c", stropt)
descr = OptionDescription('opt', '', [boolopt, stropt, linkopt]) od1 = OptionDescription('opt', '', [boolopt, stropt, linkopt])
async with await Config(descr) as cfg: cfg = Config(od1)
await cfg.property.read_write() cfg.property.read_write()
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('b').value.get() is True assert cfg.option('b').value.get() is True
assert await cfg.option('s').value.get() is None assert cfg.option('s').value.get() is None
assert await cfg.option('c').value.get() is None assert cfg.option('c').value.get() is None
await cfg.option('b').value.set(False) cfg.option('b').value.set(False)
# #
props = [] props = []
try: try:
await cfg.option('s').value.get() cfg.option('s').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert props == {'disabled'} assert props == {'disabled'}
# #
props = [] props = []
try: try:
await cfg.option('c').value.get() cfg.option('c').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert props == {'disabled'} assert props == {'disabled'}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_multi(config_type):
async def test_symlink_multi(config_type):
boolopt = BoolOption("b", "", default=[False], multi=True) boolopt = BoolOption("b", "", default=[False], multi=True)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('s1.b').value.get() == [False] assert cfg.option('s1.b').value.get() == [False]
assert await cfg.option('c').value.get() == [False] assert cfg.option('c').value.get() == [False]
await cfg.option('s1.b').value.set([True]) cfg.option('s1.b').value.set([True])
assert await cfg.option('s1.b').value.get() == [True] assert cfg.option('s1.b').value.get() == [True]
assert await cfg.option('c').value.get() == [True] assert cfg.option('c').value.get() == [True]
await cfg.option('s1.b').value.set([False]) cfg.option('s1.b').value.set([False])
assert await cfg.option('s1.b').value.get() == [False] assert cfg.option('s1.b').value.get() == [False]
assert await cfg.option('c').value.get() == [False] assert cfg.option('c').value.get() == [False]
await cfg.option('s1.b').value.set([False, True]) cfg.option('s1.b').value.set([False, True])
assert await cfg.option('s1.b').value.get() == [False, True] assert cfg.option('s1.b').value.get() == [False, True]
assert await cfg.option('c').value.get() == [False, True] assert cfg.option('c').value.get() == [False, True]
assert boolopt.impl_is_multi() is True assert boolopt.impl_is_multi() is True
assert linkopt.impl_is_multi() is True assert linkopt.impl_is_multi() is True
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_assign(config_type):
async def test_symlink_assign(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
with pytest.raises(ConfigError): with pytest.raises(ConfigError):
await cfg.option('c').value.set(True) cfg.option('c').value.set(True)
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_owner(config_type):
async def test_symlink_owner(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.option('s1.b').owner.isdefault() assert cfg.option('s1.b').owner.isdefault()
assert await cfg.option('c').owner.isdefault() assert cfg.option('c').owner.isdefault()
await cfg.option('s1.b').value.set(True) cfg.option('s1.b').value.set(True)
assert not await cfg.option('s1.b').owner.isdefault() assert not cfg.option('s1.b').owner.isdefault()
assert not await cfg.option('c').owner.isdefault() assert not cfg.option('c').owner.isdefault()
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_get_information():
async def test_symlink_get_information():
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
boolopt.impl_set_information('test', 'test') boolopt.impl_set_information('test', 'test')
@ -237,8 +276,7 @@ async def test_symlink_get_information():
assert linkopt.impl_get_information('test') == 'test2' assert linkopt.impl_get_information('test') == 'test2'
@pytest.mark.asyncio def test_symlink_leader():
async def test_symlink_leader():
a = StrOption('a', "", multi=True) a = StrOption('a', "", multi=True)
ip_admin_eth0 = SymLinkOption('ip_admin_eth0', a) ip_admin_eth0 = SymLinkOption('ip_admin_eth0', a)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "", multi=True) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "", multi=True)
@ -246,8 +284,7 @@ async def test_symlink_leader():
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
@pytest.mark.asyncio def test_symlink_followers():
async def test_symlink_followers():
a = StrOption('a', "", multi=True) a = StrOption('a', "", multi=True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = SymLinkOption('netmask_admin_eth0', a) netmask_admin_eth0 = SymLinkOption('netmask_admin_eth0', a)
@ -255,107 +292,117 @@ async def test_symlink_followers():
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
@pytest.mark.asyncio def test_symlink_with_leader(config_type):
async def test_symlink_with_leader(config_type):
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
leader = SymLinkOption('leader', ip_admin_eth0) leader = SymLinkOption('leader', ip_admin_eth0)
od = OptionDescription('root', '', [interface1, leader]) od1 = OptionDescription('root', '', [interface1, leader])
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []} assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'leader': []}
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'leader': ['val1', 'val2']} assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': 'val1', 'ip_admin_eth0.netmask_admin_eth0': None}, {'ip_admin_eth0.ip_admin_eth0': 'val2', 'ip_admin_eth0.netmask_admin_eth0': None}], 'leader': ['val1', 'val2']}
assert not await list_sessions() cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
with pytest.raises(ConfigError):
cfg.option('leader').value.pop(0)
# assert not list_sessions()
@pytest.mark.asyncio def test_symlink_with_follower(config_type):
async def test_symlink_with_follower(config_type):
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True) 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) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
follower = SymLinkOption('follower', netmask_admin_eth0) follower = SymLinkOption('follower', netmask_admin_eth0)
od = OptionDescription('root', '', [interface1, follower]) od1 = OptionDescription('root', '', [interface1, follower])
async with await Config(od) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []} assert not cfg.option('follower').isoptiondescription()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'follower': []}
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]} cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': 'val1', 'ip_admin_eth0.netmask_admin_eth0': None}, {'ip_admin_eth0.ip_admin_eth0': 'val2', 'ip_admin_eth0.netmask_admin_eth0': None}], 'follower': [None, None]}
# #
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'default' assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'default'
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'default' assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'default'
assert await cfg.option('follower', 0).owner.get() == 'default' with pytest.raises(ConfigError):
assert await cfg.option('follower', 1).owner.get() == 'default' assert cfg.option('follower', 0).owner.get() == 'default'
assert await cfg.option('follower').owner.get() == ['default', 'default'] assert cfg.option('follower').owner.get() == 'default'
# #
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
assert await cfg.option('follower', 0).value.get() == None with pytest.raises(ConfigError):
assert await cfg.option('follower', 1).value.get() == None assert cfg.option('follower', 0).value.get() == None
assert await cfg.option('follower').value.get() == [None, None] assert cfg.option('follower').value.get() == [None, None]
# #
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3') cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3')
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, 'val3'], 'follower': [None, 'val3']} assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': 'val1', 'ip_admin_eth0.netmask_admin_eth0': None}, {'ip_admin_eth0.ip_admin_eth0': 'val2', 'ip_admin_eth0.netmask_admin_eth0': 'val3'}], 'follower': [None, 'val3']}
# #
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3' assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3'
assert await cfg.option('follower', 0).value.get() == None with pytest.raises(ConfigError):
assert await cfg.option('follower', 1).value.get() == 'val3' assert cfg.option('follower', 0).value.get() == None
assert await cfg.option('follower').value.get() == [None, 'val3'] assert cfg.option('follower').value.get() == [None, 'val3']
# #
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'default' assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'default'
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'user' assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'user'
assert await cfg.option('follower', 0).owner.get() == 'default' with pytest.raises(ConfigError):
assert await cfg.option('follower', 1).owner.get() == 'user' assert cfg.option('follower', 0).owner.get() == 'default'
assert await cfg.option('follower').owner.get() == ['default', 'user'] assert cfg.option('follower').owner.get() == 'user'
assert not await list_sessions() # assert not list_sessions()
#____________________________________________________________ #____________________________________________________________
@pytest.mark.asyncio def test_symlink_dependency():
async def test_symlink_dependency():
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
assert await cfg.option('s1.b').option.has_dependency() is False assert cfg.option('s1.b').has_dependency() is False
assert await cfg.option('c').option.has_dependency() is True assert cfg.option('c').has_dependency() is True
assert await cfg.option('s1.b').option.has_dependency(False) is True assert cfg.option('s1.b').has_dependency(False) is True
assert await cfg.option('c').option.has_dependency(False) is False assert cfg.option('c').has_dependency(False) is False
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_makedict(config_type):
async def test_symlink_makedict(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
assert await cfg.value.dict() == {'c': False, 's1.b': False} assert cfg.value.dict() == {'c': False, 's1.b': False}
await cfg.option('s1.b').value.set(True) cfg.option('s1.b').value.set(True)
assert await cfg.value.dict() == {'c': True, 's1.b': True} assert cfg.value.dict() == {'c': True, 's1.b': True}
assert not await list_sessions() # assert not list_sessions()
@pytest.mark.asyncio def test_symlink_list(config_type):
async def test_symlink_list(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", od1 = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
async with await Config(descr) as cfg: cfg = Config(od1)
cfg = await get_config(cfg, config_type) cfg = get_config(cfg, config_type)
list_opt = [] list_opt = []
for opt in await cfg.option.list(): for opt in cfg.option.list():
list_opt.append(await opt.option.path()) list_opt.append(opt.path())
assert list_opt == ['c'] assert list_opt == ['c']
# #
list_opt = [] list_opt = []
for opt in await cfg.option.list(recursive=True): for opt in cfg.option.list(recursive=True):
list_opt.append(await opt.option.path()) list_opt.append(opt.path())
assert list_opt == ['c', 's1.b'] assert list_opt == ['c', 's1.b']
assert not await list_sessions() # assert not list_sessions()
def test_submulti():
multi = StrOption('multi', '', multi=submulti)
multi2 = SymLinkOption('multi2', multi)
od1 = OptionDescription('od', '', [multi, multi2])
cfg = Config(od1)
assert cfg.option('multi').ismulti()
assert cfg.option('multi').issubmulti()
assert cfg.option('multi2').ismulti()
assert cfg.option('multi2').issubmulti()

View file

@ -16,16 +16,14 @@
""" """
from .function import calc_value, calc_value_property_help, valid_ip_netmask, \ from .function import calc_value, calc_value_property_help, valid_ip_netmask, \
valid_network_netmask, valid_in_network, valid_broadcast, \ valid_network_netmask, valid_in_network, valid_broadcast, \
valid_not_equal valid_not_equal, function_waiting_for_dict
from .autolib import Calculation, Params, ParamOption, ParamDynOption, ParamSelfOption, \ from .autolib import Calculation, Params, ParamOption, ParamDynOption, ParamSelfOption, \
ParamValue, ParamIndex, ParamSuffix, ParamInformation, ParamSelfInformation ParamValue, ParamIndex, ParamSuffix, ParamInformation, ParamSelfInformation
from .option import * from .option import *
from .error import APIError from .error import ConfigError
from .api import Config, MetaConfig, GroupConfig, MixConfig from .api import Config, MetaConfig, GroupConfig, MixConfig
from .option import __all__ as all_options from .option import __all__ as all_options
from .setting import owners, groups, undefined from .setting import owners, groups, undefined
from .storage import default_storage, Storage, list_sessions, \
delete_session
allfuncs = ['Calculation', allfuncs = ['Calculation',
@ -42,20 +40,17 @@ allfuncs = ['Calculation',
'MixConfig', 'MixConfig',
'GroupConfig', 'GroupConfig',
'Config', 'Config',
'APIError', 'ConfigError',
'undefined', 'undefined',
'owners', 'owners',
'groups', 'groups',
'default_storage',
'Storage',
'list_sessions',
'delete_session',
'calc_value', 'calc_value',
'calc_value_property_help', 'calc_value_property_help',
'valid_ip_netmask', 'valid_ip_netmask',
'valid_network_netmask', 'valid_network_netmask',
'valid_in_network', 'valid_in_network',
'valid_broadcast', 'valid_broadcast',
'function_waiting_for_dict',
] ]
allfuncs.extend(all_options) allfuncs.extend(all_options)
del(all_options) del(all_options)

File diff suppressed because it is too large Load diff

View file

@ -1,29 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2019-2023 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# largely inspired by https://github.com/kchmck/pyasyncinit
# ____________________________________________________________
from functools import wraps
def asyncinit(obj):
@wraps(obj.__new__)
async def new(cls, *args, **kwargs):
instance = object.__new__(cls) # (cls, *args, **kwargs)
await instance.__init__(*args, **kwargs)
return instance
obj.__new__ = new
return obj

View file

@ -19,12 +19,12 @@
# ____________________________________________________________ # ____________________________________________________________
"enables us to carry out a calculation and return an option's value" "enables us to carry out a calculation and return an option's value"
from typing import Any, Optional, Union, Callable, Dict, List from typing import Any, Optional, Union, Callable, Dict, List
from types import CoroutineType
from itertools import chain from itertools import chain
from .error import PropertiesOptionError, ConfigError, LeadershipError, ValueWarning from .error import PropertiesOptionError, ConfigError, LeadershipError, ValueWarning
from .i18n import _ from .i18n import _
from .setting import undefined, ConfigBag, OptionBag, Undefined from .setting import undefined, ConfigBag, OptionBag, Undefined
from .function import FUNCTION_WAITING_FOR_DICT
# ____________________________________________________________ # ____________________________________________________________
@ -59,15 +59,15 @@ class Param:
class ParamOption(Param): class ParamOption(Param):
__slots__ = ('todict', __slots__ = ('option',
'option',
'notraisepropertyerror', 'notraisepropertyerror',
'raisepropertyerror') 'raisepropertyerror',
)
def __init__(self, def __init__(self,
option: 'Option', option: 'Option',
notraisepropertyerror: bool=False, notraisepropertyerror: bool=False,
raisepropertyerror: bool=False, raisepropertyerror: bool=False,
todict: bool=False) -> None: ) -> None:
if __debug__ and not hasattr(option, 'impl_is_symlinkoption'): if __debug__ and not hasattr(option, 'impl_is_symlinkoption'):
raise ValueError(_('paramoption needs an option not {}').format(type(option))) raise ValueError(_('paramoption needs an option not {}').format(type(option)))
if option.impl_is_symlinkoption(): if option.impl_is_symlinkoption():
@ -76,40 +76,36 @@ class ParamOption(Param):
cur_opt = option cur_opt = option
assert isinstance(notraisepropertyerror, bool), _('param must have a boolean not a {} for notraisepropertyerror').format(type(notraisepropertyerror)) assert isinstance(notraisepropertyerror, bool), _('param must have a boolean not a {} for notraisepropertyerror').format(type(notraisepropertyerror))
assert isinstance(raisepropertyerror, bool), _('param must have a boolean not a {} for raisepropertyerror').format(type(raisepropertyerror)) assert isinstance(raisepropertyerror, bool), _('param must have a boolean not a {} for raisepropertyerror').format(type(raisepropertyerror))
self.todict = todict
self.option = cur_opt self.option = cur_opt
self.notraisepropertyerror = notraisepropertyerror self.notraisepropertyerror = notraisepropertyerror
self.raisepropertyerror = raisepropertyerror self.raisepropertyerror = raisepropertyerror
class ParamDynOption(ParamOption): class ParamDynOption(ParamOption):
__slots__ = ('suffix',) __slots__ = ('subpath',)
def __init__(self, def __init__(self,
option: 'Option', option: 'Option',
suffix: str, subpath: str,
dynoptiondescription: 'DynOptionDescription', dynoptiondescription: 'DynOptionDescription',
notraisepropertyerror: bool=False, notraisepropertyerror: bool=False,
raisepropertyerror: bool=False, raisepropertyerror: bool=False,
optional: bool=False, optional: bool=False,
todict: bool=False,
) -> None: ) -> None:
super().__init__(option, super().__init__(option,
notraisepropertyerror, notraisepropertyerror,
raisepropertyerror, raisepropertyerror,
todict,
) )
self.suffix = suffix self.subpath = subpath
self.dynoptiondescription = dynoptiondescription self.dynoptiondescription = dynoptiondescription
self.optional = optional self.optional = optional
class ParamSelfOption(Param): class ParamSelfOption(Param):
__slots__ = ('todict', 'whole') __slots__ = ('whole')
def __init__(self, def __init__(self,
todict: bool=False, whole: bool=undefined,
whole: bool=undefined) -> None: ) -> None:
"""whole: send all value for a multi, not only indexed value""" """whole: send all value for a multi, not only indexed value"""
self.todict = todict
if whole is not undefined: if whole is not undefined:
self.whole = whole self.whole = whole
@ -121,13 +117,25 @@ class ParamValue(Param):
class ParamInformation(Param): class ParamInformation(Param):
__slots__ = ('information_name',) __slots__ = ('information_name',
'default_value',
'option',
)
def __init__(self, def __init__(self,
information_name: str, information_name: str,
default_value: Any=undefined, default_value: Any=undefined,
option: 'Option'=None
) -> None: ) -> None:
self.information_name = information_name self.information_name = information_name
self.default_value = default_value self.default_value = default_value
if option:
if option.impl_is_symlinkoption():
raise ValueError(_('option in ParamInformation cannot be a symlinkoption'))
if option.impl_is_follower():
raise ValueError(_('option in ParamInformation cannot be a follower'))
if option.impl_is_dynsymlinkoption():
raise ValueError(_('option in ParamInformation cannot be a dynamic option'))
self.option = option
class ParamSelfInformation(ParamInformation): class ParamSelfInformation(ParamInformation):
@ -147,12 +155,14 @@ class Calculation:
'params', 'params',
'help_function', 'help_function',
'_has_index', '_has_index',
'warnings_only') 'warnings_only',
)
def __init__(self, def __init__(self,
function: Callable, function: Callable,
params: Params=Params(), params: Params=Params(),
help_function: Optional[Callable]=None, help_function: Optional[Callable]=None,
warnings_only: bool=False): warnings_only: bool=False,
):
assert isinstance(function, Callable), _('first argument ({0}) must be a function').format(function) assert isinstance(function, Callable), _('first argument ({0}) must be a function').format(function)
if help_function: if help_function:
assert isinstance(help_function, Callable), _('help_function ({0}) must be a function').format(help_function) assert isinstance(help_function, Callable), _('help_function ({0}) must be a function').format(help_function)
@ -168,74 +178,57 @@ class Calculation:
if warnings_only is True: if warnings_only is True:
self.warnings_only = warnings_only self.warnings_only = warnings_only
async def execute(self, def execute(self,
option_bag: OptionBag, option_bag: OptionBag,
leadership_must_have_index: bool=False,
orig_value: Any=undefined, orig_value: Any=undefined,
allow_value_error: bool=False, allow_value_error: bool=False,
force_value_warning: bool=False, force_value_warning: bool=False,
for_settings: bool=False, for_settings: bool=False,
) -> Any: ) -> Any:
return await carry_out_calculation(option_bag.option, return carry_out_calculation(option_bag.option,
callback=self.function, callback=self.function,
callback_params=self.params, callback_params=self.params,
index=option_bag.index, index=option_bag.index,
config_bag=option_bag.config_bag, config_bag=option_bag.config_bag,
leadership_must_have_index=leadership_must_have_index,
orig_value=orig_value, orig_value=orig_value,
allow_value_error=allow_value_error, allow_value_error=allow_value_error,
force_value_warning=force_value_warning, force_value_warning=force_value_warning,
for_settings=for_settings, for_settings=for_settings,
) )
async def help(self, def help(self,
option_bag: OptionBag, option_bag: OptionBag,
leadership_must_have_index: bool=False,
for_settings: bool=False, for_settings: bool=False,
) -> str: ) -> str:
if not self.help_function: if not self.help_function:
return await self.execute(option_bag, return self.execute(option_bag,
leadership_must_have_index=leadership_must_have_index,
for_settings=for_settings, for_settings=for_settings,
) )
return await carry_out_calculation(option_bag.option, return carry_out_calculation(option_bag.option,
callback=self.help_function, callback=self.help_function,
callback_params=self.params, callback_params=self.params,
index=option_bag.index, index=option_bag.index,
config_bag=option_bag.config_bag, config_bag=option_bag.config_bag,
leadership_must_have_index=leadership_must_have_index,
for_settings=for_settings, for_settings=for_settings,
) )
def has_index(self, current_option): def __deepcopy__(x, memo):
if hasattr(self, '_has_index'): return x
return self._has_index
self._has_index = False
for arg in chain(self.params.args, self.params.kwargs.values()):
if isinstance(arg, ParamOption) and arg.option.impl_get_leadership() and \
arg.option.impl_get_leadership().in_same_group(current_option):
self._has_index = True
break
return self._has_index
class Break(Exception): def manager_callback(callback: Callable,
pass param: Param,
async def manager_callback(callbk: Param,
option, option,
index: Optional[int], index: Optional[int],
orig_value, orig_value,
config_bag: ConfigBag, config_bag: ConfigBag,
leadership_must_have_index: bool,
for_settings: bool, for_settings: bool,
) -> Any: ) -> Any:
"""replace Param by true value""" """replace Param by true value"""
def calc_index(callbk, index, same_leadership): def calc_index(param, index, same_leadership):
if index is not None: if index is not None:
if hasattr(callbk, 'whole'): if hasattr(param, 'whole'):
whole = callbk.whole whole = param.whole
else: else:
# if value is same_leadership, follower are isolate by default # if value is same_leadership, follower are isolate by default
# otherwise option is a whole option # otherwise option is a whole option
@ -244,19 +237,32 @@ async def manager_callback(callbk: Param,
return index return index
return None return None
async def calc_self(callbk, option, index, value, config_bag): def calc_self(param,
option,
index,
value,
config_bag,
):
# index must be apply only if follower # index must be apply only if follower
is_follower = option.impl_is_follower() is_follower = option.impl_is_follower()
apply_index = calc_index(callbk, index, is_follower) apply_index = calc_index(param, index, is_follower)
if value is undefined or (apply_index is None and is_follower): if value is undefined or (apply_index is None and is_follower):
if config_bag is undefined:
return undefined
path = option.impl_getpath() path = option.impl_getpath()
option_bag = await get_option_bag(config_bag, option_bag = OptionBag(option,
None,
config_bag,
properties=None,
)
properties = config_bag.context.get_settings().getproperties(option_bag,
uncalculated=True,
)
new_value = get_value(config_bag,
option, option,
param,
apply_index, apply_index,
True) True,
new_value = await get_value(callbk, option_bag, path) properties,
)
if apply_index is None and is_follower: if apply_index is None and is_follower:
new_value[index] = value new_value[index] = value
value = new_value value = new_value
@ -264,36 +270,70 @@ async def manager_callback(callbk: Param,
value = value[apply_index] value = value[apply_index]
return value return value
async def get_value(callbk, def get_value(config_bag,
option_bag, option,
path, param,
index,
self_calc,
properties=undefined,
): ):
parent_option_bag, option_bag = get_option_bag(config_bag,
option,
param,
index,
self_calc,
properties=properties,
)
if option.impl_is_follower() and index is None:
value = []
for idx in range(config_bag.context.get_length_leadership(parent_option_bag)):
parent_option_bag, option_bag = get_option_bag(config_bag,
option,
param,
idx,
self_calc,
properties=properties,
)
value.append(_get_value(param,
option_bag,
))
else:
value = _get_value(param,
option_bag,
)
return value
def _get_value(param: Params,
option_bag: OptionBag,
) -> Any:
try: try:
# get value # get value
value = await config_bag.context.getattr(path, value = config_bag.context.get_value(option_bag)
option_bag)
except PropertiesOptionError as err: except PropertiesOptionError as err:
# raise PropertiesOptionError (which is catched) because must not add value None in carry_out_calculation # raise PropertiesOptionError (which is catched) because must not add value None in carry_out_calculation
if callbk.notraisepropertyerror or callbk.raisepropertyerror: if param.notraisepropertyerror or param.raisepropertyerror:
raise err from err raise err from err
raise ConfigError(_('unable to carry out a calculation for "{}"' raise ConfigError(_('unable to carry out a calculation for "{}"'
', {}').format(option.impl_get_display_name(), err), err) from err ', {}').format(option.impl_get_display_name(), err), err) from err
except ValueError as err: except ValueError as err:
raise ValueError(_('the option "{0}" is used in a calculation but is invalid ({1})').format(option_bag.option.impl_get_display_name(), err)) from err raise ValueError(_('the option "{0}" is used in a calculation but is invalid ({1})').format(option_bag.option.impl_get_display_name(), err)) from err
except AttributeError as err: except AttributeError as err:
if isinstance(callbk, ParamDynOption) and callbk.optional: if isinstance(param, ParamDynOption) and param.optional:
# cannot acces, simulate a propertyerror # cannot acces, simulate a propertyerror
raise PropertiesOptionError(option_bag, raise PropertiesOptionError(option_bag,
['configerror'], ['configerror'],
config_bag.context.cfgimpl_get_settings(), config_bag.context.get_settings(),
) )
raise ConfigError(_(f'unable to get value for calculating "{option_bag.option.impl_get_display_name()}", {err}')) from err raise ConfigError(_(f'unable to get value for calculating "{option_bag.option.impl_get_display_name()}", {err}')) from err
return value return value
async def get_option_bag(config_bag, def get_option_bag(config_bag,
opt, opt,
param,
index_, index_,
self_calc): self_calc,
properties=undefined,
):
# don't validate if option is option that we tried to validate # don't validate if option is option that we tried to validate
config_bag = config_bag.copy() config_bag = config_bag.copy()
if for_settings: if for_settings:
@ -301,103 +341,165 @@ async def manager_callback(callbk: Param,
config_bag.set_permissive() config_bag.set_permissive()
if not for_settings: if not for_settings:
config_bag.properties -= {'warnings'} config_bag.properties -= {'warnings'}
option_bag = OptionBag() if self_calc:
option_bag.set_option(opt, config_bag.unrestraint()
config_bag.remove_validation()
root_option_bag = OptionBag(config_bag.context.get_description(),
None,
config_bag,
)
try:
options_bag = config_bag.context.get_sub_option_bag(root_option_bag,
opt.impl_getpath(),
index_, index_,
config_bag) validate_properties=not self_calc,
if not self_calc: properties=properties,
option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag) )
except PropertiesOptionError as err:
# raise PropertiesOptionError (which is catched) because must not add value None in carry_out_calculation
if param.notraisepropertyerror or param.raisepropertyerror:
raise err from err
raise ConfigError(_('unable to carry out a calculation for "{}"'
', {}').format(option.impl_get_display_name(), err), err) from err
except ValueError as err:
raise ValueError(_('the option "{0}" is used in a calculation but is invalid ({1})').format(option.impl_get_display_name(), err)) from err
except AttributeError as err:
if isinstance(param, ParamDynOption) and param.optional:
# cannot acces, simulate a propertyerror
raise PropertiesOptionError(param,
['configerror'],
config_bag.context.get_settings(),
)
raise ConfigError(_(f'unable to get value for calculating "{option.impl_get_display_name()}", {err}')) from err
if len(options_bag) > 1:
parent_option_bag = options_bag[-2]
else: else:
option_bag.config_bag.unrestraint() parent_option_bag = None
option_bag.config_bag.remove_validation() return parent_option_bag, options_bag[-1]
# if we are in properties calculation, cannot calculated properties
option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag,
apply_requires=False)
return option_bag
if isinstance(callbk, ParamValue): if isinstance(param, ParamValue):
return callbk.value return param.value
if isinstance(callbk, ParamInformation): if isinstance(param, ParamInformation):
if isinstance(callbk, ParamSelfInformation): if isinstance(param, ParamSelfInformation):
option_bag = OptionBag() option_bag = OptionBag(option,
option_bag.set_option(option,
index, index,
config_bag, config_bag,
) )
elif param.option:
option_bag = OptionBag(param.option,
None,
config_bag,
)
else: else:
option_bag = None option_bag = None
try: try:
return await config_bag.context.impl_get_information(config_bag, return config_bag.context.get_values().get_information(option_bag,
option_bag, param.information_name,
callbk.information_name, param.default_value,
callbk.default_value,
) )
except ValueError as err: except ValueError as err:
raise ConfigError(_('option "{}" cannot be calculated: {}').format(option.impl_get_display_name(), raise ConfigError(_('option "{}" cannot be calculated: {}').format(option.impl_get_display_name(),
str(err), str(err),
)) ))
if isinstance(callbk, ParamIndex): if isinstance(param, ParamIndex):
return index return index
if isinstance(callbk, ParamSuffix): if isinstance(param, ParamSuffix):
if not option.issubdyn(): if not option.issubdyn():
raise ConfigError(_('option "{}" is not in a dynoptiondescription').format(option.impl_get_display_name())) raise ConfigError(_('option "{}" is not in a dynoptiondescription').format(option.impl_get_display_name()))
return option.impl_getsuffix() return option.impl_getsuffix()
if isinstance(callbk, ParamSelfOption): if isinstance(param, ParamSelfOption):
if leadership_must_have_index and option.impl_is_follower() and index is None: value = calc_self(param,
raise Break() option,
value = await calc_self(callbk, option, index, orig_value, config_bag) index,
if not callbk.todict: orig_value,
config_bag,
)
if callback.__name__ not in FUNCTION_WAITING_FOR_DICT:
return value return value
return {'name': option.impl_get_display_name(), return {'name': option.impl_get_display_name(),
'value': value} 'value': value,
}
if isinstance(callbk, ParamOption): if isinstance(param, ParamOption):
callbk_option = callbk.option callbk_option = param.option
callbk_options = None callbk_options = None
if callbk_option.issubdyn(): if callbk_option.issubdyn():
found = False found = False
if isinstance(callbk, ParamDynOption): if isinstance(param, ParamDynOption):
subdyn = callbk.dynoptiondescription od_path = param.dynoptiondescription.impl_getpath()
rootpath = subdyn.impl_getpath() + callbk.suffix if "." in od_path:
suffix = callbk.suffix rootpath = od_path.rsplit('.', 1)[0] + '.'
callbk_option = callbk_option.to_dynoption(rootpath, else:
suffix, rootpath = ''
subdyn) full_path = rootpath + param.subpath
root_option_bag = OptionBag(config_bag.context.get_description(),
None,
config_bag,
)
try:
soptions_bag = config_bag.context.get_sub_option_bag(root_option_bag,
full_path,
#FIXME index?
index=None,
validate_properties=True,
properties=None,
)
except AttributeError as err:
raise ConfigError(_(f'option "{option.impl_get_display_name()}" is not in a dynoptiondescription: {err}'))
callbk_option = soptions_bag[-1].option
found = True
elif option.impl_is_sub_dyn_optiondescription():
if option.getsubdyn() == callbk_option.getsubdyn():
root_path = option.impl_getpath().rsplit('.', 1)[0]
len_path = root_path.count('.')
full_path = root_path + '.' + callbk_option.impl_getpath().split('.', len_path + 1)[-1]
root_option_bag = OptionBag(config_bag.context.get_description(),
None,
config_bag,
)
try:
soptions_bag = config_bag.context.get_sub_option_bag(root_option_bag,
full_path,
#FIXME index?
index=None,
validate_properties=True,
properties=None,
)
except AttributeError as err:
raise ConfigError(_(f'option "{option.impl_get_display_name()}" is not in a dynoptiondescription: {err}'))
callbk_option = soptions_bag[-1].option
found = True found = True
elif option.impl_is_dynsymlinkoption(): elif option.impl_is_dynsymlinkoption():
rootpath = option.rootpath rootpath = option.rootpath
call_path = callbk_option.impl_getpath() call_path = callbk_option.impl_getpath()
if call_path.startswith(option.opt.impl_getpath().rsplit('.', 1)[0]): if option.opt.issubdyn() and callbk_option.getsubdyn() == option.getsubdyn() or \
not option.opt.issubdyn() and callbk_option.getsubdyn() == option.opt:
# in same dynoption # in same dynoption
if len(callbk_option.impl_getpath().split('.')) == len(rootpath.split('.')):
rootpath = rootpath.rsplit('.', 1)[0]
suffix = option.impl_getsuffix() suffix = option.impl_getsuffix()
subdyn = callbk_option.getsubdyn() subdyn = callbk_option.getsubdyn()
callbk_option = callbk_option.to_dynoption(rootpath, root_path, sub_path = subdyn.split_path(subdyn,
option,
)
if root_path:
parent_path = root_path + subdyn.impl_getname(suffix) + sub_path
else:
parent_path = subdyn.impl_getname(suffix) + sub_path
callbk_option = callbk_option.to_dynoption(parent_path,
suffix, suffix,
subdyn, subdyn,
) )
found = True found = True
if not found: if not found:
callbk_options = [] callbk_options = []
dynopt = callbk_option.getsubdyn() for doption_bag in callbk_option.getsubdyn().get_sub_children(callbk_option,
rootpath = dynopt.impl_getpath() config_bag,
subpaths = [rootpath] + callbk_option.impl_getpath()[len(rootpath) + 1:].split('.')[:-1] index=None,
for suffix in await dynopt.get_suffixes(config_bag): ):
path_suffix = dynopt.convert_suffix_to_path(suffix) callbk_options.append(doption_bag.option)
subpath = '.'.join([subp + path_suffix for subp in subpaths])
doption = callbk_option.to_dynoption(subpath,
suffix,
dynopt)
callbk_options.append(doption)
if leadership_must_have_index and callbk_option.impl_is_follower() and index is None:
raise Break()
if config_bag is undefined:
return undefined
if callbk_options is None: if callbk_options is None:
callbk_options = [callbk_option] callbk_options = [callbk_option]
values = None values = None
@ -405,7 +507,7 @@ async def manager_callback(callbk: Param,
values = [] values = []
for callbk_option in callbk_options: for callbk_option in callbk_options:
if index is not None and callbk_option.impl_get_leadership() and \ if index is not None and callbk_option.impl_get_leadership() and \
callbk_option.impl_get_leadership().in_same_group(option): callbk_option.impl_get_leadership().in_same_leadership(option):
if not callbk_option.impl_is_follower(): if not callbk_option.impl_is_follower():
# leader # leader
index_ = None index_ = None
@ -417,14 +519,13 @@ async def manager_callback(callbk: Param,
else: else:
index_ = None index_ = None
with_index = False with_index = False
path = callbk_option.impl_getpath() if callbk_option.impl_getpath() == 'od.dodval1.st.boolean':
option_bag = await get_option_bag(config_bag, raise Exception('pfff')
value = get_value(config_bag,
callbk_option, callbk_option,
param,
index_, index_,
False) False,
value = await get_value(callbk,
option_bag,
path,
) )
if with_index: if with_index:
value = value[index] value = value[index]
@ -432,21 +533,18 @@ async def manager_callback(callbk: Param,
values.append(value) values.append(value)
if values is not None: if values is not None:
value = values value = values
if not callbk.todict: if callback.__name__ not in FUNCTION_WAITING_FOR_DICT:
return value return value
return {'name': callbk_option.impl_get_display_name(), return {'name': callbk_option.impl_get_display_name(),
'value': value} 'value': value}
raise ConfigError(_('unknown callback type {} in option {}').format(callbk,
option.impl_get_display_name()))
async def carry_out_calculation(option, def carry_out_calculation(option,
callback: Callable, callback: Callable,
callback_params: Optional[Params], callback_params: Optional[Params],
index: Optional[int], index: Optional[int],
config_bag: Optional[ConfigBag], config_bag: Optional[ConfigBag],
orig_value=undefined, orig_value=undefined,
leadership_must_have_index: bool=False,
allow_value_error: bool=False, allow_value_error: bool=False,
force_value_warning: bool=False, force_value_warning: bool=False,
for_settings: bool=False, for_settings: bool=False,
@ -467,43 +565,42 @@ async def carry_out_calculation(option,
- tuple with option and boolean's force_permissive (True when don't raise - tuple with option and boolean's force_permissive (True when don't raise
if PropertiesOptionError) if PropertiesOptionError)
Values could have multiple values only when key is ''.""" Values could have multiple values only when key is ''."""
if not option.impl_is_optiondescription() and option.impl_is_follower() and index is None:
raise Exception('follower must have index in carry_out_calculation!')
def fake_items(iterator): def fake_items(iterator):
return ((None, i) for i in iterator) return ((None, i) for i in iterator)
args = [] args = []
kwargs = {} kwargs = {}
if callback_params: if callback_params:
for key, callbk in chain(fake_items(callback_params.args), callback_params.kwargs.items()): for key, param in chain(fake_items(callback_params.args), callback_params.kwargs.items()):
try: try:
value = await manager_callback(callbk, value = manager_callback(callback,
param,
option, option,
index, index,
orig_value, orig_value,
config_bag, config_bag,
leadership_must_have_index,
for_settings, for_settings,
) )
if value is undefined:
return undefined
if key is None: if key is None:
args.append(value) args.append(value)
else: else:
kwargs[key] = value kwargs[key] = value
except PropertiesOptionError as err: except PropertiesOptionError as err:
if callbk.raisepropertyerror: if param.raisepropertyerror:
raise err raise err
if callbk.todict: if callback.__name__ in FUNCTION_WAITING_FOR_DICT:
if key is None: if key is None:
args.append({'propertyerror': str(err)}) args.append({'propertyerror': str(err), 'name': option.impl_get_display_name()})
else: else:
kwargs[key] = {'propertyerror': str(err)} kwargs[key] = {'propertyerror': str(err), 'name': option.impl_get_display_name()}
except Break: ret = calculate(option,
continue
ret = await calculate(option,
callback, callback,
allow_value_error, allow_value_error,
force_value_warning, force_value_warning,
args, args,
kwargs) kwargs,
)
if isinstance(ret, list) and not option.impl_is_dynoptiondescription() and \ if isinstance(ret, list) and not option.impl_is_dynoptiondescription() and \
option.impl_is_follower() and not option.impl_is_submulti(): option.impl_is_follower() and not option.impl_is_submulti():
if args or kwargs: if args or kwargs:
@ -524,7 +621,7 @@ async def carry_out_calculation(option,
return ret return ret
async def calculate(option, def calculate(option,
callback: Callable, callback: Callable,
allow_value_error: bool, allow_value_error: bool,
force_value_warning: bool, force_value_warning: bool,
@ -539,10 +636,7 @@ async def calculate(option,
""" """
try: try:
ret = callback(*args, **kwargs) return callback(*args, **kwargs)
if isinstance(ret, CoroutineType):
ret = await ret
return ret
except (ValueError, ValueWarning) as err: except (ValueError, ValueWarning) as err:
if allow_value_error: if allow_value_error:
if force_value_warning: if force_value_warning:
@ -550,8 +644,6 @@ async def calculate(option,
raise err raise err
error = err error = err
except Exception as err: except Exception as err:
# import traceback
# traceback.print_exc()
error = err error = err
if args or kwargs: if args or kwargs:
msg = _('unexpected error "{0}" in function "{1}" with arguments "{3}" and "{4}" ' msg = _('unexpected error "{0}" in function "{1}" with arguments "{3}" and "{4}" '

106
tiramisu/cacheobj.py Normal file
View file

@ -0,0 +1,106 @@
# -*- coding: utf-8 -*-
"cache used by storage"
# Copyright (C) 2013-2023 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
from time import time
class Cache:
"""cache object
"""
__slots__ = ('_cache',)
def __init__(self):
self._cache = {}
def _get_path_index(self, option_bag):
if option_bag is None:
path = None
index = None
else:
path = option_bag.path
index = option_bag.index
return path, index
def getcache(self,
option_bag,
type_,
expiration=True,
):
"""get the cache value fot a specified path
"""
no_cache = False, None, False
path, index = self._get_path_index(option_bag)
if path not in self._cache or index not in self._cache[path]:
return no_cache
value, timestamp, validated = self._cache[path][index]
if type_ == 'context_props':
# cached value is settings properties so value is props
props = value
self_props = {}
else:
props = option_bag.config_bag.properties
if type_ == 'self_props':
# cached value is self_props
self_props = value
else:
self_props = option_bag.properties
if 'cache' in props or \
'cache' in self_props:
if expiration and timestamp and \
('expire' in props or \
'expire' in self_props):
ntime = int(time())
if timestamp + option_bag.config_bag.expiration_time >= ntime:
return True, value, validated
else:
return True, value, validated
return no_cache
def setcache(self,
option_bag,
val,
type_='values',
validated=True,
):
"""add val in cache for a specified path
if follower, add index
"""
if type_ == 'values':
if 'cache' not in option_bag.config_bag.properties and \
'cache' not in option_bag.properties:
return
elif (option_bag is None or 'cache' not in option_bag.config_bag.properties) and \
'cache' not in val:
return
path, index = self._get_path_index(option_bag)
self._cache.setdefault(path, {})[index] = (val, int(time()), validated)
def delcache(self, path):
"""reset cache a a specified path
"""
if path in self._cache:
del self._cache[path]
def get_cached(self):
"""get cache values
"""
return self._cache
def reset_all_cache(self):
"""reset all cache values
"""
self._cache.clear()

File diff suppressed because it is too large Load diff

View file

@ -128,11 +128,12 @@ class PropertiesOptionError(AttributeError):
# Exceptions for a Config # Exceptions for a Config
class ConfigError(Exception): class ConfigError(Exception):
"""attempt to change an option's owner without a value """attempt to change an option's owner without a value
or in case of `_cfgimpl_descr` is None or in case of `_descr` is None
or if a calculation cannot be carried out""" or if a calculation cannot be carried out"""
def __init__(self, def __init__(self,
exp, exp,
ori_err=None): ori_err=None,
):
super().__init__(exp) super().__init__(exp)
self.ori_err = ori_err self.ori_err = ori_err
@ -209,7 +210,3 @@ class ValueOptionError(_CommonError, ValueError):
class ValueErrorWarning(ValueWarning): class ValueErrorWarning(ValueWarning):
tmpl = _('"{0}" is an invalid {1} for "{2}"') tmpl = _('"{0}" is an invalid {1} for "{2}"')
class APIError(Exception):
pass

View file

@ -12,6 +12,8 @@
# #
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
"""some functions to validates or calculates value
"""
from typing import Any, List, Optional from typing import Any, List, Optional
from operator import add, mul, sub, truediv from operator import add, mul, sub, truediv
from ipaddress import ip_address, ip_interface, ip_network from ipaddress import ip_address, ip_interface, ip_network
@ -20,145 +22,130 @@ from .setting import undefined
from .error import display_list from .error import display_list
def valid_network_netmask(network: str, FUNCTION_WAITING_FOR_DICT = []
netmask: str):
"""FIXME
def function_waiting_for_dict(function):
"""functions (calculation or validation) receive by default only the value of other options
all functions declared with this function recieve a dict with option informations
(value, name, ...)
""" """
if isinstance(network, dict): name = function.__name__
network_value = network['value'] if name not in FUNCTION_WAITING_FOR_DICT:
network_display_name = '({})'.format(network['name']) FUNCTION_WAITING_FOR_DICT.append(name)
else: return function
network_value = network
network_display_name = ''
if None in [network_value, netmask]: @function_waiting_for_dict
def valid_network_netmask(network: dict,
netmask: dict,
):
"""
validates if network and netmask are coherent
this validator must be set to netmask option
"""
if None in [network['value'], netmask['value']]:
return return
try: try:
ip_network('{0}/{1}'.format(network_value, netmask)) ip_network(f'{network["value"]}/{netmask["value"]}')
except ValueError: except ValueError as err:
raise ValueError(_('network "{0}" {1}does not match with this netmask').format(network_value, raise ValueError(_(f'network "{network["value"]}" ({network["name"]}) does not match '
network_display_name)) 'with this netmask')) from err
def valid_ip_netmask(ip: str,
netmask: str): @function_waiting_for_dict
if isinstance(ip, dict): def valid_ip_netmask(ip: dict, # pylint: disable=invalid-name
ip_value = ip['value'] netmask: dict,
ip_display_name = '({})'.format(ip['name']) ):
else: """validates if ip and netmask are coherent
ip_value = ip this validator must be set to netmask option
ip_display_name = '' """
if None in [ip_value, netmask]: if None in [ip['value'], netmask['value']]:
return return
ip_netmask = ip_interface('{0}/{1}'.format(ip_value, netmask)) ip_netmask = ip_interface(f'{ip["value"]}/{netmask["value"]}')
if ip_netmask.ip == ip_netmask.network.network_address: if ip_netmask.ip == ip_netmask.network.network_address:
raise ValueError(_('IP \"{0}\" {1}with this netmask is in fact a network address').format(ip_value, ip_display_name)) msg = _(f'IP "{ip["value"]}" ({ip["name"]}) with this netmask is '
elif ip_netmask.ip == ip_netmask.network.broadcast_address: 'in fact a network address')
raise ValueError(_('IP \"{0}\" {1}with this netmask is in fact a broacast address').format(ip_value, ip_display_name)) raise ValueError(msg)
if ip_netmask.ip == ip_netmask.network.broadcast_address:
msg = _(f'IP "{ip["value"]}" ({ip["name"]}) with this netmask is '
# FIXME CIDR ? 'in fact a broacast address')
def valid_broadcast(network: 'NetworkOption',
netmask: 'NetmaskOption',
broadcast: 'BroadcastOption'):
if isinstance(network, dict):
network_value = network['value']
network_display_name = ' ({})'.format(network['name'])
else:
network_value = network
network_display_name = ''
if isinstance(netmask, dict):
netmask_value = netmask['value']
netmask_display_name = ' ({})'.format(netmask['name'])
else:
netmask_value = netmask
netmask_display_name = ''
if ip_network('{0}/{1}'.format(network, netmask)).broadcast_address != ip_address(broadcast):
raise ValueError(_('broadcast invalid with network {0}{1} and netmask {2}{3}'
'').format(network_value,
network_display_name,
netmask_value,
netmask_display_name))
def valid_in_network(ip,
network,
netmask=None):
if isinstance(network, dict):
network_value = network['value']
network_display_name = ' ({})'.format(network['name'])
else:
network_value = network
network_display_name = ''
if isinstance(netmask, dict):
netmask_value = netmask['value']
netmask_display_name = ' ({})'.format(netmask['name'])
else:
netmask_value = netmask
netmask_display_name = ''
if network_value is None:
return
if '/' in network_value:
network_obj = ip_network('{0}'.format(network_value))
else:
if netmask_value is None:
return
network_obj = ip_network('{0}/{1}'.format(network_value,
netmask_value))
if ip_interface(ip) not in network_obj:
if netmask is None:
msg = _('this IP is not in network {0}{1}').format(network_value,
network_display_name)
else:
msg = _('this IP is not in network {0}{1} with netmask {2}{3}').format(network_value,
network_display_name,
netmask_value,
netmask_display_name)
raise ValueError(msg) raise ValueError(msg)
@function_waiting_for_dict
def valid_broadcast(network: dict,
netmask: dict,
broadcast: dict,
):
"""validates if the broadcast is coherent with network and netmask
"""
if None in [network['value'], netmask['value'], broadcast['value']]:
return
if ip_network(f'{network["value"]}/{netmask["value"]}').broadcast_address != \
ip_address(broadcast['value']):
msg = _(f'broadcast invalid with network {network["value"]} ({network["name"]}) '
f'and netmask {netmask["value"]} ({netmask["name"]})')
raise ValueError(msg)
@function_waiting_for_dict
def valid_in_network(ip: dict, # pylint: disable=invalid-name
network: dict,
netmask=Optional[dict],
):
"""validates if an IP is in a network
this validator must be set to ip option
"""
if None in [ip['value'], network['value']]:
return
if '/' in network['value']:
# it's a CIDR network
network_value = network['value']
else:
if netmask is None or netmask['value'] is None:
return
network_value = f'{network["value"]}/{netmask["value"]}'
network_obj = ip_network(network_value)
ip_netmask = ip_interface(f'{ip["value"]}/{network_obj.netmask}')
if ip_netmask not in network_obj:
if netmask is None:
msg = _('this IP is not in network {network["value"]} ({network["name"]})')
else:
msg = _('this IP is not in network {network["value"]} ({network["name"]}) '
'with netmask {netmask["value"]} ({netmask["name"]})')
raise ValueError(msg)
# test if ip is not network/broadcast IP # test if ip is not network/broadcast IP
ip_netmask = ip_interface('{0}/{1}'.format(ip, network_obj.netmask))
if ip_netmask.ip == ip_netmask.network.network_address: if ip_netmask.ip == ip_netmask.network.network_address:
if netmask is None: msg = _(f'this IP with the network {network["value"]} ({network["value"]} '
msg = _('this IP with the network {0}{1} is in fact a network address').format(network_value, 'is in fact a network address')
network_display_name)
else:
msg = _('this IP with the netmask {0}{1} is in fact a network address').format(netmask_value,
netmask_display_name)
raise ValueError(msg) raise ValueError(msg)
elif ip_netmask.ip == ip_netmask.network.broadcast_address: if ip_netmask.ip == ip_netmask.network.broadcast_address:
if netmask is None: msg = _(f'this IP with the network {network["value"]} ({network["value"]} '
msg = _('this IP with the network {0}{1} is in fact a broadcast address').format(network_value, 'is in fact a broadcast address')
network_display_name)
else:
msg = _('this IP with the netmask {0}{1} is in fact a broadcast address').format(netmask_value,
netmask_display_name)
raise ValueError(msg) raise ValueError(msg)
@function_waiting_for_dict
def valid_not_equal(*values): def valid_not_equal(*values):
"""valid that two options have not same value
"""
equal = set() equal = set()
for idx, val in enumerate(values[1:]): for val in values[1:]:
if isinstance(val, dict):
if 'propertyerror' in val: if 'propertyerror' in val:
continue continue
tval = val['value'] if values[0]['value'] == val['value'] is not None:
else:
tval = val
if values[0] == tval is not None:
if isinstance(val, dict):
if equal is True:
equal = set()
equal.add(val['name']) equal.add(val['name'])
elif not equal: if not equal:
equal = True return
if equal: msg = _(f'value is identical to {display_list(list(equal), add_quote=True)}')
if equal is not True:
msg = _('value is identical to {}').format(display_list(list(equal), add_quote=True))
else:
msg = _('value is identical')
raise ValueError(msg) raise ValueError(msg)
class CalcValue: class CalcValue:
"""class to calc_value with different functions
"""
# pylint: disable=too-many-instance-attributes
def __call__(self, def __call__(self,
*args: List[Any], *args: List[Any],
multi: bool=False, multi: bool=False,
@ -175,6 +162,7 @@ class CalcValue:
operator: Optional[str]=None, operator: Optional[str]=None,
index: Optional[int]=None, index: Optional[int]=None,
**kwargs) -> Any: **kwargs) -> Any:
# pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals
"""calculate value """calculate value
:param args: list of value :param args: list of value
:param multi: value returns must be a list of value :param multi: value returns must be a list of value
@ -183,9 +171,11 @@ class CalcValue:
:param condition: test if condition is equal to expected value :param condition: test if condition is equal to expected value
if there is more than one condition, set condition_0, condition_1, ... if there is more than one condition, set condition_0, condition_1, ...
:param expected: value expected for all conditions :param expected: value expected for all conditions
if expected value is different between condition, set expected_0, expected_1, ... if expected value is different between condition, set expected_0,
expected_1, ...
:param no_condition_is_invalid: if no condition and not condition_0, condition_1, ... (for :param no_condition_is_invalid: if no condition and not condition_0, condition_1, ... (for
example if option is disabled) consider that condition not matching example if option is disabled) consider that condition not
matching
:param condition_operator: OR or AND operator for condition :param condition_operator: OR or AND operator for condition
:param allow_none: if False, do not return list in None is present in list :param allow_none: if False, do not return list in None is present in list
:param remove_duplicate_value: if True, remote duplicated value :param remove_duplicate_value: if True, remote duplicated value
@ -196,28 +186,36 @@ class CalcValue:
examples: examples:
* you want to copy value from an option to an other option: * you want to copy value from an option to an other option:
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, \
... Params, ParamOption
>>> val1 = StrOption('val1', '', 'val1') >>> val1 = StrOption('val1', '', 'val1')
>>> val2 = StrOption('val2', '', callback=calc_value, callback_params=Params(ParamOption(val1))) >>> val2 = StrOption('val2', '', callback=calc_value,
... callback_params=Params(ParamOption(val1)))
>>> od = OptionDescription('root', '', [val1, val2]) >>> od = OptionDescription('root', '', [val1, val2])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 'val1', 'val2': 'val1'} {'val1': 'val1', 'val2': 'val1'}
* you want to copy values from two options in one multi option * you want to copy values from two options in one multi option
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1') >>> val1 = StrOption('val1', "", 'val1')
>>> val2 = StrOption('val2', "", 'val2') >>> val2 = StrOption('val2', "", 'val2')
>>> val3 = StrOption('val3', "", multi=True, callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True))) >>> val3 = StrOption('val3', "", multi=True, callback=calc_value,
... callback_params=Params((ParamOption(val1), ParamOption(val2)),
... multi=ParamValue(True)))
>>> od = OptionDescription('root', '', [val1, val2, val3]) >>> od = OptionDescription('root', '', [val1, val2, val3])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 'val1', 'val2': 'val2', 'val3': ['val1', 'val2']} {'val1': 'val1', 'val2': 'val2', 'val3': ['val1', 'val2']}
* you want to copy a value from an option if it not disabled, otherwise set 'default_value' * you want to copy a value from an option if it not disabled, otherwise set 'default_value'
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', '', 'val1') >>> val1 = StrOption('val1', '', 'val1')
>>> val2 = StrOption('val2', '', callback=calc_value, callback_params=Params(ParamOption(val1, True), default=ParamValue('default_value'))) >>> val2 = StrOption('val2', '', callback=calc_value,
... callback_params=Params(ParamOption(val1, True),
... default=ParamValue('default_value')))
>>> od = OptionDescription('root', '', [val1, val2]) >>> od = OptionDescription('root', '', [val1, val2])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.property.read_write() >>> cfg.property.read_write()
@ -228,10 +226,12 @@ class CalcValue:
{'val2': 'default_value'} {'val2': 'default_value'}
* you want to copy value from an option if an other is True, otherwise set 'default_value' * you want to copy value from an option if an other is True, otherwise set 'default_value'
>>> from tiramisu import calc_value, BoolOption, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, BoolOption, StrOption, OptionDescription, Config, \
... Params, ParamOption, ParamValue
>>> boolean = BoolOption('boolean', '', True) >>> boolean = BoolOption('boolean', '', True)
>>> val1 = StrOption('val1', '', 'val1') >>> val1 = StrOption('val1', '', 'val1')
>>> val2 = StrOption('val2', '', callback=calc_value, callback_params=Params(ParamOption(val1, True), >>> val2 = StrOption('val2', '', callback=calc_value,
... callback_params=Params(ParamOption(val1, True),
... default=ParamValue('default_value'), ... default=ParamValue('default_value'),
... condition=ParamOption(boolean), ... condition=ParamOption(boolean),
... expected=ParamValue(True))) ... expected=ParamValue(True)))
@ -245,41 +245,55 @@ class CalcValue:
{'boolean': False, 'val1': 'val1', 'val2': 'default_value'} {'boolean': False, 'val1': 'val1', 'val2': 'default_value'}
* you want to copy option even if None is present * you want to copy option even if None is present
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1') >>> val1 = StrOption('val1', "", 'val1')
>>> val2 = StrOption('val2', "") >>> val2 = StrOption('val2', "")
>>> val3 = StrOption('val3', "", multi=True, callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), allow_none=ParamValue(True))) >>> val3 = StrOption('val3', "", multi=True, callback=calc_value,
... callback_params=Params((ParamOption(val1), ParamOption(val2)),
... multi=ParamValue(True), allow_none=ParamValue(True)))
>>> od = OptionDescription('root', '', [val1, val2, val3]) >>> od = OptionDescription('root', '', [val1, val2, val3])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 'val1', 'val2': None, 'val3': ['val1', None]} {'val1': 'val1', 'val2': None, 'val3': ['val1', None]}
* you want uniq value * you want uniq value
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1') >>> val1 = StrOption('val1', "", 'val1')
>>> val2 = StrOption('val2', "", 'val1') >>> val2 = StrOption('val2', "", 'val1')
>>> val3 = StrOption('val3', "", multi=True, callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), remove_duplicate_value=ParamValue(True))) >>> val3 = StrOption('val3', "", multi=True, callback=calc_value,
... callback_params=Params((ParamOption(val1), ParamOption(val2)),
... multi=ParamValue(True), remove_duplicate_value=ParamValue(True)))
>>> od = OptionDescription('root', '', [val1, val2, val3]) >>> od = OptionDescription('root', '', [val1, val2, val3])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 'val1', 'val2': 'val1', 'val3': ['val1']} {'val1': 'val1', 'val2': 'val1', 'val3': ['val1']}
* you want to join two values with '.' * you want to join two values with '.'
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1') >>> val1 = StrOption('val1', "", 'val1')
>>> val2 = StrOption('val2', "", 'val2') >>> val2 = StrOption('val2', "", 'val2')
>>> val3 = StrOption('val3', "", callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), join=ParamValue('.'))) >>> val3 = StrOption('val3', "", callback=calc_value,
... callback_params=Params((ParamOption(val1),
... ParamOption(val2)), join=ParamValue('.')))
>>> od = OptionDescription('root', '', [val1, val2, val3]) >>> od = OptionDescription('root', '', [val1, val2, val3])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 'val1', 'val2': 'val2', 'val3': 'val1.val2'} {'val1': 'val1', 'val2': 'val2', 'val3': 'val1.val2'}
* you want join three values, only if almost three values are set * you want join three values, only if almost three values are set
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1') >>> val1 = StrOption('val1', "", 'val1')
>>> val2 = StrOption('val2', "", 'val2') >>> val2 = StrOption('val2', "", 'val2')
>>> val3 = StrOption('val3', "", 'val3') >>> val3 = StrOption('val3', "", 'val3')
>>> val4 = StrOption('val4', "", callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2), ParamOption(val3, True)), join=ParamValue('.'), min_args_len=ParamValue(3))) >>> val4 = StrOption('val4', "", callback=calc_value,
... callback_params=Params((ParamOption(val1),
... ParamOption(val2),
... ParamOption(val3, True)),
... join=ParamValue('.'), min_args_len=ParamValue(3)))
>>> od = OptionDescription('root', '', [val1, val2, val3, val4]) >>> od = OptionDescription('root', '', [val1, val2, val3, val4])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.property.read_write() >>> cfg.property.read_write()
@ -290,25 +304,31 @@ class CalcValue:
{'val1': 'val1', 'val2': 'val2', 'val4': ''} {'val1': 'val1', 'val2': 'val2', 'val4': ''}
* you want to add all values * you want to add all values
>>> from tiramisu import calc_value, IntOption, OptionDescription, Config, Params, ParamOption, ParamValue >>> from tiramisu import calc_value, IntOption, OptionDescription, Config, Params, \
... ParamOption, ParamValue
>>> val1 = IntOption('val1', "", 1) >>> val1 = IntOption('val1', "", 1)
>>> val2 = IntOption('val2', "", 2) >>> val2 = IntOption('val2', "", 2)
>>> val3 = IntOption('val3', "", callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), operator=ParamValue('add'))) >>> val3 = IntOption('val3', "", callback=calc_value,
... callback_params=Params((ParamOption(val1),
ParamOption(val2)),
... operator=ParamValue('add')))
>>> od = OptionDescription('root', '', [val1, val2, val3]) >>> od = OptionDescription('root', '', [val1, val2, val3])
>>> cfg = Config(od) >>> cfg = Config(od)
>>> cfg.value.dict() >>> cfg.value.dict()
{'val1': 1, 'val2': 2, 'val3': 3} {'val1': 1, 'val2': 2, 'val3': 3}
""" """
# pylint: disable=attribute-defined-outside-init
self.args = args self.args = args
self.condition = condition self.condition = condition
self.expected = expected self.expected = expected
self.condition_operator = condition_operator self.condition_operator = condition_operator
self.reverse_condition = reverse_condition self.reverse_condition = reverse_condition
self.kwargs = kwargs self.kwargs = kwargs
self.no_condition_is_invalid = no_condition_is_invalid self.no_condition_is_invalid = no_condition_is_invalid # pylint: disable=attribute-defined-outside-init
value = self.get_value(default, value = self.get_value(default,
min_args_len) min_args_len,
)
if not multi: if not multi:
if join is not None: if join is not None:
if None not in value: if None not in value:
@ -317,12 +337,13 @@ class CalcValue:
value = None value = None
elif value and operator: elif value and operator:
new_value = value[0] new_value = value[0]
op = {'mul': mul, oper = {'mul': mul,
'add': add, 'add': add,
'div': truediv, 'div': truediv,
'sub': sub}[operator] 'sub': sub,
}[operator]
for val in value[1:]: for val in value[1:]:
new_value = op(new_value, val) new_value = oper(new_value, val)
value = new_value value = new_value
elif value == []: elif value == []:
value = None value = None
@ -344,7 +365,9 @@ class CalcValue:
break break
lval = len(val) lval = len(val)
if length_val is not None and length_val != lval: if length_val is not None and length_val != lval:
raise ValueError(_(f'unexpected value in calc_value with join attribute "{val}" with invalid length "{length_val}"')) msg = _('unexpected value in calc_value with join attribute '
f'"{val}" with invalid length "{length_val}"')
raise ValueError(msg)
length_val = lval length_val = lval
new_value = [] new_value = []
if length_val is not None: if length_val is not None:
@ -374,6 +397,9 @@ class CalcValue:
pattern: str, pattern: str,
to_dict: bool=False, to_dict: bool=False,
empty_test=undefined) -> Any: empty_test=undefined) -> Any:
"""get value from kwargs
"""
# pylint: disable=too-many-branches
# if value attribute exist return it's value # if value attribute exist return it's value
# otherwise pattern_0, pattern_1, ... # otherwise pattern_0, pattern_1, ...
# otherwise undefined # otherwise undefined
@ -385,10 +411,9 @@ class CalcValue:
else: else:
kwargs_matches = {} kwargs_matches = {}
len_pattern = len(pattern) len_pattern = len(pattern)
for key in self.kwargs.keys(): for key, pattern_value in self.kwargs.items():
if key.startswith(pattern): if key.startswith(pattern):
index = int(key[len_pattern:]) index = int(key[len_pattern:])
pattern_value = self.kwargs[key]
if isinstance(pattern_value, dict): if isinstance(pattern_value, dict):
pattern_value = pattern_value['value'] pattern_value = pattern_value['value']
kwargs_matches[index] = pattern_value kwargs_matches[index] = pattern_value
@ -408,21 +433,28 @@ class CalcValue:
return returns return returns
def is_condition_matches(self, def is_condition_matches(self,
condition_value): condition_value,
):
"""verify the condition
"""
# pylint: disable=too-many-branches
calculated_conditions = self.value_from_kwargs(condition_value, calculated_conditions = self.value_from_kwargs(condition_value,
'condition_', 'condition_',
to_dict='all') to_dict='all',
)
if calculated_conditions is undefined: if calculated_conditions is undefined:
is_matches = not self.no_condition_is_invalid is_matches = not self.no_condition_is_invalid
else: else:
is_matches = None is_matches = None
calculated_expected = self.value_from_kwargs(self.expected, calculated_expected = self.value_from_kwargs(self.expected,
'expected_', 'expected_',
to_dict=True) to_dict=True,
)
calculated_reverse = self.value_from_kwargs(self.reverse_condition, calculated_reverse = self.value_from_kwargs(self.reverse_condition,
'reverse_condition_', 'reverse_condition_',
to_dict=True, to_dict=True,
empty_test=False) empty_test=False,
)
for idx, calculated_condition in calculated_conditions.items(): for idx, calculated_condition in calculated_conditions.items():
if isinstance(calculated_expected, dict): if isinstance(calculated_expected, dict):
if idx is not None: if idx is not None:
@ -453,14 +485,20 @@ class CalcValue:
if is_matches: if is_matches:
break break
else: else:
raise ValueError(_('unexpected {} condition_operator in calc_value').format(self.condition_operator)) msg = _(f'unexpected {self.condition_operator} condition_operator '
'in calc_value')
raise ValueError(msg)
is_matches = is_matches and not self.reverse_condition \ is_matches = is_matches and not self.reverse_condition \
or not is_matches and self.reverse_condition or not is_matches and self.reverse_condition
return is_matches return is_matches
def get_value(self, def get_value(self,
default, default,
min_args_len): min_args_len,
):
"""get the value from arguments
"""
# retrieve the condition
if isinstance(self.condition, dict): if isinstance(self.condition, dict):
if 'value' in self.condition: if 'value' in self.condition:
condition_value = self.condition['value'] condition_value = self.condition['value']
@ -468,18 +506,19 @@ class CalcValue:
condition_value = undefined condition_value = undefined
else: else:
condition_value = self.condition condition_value = self.condition
condition_matches = self.is_condition_matches(condition_value) # value is empty if condition doesn't match
if not condition_matches: # otherwise value is arg
# force to default if not self.is_condition_matches(condition_value):
value = [] value = []
else: else:
value = self.get_args() value = self.get_args()
if min_args_len and not len(value) >= min_args_len: if min_args_len and not len(value) >= min_args_len:
value = [] value = []
if value == []: if not value:
# default value # default value
new_default = self.value_from_kwargs(default, new_default = self.value_from_kwargs(default,
'default_') 'default_',
)
if new_default is not undefined: if new_default is not undefined:
if not isinstance(new_default, list): if not isinstance(new_default, list):
value = [new_default] value = [new_default]
@ -488,29 +527,34 @@ class CalcValue:
return value return value
def get_args(self): def get_args(self):
"""get all arguments
"""
return list(self.args) return list(self.args)
class CalcValuePropertyHelp(CalcValue): class CalcValuePropertyHelp(CalcValue):
"""special class to display property error
"""
def get_name(self): def get_name(self):
"""get the condition name
"""
return self.condition['name'] return self.condition['name']
def get_indexed_name(self, index): def get_indexed_name(self, index: int) -> str:
return self.kwargs.get(f'condition_{index}')['name'] """get name for a specified index
"""
condition_index = self.kwargs.get(f'condition_{index}')
if condition_index is not None and not isinstance(condition_index, dict):
raise ValueError(_(f'unexpected condition_{index} must have "todict" argument'))
return condition_index['name']
def has_condition_kwargs(self):
for condition in self.kwargs:
if condition.startswith('condition_'):
return True
return False
def build_arg(self, name, value): def build_property_message(self,
#if isinstance(option, tuple): name: str,
# if not reverse: value: Any,
# msg = _('the calculated value is {0}').format(display_value) ) -> str:
# else: """prepare message to display error message if needed
# msg = _('the calculated value is not {0}').format(display_value) """
#else:
if not self.reverse_condition: if not self.reverse_condition:
msg = _('the value of "{0}" is {1}').format(name, value) msg = _('the value of "{0}" is {1}').format(name, value)
else: else:
@ -519,9 +563,6 @@ class CalcValuePropertyHelp(CalcValue):
def get_args(self): def get_args(self):
args = super().get_args() args = super().get_args()
if args:
if len(self.args) != 1:
raise ValueError(_('only one property is allowed for a calculation'))
action = args[0] action = args[0]
calculated_expected = self.value_from_kwargs(self.expected, calculated_expected = self.value_from_kwargs(self.expected,
'expected_', 'expected_',
@ -538,21 +579,19 @@ class CalcValuePropertyHelp(CalcValue):
display_value = display_list([str(val) for val in calc_values], display_value = display_list([str(val) for val in calc_values],
'or', 'or',
add_quote=True) add_quote=True)
msg = self.build_arg(name, display_value) msg = self.build_property_message(name, display_value)
elif self.has_condition_kwargs(): else:
msgs = [] msgs = []
for key, value in calculated_expected.items(): for key, value in calculated_expected.items():
name = self.get_indexed_name(key) name = self.get_indexed_name(key)
msgs.append(self.build_arg(name, f'"{value}"')) msgs.append(self.build_property_message(name, f'"{value}"'))
msg = display_list(msgs, self.condition_operator.lower()) msg = display_list(msgs, self.condition_operator.lower())
else:
return [(action, f'"{action}"')]
return [(action, f'"{action}" ({msg})')] return [(action, f'"{action}" ({msg})')]
return
## calc_properties.setdefault(action, []).append(msg)
calc_value = CalcValue() calc_value = CalcValue()
calc_value.__name__ = 'calc_value' calc_value.__name__ = 'calc_value' # pylint: disable=attribute-defined-outside-init
# function_waiting_for_dict(calc_value)
calc_value_property_help = CalcValuePropertyHelp() calc_value_property_help = CalcValuePropertyHelp()
calc_value_property_help.__name__ = 'calc_value_property_help' calc_value_property_help.__name__ = 'calc_value_property_help' # pylint: disable=attribute-defined-outside-init
function_waiting_for_dict(calc_value_property_help)

View file

@ -37,10 +37,10 @@ def get_translation() -> str:
app_name = __name__[:-5] app_name = __name__[:-5]
translations_path = resource_filename(app_name, 'locale') translations_path = resource_filename(app_name, 'locale')
if 'TIRAMISU_LOCALE' in environ: if 'TIRAMISU_LOCALE' in environ: # pragma: no cover
user_locale = environ['TIRAMISU_LOCALE'] user_locale = environ['TIRAMISU_LOCALE']
else: else:
if 'Windows' in system(): if 'Windows' in system(): # pragma: no cover
import ctypes import ctypes
from locale import windows_locale from locale import windows_locale
default_locale = windows_locale[ctypes.windll.kernel32.GetUserDefaultUILanguage()] default_locale = windows_locale[ctypes.windll.kernel32.GetUserDefaultUILanguage()]
@ -52,9 +52,9 @@ def get_translation() -> str:
user_locale = default_locale[0][:2] user_locale = default_locale[0][:2]
else: else:
user_locale = DEFAULT user_locale = DEFAULT
elif default_locale: elif default_locale: # pragma: no cover
user_locale = default_locale[:2] user_locale = default_locale[:2]
else: else: # pragma: no cover
user_locale = DEFAULT user_locale = DEFAULT
try: try:
trans = translation(domain=app_name, trans = translation(domain=app_name,
@ -62,7 +62,7 @@ def get_translation() -> str:
languages=[user_locale], languages=[user_locale],
) )
# codeset='UTF-8') # codeset='UTF-8')
except FileNotFoundError: except FileNotFoundError: # pragma: no cover
log.debug('cannot found translation file for langage {} in localedir {}'.format(user_locale, log.debug('cannot found translation file for langage {} in localedir {}'.format(user_locale,
translations_path)) translations_path))
trans = NullTranslations() trans = NullTranslations()

View file

@ -277,7 +277,7 @@ msgstr "ne peut accéder à {0} \"{1}\" parce que \"{2}\" a {3} {4}"
#: tiramisu/error.py:116 #: tiramisu/error.py:116
msgid "cannot access to {0} \"{1}\" because has {2} {3}" msgid "cannot access to {0} \"{1}\" because has {2} {3}"
msgstr "ne peut accéder à l'{0} \"{1}\" a cause {2} {3}" msgstr "ne peut accéder à l'{0} \"{1}\" à cause {2} {3}"
#: tiramisu/error.py:192 #: tiramisu/error.py:192
msgid "invalid value" msgid "invalid value"
@ -551,7 +551,7 @@ msgstr "ne doit pas être une IP"
#: tiramisu/option/domainnameoption.py:139 #: tiramisu/option/domainnameoption.py:139
msgid "must have dot" msgid "must have dot"
msgstr "doit avec un point" msgstr "doit avoir un point"
#: tiramisu/option/domainnameoption.py:141 #: tiramisu/option/domainnameoption.py:141
msgid "invalid length (max 255)" msgid "invalid length (max 255)"

File diff suppressed because it is too large Load diff

View file

@ -15,12 +15,12 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________ # ____________________________________________________________
from logging import getLogger, DEBUG, basicConfig, StreamHandler, Formatter from logging import getLogger, DEBUG, StreamHandler, Formatter
import os import os
log = getLogger('tiramisu') log = getLogger('tiramisu')
if os.environ.get('TIRAMISU_DEBUG') == 'True': if os.environ.get('TIRAMISU_DEBUG') == 'True': # pragma: no cover
log.setLevel(DEBUG) log.setLevel(DEBUG)
handler = StreamHandler() handler = StreamHandler()
handler.setLevel(DEBUG) handler.setLevel(DEBUG)

View file

@ -1,3 +1,25 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2023 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# The original `Config` design model is unproudly borrowed from
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence
# ____________________________________________________________
"""all official option
"""
from .optiondescription import OptionDescription from .optiondescription import OptionDescription
from .dynoptiondescription import DynOptionDescription from .dynoptiondescription import DynOptionDescription
from .syndynoptiondescription import SynDynOptionDescription, SynDynLeadership from .syndynoptiondescription import SynDynOptionDescription, SynDynLeadership

View file

@ -18,18 +18,16 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from types import FunctionType """base option
from typing import FrozenSet, Callable, Tuple, Set, Optional, Union, Any, List """
from typing import FrozenSet, Set, Any, List
import weakref import weakref
from inspect import signature
from itertools import chain from itertools import chain
from ..i18n import _ from ..i18n import _
from ..setting import undefined, Settings from ..setting import undefined
from ..value import Values from ..autolib import Calculation, ParamOption
from ..error import ConfigError, display_list
from ..autolib import Calculation, Params, ParamOption
STATIC_TUPLE = frozenset() STATIC_TUPLE = frozenset()
@ -38,6 +36,8 @@ submulti = 2
def valid_name(name): def valid_name(name):
"""valid option name
"""
if not isinstance(name, str): if not isinstance(name, str):
return False return False
# if '.' in name: # if '.' in name:
@ -53,7 +53,7 @@ class Base:
__slots__ = ('_name', __slots__ = ('_name',
'_path', '_path',
'_informations', '_informations',
'_subdyn', '_subdyns',
'_properties', '_properties',
'_has_dependency', '_has_dependency',
'_dependencies', '_dependencies',
@ -73,7 +73,8 @@ class Base:
elif isinstance(properties, tuple): elif isinstance(properties, tuple):
properties = frozenset(properties) properties = frozenset(properties)
if is_multi: if is_multi:
# if option is a multi, it cannot be 'empty' (None not allowed in the list) and cannot have multiple time the same value # if option is a multi, it cannot be 'empty' (None not allowed in the list)
# and cannot have multiple time the same value
# 'empty' and 'unique' are removed for follower's option # 'empty' and 'unique' are removed for follower's option
if 'notunique' not in properties: if 'notunique' not in properties:
properties = properties | {'unique'} properties = properties | {'unique'}
@ -85,7 +86,8 @@ class Base:
for prop in properties: for prop in properties:
if not isinstance(prop, str): if not isinstance(prop, str):
if not isinstance(prop, Calculation): if not isinstance(prop, Calculation):
raise ValueError(_('invalid property type {0} for {1}, must be a string or a Calculation').format(type(prop), name)) raise ValueError(_('invalid property type {0} for {1}, must be a string or a '
'Calculation').format(type(prop), name))
for param in chain(prop.params.args, prop.params.kwargs.values()): for param in chain(prop.params.args, prop.params.kwargs.values()):
if isinstance(param, ParamOption): if isinstance(param, ParamOption):
param.option._add_dependency(self) param.option._add_dependency(self)
@ -96,18 +98,21 @@ class Base:
_setattr(self, '_properties', properties) _setattr(self, '_properties', properties)
def impl_has_dependency(self, def impl_has_dependency(self,
self_is_dep: bool=True) -> bool: self_is_dep: bool=True,
) -> bool:
"""this has dependency
"""
if self_is_dep is True: if self_is_dep is True:
return getattr(self, '_has_dependency', False) return getattr(self, '_has_dependency', False)
return hasattr(self, '_dependencies') return hasattr(self, '_dependencies')
def _get_dependencies(self, def get_dependencies(self,
context_od, context_od,
) -> Set[str]: ) -> Set[str]:
ret = set(getattr(self, '_dependencies', STATIC_TUPLE)) ret = set(getattr(self, '_dependencies', STATIC_TUPLE))
if context_od and hasattr(context_od, '_dependencies'): if context_od and hasattr(context_od, '_dependencies'):
# add options that have context is set in calculation # add options that have context is set in calculation
return set(context_od._dependencies) | ret return set(context_od._dependencies) | ret # pylint: disable=protected-access
return ret return ret
def _get_suffixes_dependencies(self) -> Set[str]: def _get_suffixes_dependencies(self) -> Set[str]:
@ -118,50 +123,36 @@ class Base:
is_suffix: bool=False, is_suffix: bool=False,
) -> None: ) -> None:
woption = weakref.ref(option) woption = weakref.ref(option)
options = self._get_dependencies(None) options = self.get_dependencies(None)
options.add(weakref.ref(option)) options.add(woption)
self._dependencies = tuple(options) self._dependencies = tuple(options) # pylint: disable=attribute-defined-outside-init
if is_suffix: if is_suffix:
options = list(self._get_suffixes_dependencies()) options = list(self._get_suffixes_dependencies())
options.append(weakref.ref(option)) options.append(woption)
self._suffixes_dependencies = tuple(options) self._suffixes_dependencies = tuple(options) # pylint: disable=attribute-defined-outside-init
def _impl_set_callback(self,
callback: Callable,
callback_params: Optional[Params]=None) -> None:
if __debug__:
if callback is None and callback_params is not None:
raise ValueError(_("params defined for a callback function but "
"no callback defined"
' yet for option "{0}"').format(
self.impl_getname()))
self._validate_calculator(callback,
callback_params)
if callback is not None:
callback_params = self._build_calculator_params(callback,
callback_params,
'callback')
# first part is validator
val = getattr(self, '_val_call', (None,))[0]
if not callback_params:
val_call = (callback,)
else:
val_call = (callback, callback_params)
self._val_call = (val, val_call)
def impl_is_optiondescription(self) -> bool: def impl_is_optiondescription(self) -> bool:
"""option is an option description
"""
return False return False
def impl_is_dynoptiondescription(self) -> bool: def impl_is_dynoptiondescription(self) -> bool:
"""option is not a dyn option description
"""
return False
def impl_is_sub_dyn_optiondescription(self):
return False return False
def impl_getname(self) -> str: def impl_getname(self) -> str:
return self._name """get name
"""
return self._name # pylint: disable=no-member
def _set_readonly(self) -> None: def _set_readonly(self) -> None:
if isinstance(self._informations, dict): if isinstance(self._informations, dict): # pylint: disable=no-member
_setattr = object.__setattr__ _setattr = object.__setattr__
dico = self._informations dico = self._informations # pylint: disable=no-member
keys = tuple(dico.keys()) keys = tuple(dico.keys())
if len(keys) == 1: if len(keys) == 1:
dico = dico['doc'] dico = dico['doc']
@ -173,31 +164,36 @@ class Base:
_setattr(self, '_extra', tuple([tuple(extra.keys()), tuple(extra.values())])) _setattr(self, '_extra', tuple([tuple(extra.keys()), tuple(extra.values())]))
def impl_is_readonly(self) -> str: def impl_is_readonly(self) -> str:
"""the option is readonly
"""
# _path is None when initialise SymLinkOption # _path is None when initialise SymLinkOption
return hasattr(self, '_path') and self._path is not None return hasattr(self, '_path') and self._path is not None # pylint: disable=no-member
def impl_getproperties(self) -> FrozenSet[str]: def impl_getproperties(self) -> FrozenSet[str]:
"""get properties
"""
return getattr(self, '_properties', frozenset()) return getattr(self, '_properties', frozenset())
def _setsubdyn(self, def _setsubdyn(self,
subdyn) -> None: subdyn,
self._subdyn = weakref.ref(subdyn) ) -> None:
# pylint: disable=attribute-defined-outside-init
if getattr(self, '_subdyns', None) is None:
self._subdyns = []
self._subdyns.append(subdyn)
def issubdyn(self) -> bool: def issubdyn(self) -> bool:
return getattr(self, '_subdyn', None) is not None """is sub dynoption
"""
return getattr(self, '_subdyns', None) is not None
def getsubdyn(self): def getsubdyn(self):
return self._subdyn() """get sub dynoption
"""
return self._subdyns[0]()
def impl_get_callback(self): def get_sub_dyns(self):
call = getattr(self, '_val_call', (None, None))[1] return self._subdyns
if call is None:
ret_call = (None, None)
elif len(call) == 1:
ret_call = (call[0], None)
else:
ret_call = call
return ret_call
# ____________________________________________________________ # ____________________________________________________________
# information # information
@ -209,7 +205,7 @@ class Base:
:param key: the item string (ex: "help") :param key: the item string (ex: "help")
""" """
dico = self._informations dico = self._informations # pylint: disable=no-member
if isinstance(dico, tuple): if isinstance(dico, tuple):
if key in dico[0]: if key in dico[0]:
return dico[1][dico[0].index(key)] return dico[1][dico[0].index(key)]
@ -221,7 +217,9 @@ class Base:
return dico[key] return dico[key]
if default is not undefined: if default is not undefined:
return default return default
raise ValueError(_(f'information\'s item for "{self.impl_get_display_name()}" not found: "{key}"')) # pylint: disable=no-member
raise ValueError(_(f'information\'s item for "{self.impl_get_display_name()}" '
f'not found: "{key}"'))
def impl_set_information(self, def impl_set_information(self,
key: str, key: str,
@ -238,13 +236,15 @@ class Base:
" read-only").format(self.__class__.__name__, " read-only").format(self.__class__.__name__,
self, self,
key)) key))
self._informations[key] = value self._informations[key] = value # pylint: disable=no-member
def impl_list_information(self) -> Any: def impl_list_information(self) -> Any:
dico = self._informations """get the list of information keys
"""
dico = self._informations # pylint: disable=no-member
if isinstance(dico, tuple): if isinstance(dico, tuple):
return list(dico[0]) return list(dico[0])
elif isinstance(dico, str): if isinstance(dico, str):
return ['doc'] return ['doc']
# it's a dict # it's a dict
return list(dico.keys()) return list(dico.keys())
@ -257,12 +257,10 @@ class BaseOption(Base):
""" """
__slots__ = ('_display_name_function',) __slots__ = ('_display_name_function',)
def __getstate__(self):
raise NotImplementedError()
def __setattr__(self, def __setattr__(self,
name: str, name: str,
value: Any) -> Any: value: Any,
) -> Any:
"""set once and only once some attributes in the option, """set once and only once some attributes in the option,
like `_name`. `_name` cannot be changed once the option is like `_name`. `_name` cannot be changed once the option is
pushed in the :class:`tiramisu.option.OptionDescription`. pushed in the :class:`tiramisu.option.OptionDescription`.
@ -277,68 +275,50 @@ class BaseOption(Base):
' read-only').format(self.__class__.__name__, ' read-only').format(self.__class__.__name__,
self.impl_get_display_name(), self.impl_get_display_name(),
name)) name))
super(BaseOption, self).__setattr__(name, value) super().__setattr__(name, value)
def impl_getpath(self) -> str: def impl_getpath(self) -> str:
"""get the path of the option
"""
try: try:
return self._path return self._path
except AttributeError: except AttributeError as err:
raise AttributeError(_('"{}" not part of any Config').format(self.impl_get_display_name())) raise AttributeError(_(f'"{self.impl_get_display_name()}" not part of any Config')) \
from err
def impl_has_callback(self) -> bool: def impl_get_display_name(self,
"to know if a callback has been defined or not" dynopt=None,
return self.impl_get_callback()[0] is not None
def _impl_get_display_name(self,
dyn_name: Base=None,
suffix: str=None,
) -> str: ) -> str:
"""get display name
"""
if dynopt is None:
dynopt = self
if hasattr(self, '_display_name_function'):
return self._display_name_function(dynopt)
name = self.impl_get_information('doc', None) name = self.impl_get_information('doc', None)
if name is None or name == '': if name is None or name == '':
if dyn_name is not None: name = dynopt.impl_getname()
name = dyn_name
else:
name = self.impl_getname()
elif suffix:
name += suffix
return name return name
def _get_display_name(self,
dyn_name,
suffix,
):
if hasattr(self, '_display_name_function'):
return self._display_name_function(self,
dyn_name,
suffix,
)
return self._impl_get_display_name(dyn_name,
suffix,
)
def impl_get_display_name(self) -> str:
return self._get_display_name(None,
None,
)
def reset_cache(self, def reset_cache(self,
path: str, path: str,
config_bag: 'OptionBag', config_bag: 'OptionBag',
resetted_opts: List[Base]) -> None: resetted_opts: List[Base], # pylint: disable=unused-argument
) -> None:
"""reset cache
"""
context = config_bag.context context = config_bag.context
context._impl_properties_cache.delcache(path) context.properties_cache.delcache(path)
context._impl_permissives_cache.delcache(path) context._impl_permissives_cache.delcache(path) # pylint: disable=protected-access
if not self.impl_is_optiondescription(): if not self.impl_is_optiondescription():
context._impl_values_cache.delcache(path) context.get_values_cache().delcache(path) # pylint: disable=protected-access
def impl_is_symlinkoption(self) -> bool: def impl_is_symlinkoption(self) -> bool:
"""the option is not a symlinkoption
"""
return False return False
def get_dependencies_information(self, def get_dependencies_information(self) -> List[str]:
itself=False, """get dependencies information
) -> List[str]: """
if itself: return getattr(self, '_dependencies_information', {})
idx = 1
else:
idx = 0
return getattr(self, '_dependencies_information', [[], []])[idx]

View file

@ -18,19 +18,23 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""BoolOption
"""
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
class BoolOption(Option): class BoolOption(Option):
"represents a choice between ``True`` and ``False``" """represents a choice between ``True`` and ``False``
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'boolean' _type = _('boolean')
_display_name = _('boolean')
def validate(self, def validate(self,
value: bool) -> None: value: bool,
) -> None:
"""validate value
"""
if not isinstance(value, bool): if not isinstance(value, bool):
raise ValueError() raise ValueError()

View file

@ -18,21 +18,25 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_address, ip_network """BroadcastOption
"""
from ipaddress import ip_address
from ..error import ConfigError
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
class BroadcastOption(Option): class BroadcastOption(Option):
"""represents the choice of a broadcast
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'broadcast_address' _type = _('broadcast address')
_display_name = _('broadcast address')
def validate(self, def validate(self,
value: str) -> None: value: str,
) -> None:
"""validate
"""
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
if value.count('.') != 3: if value.count('.') != 3:
@ -42,5 +46,5 @@ class BroadcastOption(Option):
raise ValueError() raise ValueError()
try: try:
ip_address(value) ip_address(value)
except ValueError: except ValueError as err:
raise ValueError() raise ValueError() from err

View file

@ -18,6 +18,8 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""ChoiceOption
"""
from typing import Any from typing import Any
from ..setting import undefined, OptionBag from ..setting import undefined, OptionBag
@ -33,8 +35,7 @@ class ChoiceOption(Option):
The option can also have the value ``None`` The option can also have the value ``None``
""" """
__slots__ = tuple() __slots__ = tuple()
_type = 'choice' _type = _('choice')
_display_name = _('choice')
def __init__(self, def __init__(self,
name, name,
@ -55,10 +56,13 @@ class ChoiceOption(Option):
*args, *args,
**kwargs) **kwargs)
async def impl_get_values(self, def impl_get_values(self,
option_bag): option_bag: OptionBag,
):
"""get values allowed by option
"""
if isinstance(self._choice_values, Calculation): if isinstance(self._choice_values, Calculation):
values = await self._choice_values.execute(option_bag) values = self._choice_values.execute(option_bag)
if values is not undefined and not isinstance(values, list): if values is not undefined and not isinstance(values, list):
raise ConfigError(_('the calculated values "{0}" for "{1}" is not a list' raise ConfigError(_('the calculated values "{0}" for "{1}" is not a list'
'').format(values, self.impl_getname())) '').format(values, self.impl_getname()))
@ -67,27 +71,27 @@ class ChoiceOption(Option):
return values return values
def validate(self, def validate(self,
value: Any) -> None:
pass
def sync_validate_with_option(self,
value: Any, value: Any,
option_bag: OptionBag) -> None: ) -> None:
if isinstance(self._choice_values, Calculation): """nothing to valide
"""
def validate_with_option(self,
value: Any,
option_bag: OptionBag,
loaded: bool,
) -> None:
if loaded and isinstance(self._choice_values, Calculation):
return return
values = self._choice_values values = self.impl_get_values(option_bag)
self.validate_values(value, values)
async def validate_with_option(self,
value: Any,
option_bag: OptionBag) -> None:
values = await self.impl_get_values(option_bag)
self.validate_values(value, values) self.validate_values(value, values)
def validate_values(self, def validate_values(self,
value, value,
values, values,
) -> None: ) -> None:
"""validate values
"""
if values is not undefined and value not in values: if values is not undefined and value not in values:
if len(values) == 1: if len(values) == 1:
raise ValueError(_('only "{0}" is allowed' raise ValueError(_('only "{0}" is allowed'

View file

@ -18,22 +18,24 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""DateOption
"""
from datetime import datetime from datetime import datetime
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .stroption import StrOption from .stroption import StrOption
class DateOption(StrOption): class DateOption(StrOption):
"""represents the choice of a date
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'date' _type = _('date')
_display_name = _('date')
def validate(self, def validate(self,
value: str) -> None: value: str) -> None:
super().validate(value) super().validate(value)
try: try:
datetime.strptime(value, "%Y-%m-%d") datetime.strptime(value, "%Y-%m-%d")
except ValueError: except ValueError as err:
raise ValueError() raise ValueError() from err

View file

@ -18,6 +18,8 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""DomainnameOption
"""
import re import re
from ipaddress import ip_interface from ipaddress import ip_interface
from typing import Any, Optional, List from typing import Any, Optional, List
@ -38,8 +40,7 @@ class DomainnameOption(StrOption):
fqdn: with tld, not supported yet fqdn: with tld, not supported yet
""" """
__slots__ = tuple() __slots__ = tuple()
_type = 'domainname' _type = _('domain name')
_display_name = _('domain name')
def __init__(self, def __init__(self,
name: str, name: str,
@ -54,8 +55,9 @@ class DomainnameOption(StrOption):
allow_cidr_network: bool=False, allow_cidr_network: bool=False,
type: str='domainname', type: str='domainname',
allow_without_dot: bool=False, allow_without_dot: bool=False,
allow_startswith_dot: bool=False) -> None: allow_startswith_dot: bool=False,
) -> None:
# pylint: disable=too-many-branches,too-many-locals,too-many-arguments
if type not in ['netbios', 'hostname', 'domainname']: if type not in ['netbios', 'hostname', 'domainname']:
raise ValueError(_('unknown type {0} for hostname').format(type)) raise ValueError(_('unknown type {0} for hostname').format(type))
extra = {'_dom_type': type} extra = {'_dom_type': type}
@ -111,10 +113,9 @@ class DomainnameOption(StrOption):
warnings_only=warnings_only, warnings_only=warnings_only,
extra=extra) extra=extra)
def _get_len(self, type): def _get_len(self, type_):
if type == 'netbios': if type_ == 'netbios':
return 15 return 15
else:
return 63 return 63
def _validate_domain(self, def _validate_domain(self,
@ -196,14 +197,11 @@ class DomainnameOption(StrOption):
allow_ip = self.impl_get_extra('_allow_ip') allow_ip = self.impl_get_extra('_allow_ip')
allow_cidr_network = self.impl_get_extra('_allow_cidr_network') allow_cidr_network = self.impl_get_extra('_allow_cidr_network')
# it's an IP so validate with IPOption # it's an IP so validate with IPOption
if allow_ip is False and allow_cidr_network is False: if allow_ip is True and allow_cidr_network is False:
raise ValueError(_('must not be an IP'))
if allow_ip is True:
try: try:
self.impl_get_extra('_ip').second_level_validation(value, warnings_only) self.impl_get_extra('_ip').second_level_validation(value, warnings_only)
return return
except ValueError as err: except ValueError as err:
if allow_cidr_network is False:
raise err raise err
if allow_cidr_network is True: if allow_cidr_network is True:
self.impl_get_extra('_network').second_level_validation(value, warnings_only) self.impl_get_extra('_network').second_level_validation(value, warnings_only)

View file

@ -18,16 +18,20 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""DynOptionDescription
"""
import re import re
from typing import List, Callable, Any import weakref
from typing import List, Any, Optional, Tuple
from itertools import chain from itertools import chain
from ..autolib import ParamOption from ..autolib import ParamOption
from ..i18n import _ from ..i18n import _
from .optiondescription import OptionDescription from .optiondescription import OptionDescription
from .syndynoptiondescription import SynDynLeadership
from .baseoption import BaseOption from .baseoption import BaseOption
from ..setting import OptionBag, ConfigBag, groups, undefined from ..setting import OptionBag, ConfigBag, undefined
from ..error import ConfigError from ..error import ConfigError
from ..autolib import Calculation from ..autolib import Calculation
@ -36,31 +40,29 @@ NAME_REGEXP = re.compile(r'^[a-zA-Z\d\-_]*$')
class DynOptionDescription(OptionDescription): class DynOptionDescription(OptionDescription):
__slots__ = ('_suffixes',) """dyn option description
"""
__slots__ = ('_suffixes',
'_subdyns',
)
def __init__(self, def __init__(self,
name: str, name: str,
doc: str, doc: str,
children: List[BaseOption], children: List[BaseOption],
suffixes: Calculation, suffixes: Calculation,
properties=None) -> None: properties=None,
) -> None:
# pylint: disable=too-many-arguments
super().__init__(name, super().__init__(name,
doc, doc,
children, children,
properties) properties,
)
# check children + set relation to this dynoptiondescription # check children + set relation to this dynoptiondescription
wself = weakref.ref(self)
for child in children: for child in children:
if isinstance(child, OptionDescription): child._setsubdyn(wself)
if __debug__ and child.impl_get_group_type() != groups.leadership:
raise ConfigError(_('cannot set optiondescription in a '
'dynoptiondescription'))
for chld in child._children[1]:
chld._setsubdyn(self)
if __debug__ and child.impl_is_symlinkoption():
raise ConfigError(_('cannot set symlinkoption in a '
'dynoptiondescription'))
child._setsubdyn(self)
# add suffixes # add suffixes
if __debug__ and not isinstance(suffixes, Calculation): if __debug__ and not isinstance(suffixes, Calculation):
raise ConfigError(_('suffixes in dynoptiondescription has to be a calculation')) raise ConfigError(_('suffixes in dynoptiondescription has to be a calculation'))
@ -74,6 +76,8 @@ class DynOptionDescription(OptionDescription):
def convert_suffix_to_path(self, def convert_suffix_to_path(self,
suffix: Any, suffix: Any,
) -> str: ) -> str:
"""convert suffix to use it to a path
"""
if suffix is None: if suffix is None:
return None return None
if not isinstance(suffix, str): if not isinstance(suffix, str):
@ -82,20 +86,30 @@ class DynOptionDescription(OptionDescription):
suffix = suffix.replace('.', '_') suffix = suffix.replace('.', '_')
return suffix return suffix
async def get_suffixes(self, def get_suffixes(self,
config_bag: ConfigBag) -> List[str]: config_bag: ConfigBag,
option_bag = OptionBag() dynoption=None,
option_bag.set_option(self, ) -> List[str]:
"""get dynamic suffixes
"""
if dynoption:
self_opt = dynoption
else:
self_opt = self
option_bag = OptionBag(self_opt,
None, None,
config_bag) config_bag,
values = await self._suffixes.execute(option_bag) properties=None,
)
values = self._suffixes.execute(option_bag)
if values is None: if values is None:
values = [] values = []
values_ = [] values_ = []
if __debug__: if __debug__:
if not isinstance(values, list): if not isinstance(values, list):
raise ValueError(_('DynOptionDescription suffixes for option "{}", is not a list ({})' raise ValueError(_('DynOptionDescription suffixes for '
'').format(self.impl_get_display_name(), values)) f'option "{self.impl_get_display_name()}", is not '
f'a list ({values})'))
for val in values: for val in values:
cval = self.convert_suffix_to_path(val) cval = self.convert_suffix_to_path(val)
if not isinstance(cval, str) or re.match(NAME_REGEXP, cval) is None: if not isinstance(cval, str) or re.match(NAME_REGEXP, cval) is None:
@ -105,14 +119,83 @@ class DynOptionDescription(OptionDescription):
self.impl_get_display_name())) self.impl_get_display_name()))
else: else:
values_.append(val) values_.append(val)
if __debug__: if __debug__ and len(values_) > len(set(values_)):
if len(values_) > len(set(values_)): raise ValueError(_(f'DynOptionDescription "{self._name}" suffixes return a list with '
extra_values = values_.copy() f'same values "{values_}"'''))
for val in set(values_):
extra_values.remove(val)
raise ValueError(_('DynOptionDescription suffixes return a list with multiple value '
'"{}"''').format(extra_values))
return values_ return values_
def impl_is_dynoptiondescription(self) -> bool: def impl_is_dynoptiondescription(self) -> bool:
return True return True
def option_is_self(self,
option,
) -> bool:
return option == self or \
(option.impl_is_sub_dyn_optiondescription() and option.opt == self)
def split_path(self,
dynoption,
option,
) -> Tuple[str, str]:
"""self.impl_getpath() is something like root.xxx.dynoption_path
option.impl_getpath() is something like root.xxx.dynoption_path.sub.path
must return ('root.xxx.', '.sub')
"""
if dynoption is None:
self_path = self.impl_getpath()
else:
self_path = dynoption.impl_getpath()
root_path = self_path.rsplit('.', 1)[0] if '.' in self_path else None
#
if self.option_is_self(option):
sub_path = ''
else:
option_path = option.impl_getpath()
if root_path:
if isinstance(option, SynDynLeadership):
count_root_path = option_path.count('.') - root_path.count('.')
root_path = option_path.rsplit('.', count_root_path)[0]
root_path += '.'
self_number_child = self_path.count('.') + 1
option_sub_path = option_path.split('.', self_number_child)[-1]
sub_path = '.' + option_sub_path.rsplit('.', 1)[0] if '.' in option_sub_path else ''
return root_path, sub_path
def get_sub_children(self,
option,
config_bag,
*,
index=None,
properties=undefined,
dynoption=None,
):
root_path, sub_path = self.split_path(dynoption,
option,
)
for suffix in self.get_suffixes(config_bag,
dynoption=dynoption,
):
if self.option_is_self(option):
parent_path = root_path
elif root_path:
parent_path = root_path + self.impl_getname(suffix) + sub_path
else:
parent_path = self.impl_getname(suffix) + sub_path
yield OptionBag(option.to_dynoption(parent_path,
suffix,
self,
),
index,
config_bag,
properties=properties,
ori_option=option
)
def impl_getname(self, suffix=None) -> str:
"""get name
"""
name = super().impl_getname()
if suffix is None:
return name
path_suffix = self.convert_suffix_to_path(suffix)
return name + path_suffix

View file

@ -18,6 +18,8 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""EmailOption
"""
import re import re
from ..i18n import _ from ..i18n import _
@ -25,7 +27,8 @@ from .stroption import RegexpOption
class EmailOption(RegexpOption): class EmailOption(RegexpOption):
"""represents a choice of an email
"""
__slots__ = tuple() __slots__ = tuple()
_regexp = re.compile(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$") _regexp = re.compile(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
_type = 'email' _type = _('email address')
_display_name = _('email address')

View file

@ -18,16 +18,17 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
import re """FilenameOption
"""
from ..i18n import _ from ..i18n import _
from .stroption import StrOption from .stroption import StrOption
class FilenameOption(StrOption): class FilenameOption(StrOption):
"""represents a choice of a file name
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'filename' _type = _('file name')
_display_name = _('file name')
def validate(self, def validate(self,
value: str, value: str,

View file

@ -18,17 +18,18 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""FloatOption
"""
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
class FloatOption(Option): class FloatOption(Option):
"represents a choice of a floating point number" """represents a choice of a floating point number
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'float' _type = _('float')
_display_name = _('float')
def validate(self, def validate(self,
value: float) -> None: value: float) -> None:

View file

@ -18,8 +18,9 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""IntOption
"""
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -27,8 +28,7 @@ from .option import Option
class IntOption(Option): class IntOption(Option):
"represents a choice of an integer" "represents a choice of an integer"
__slots__ = tuple() __slots__ = tuple()
_type = 'integer' _type = _('integer')
_display_name = _('integer')
def __init__(self, def __init__(self,
*args, *args,
@ -43,7 +43,8 @@ class IntOption(Option):
super().__init__(*args, extra=extra, **kwargs) super().__init__(*args, extra=extra, **kwargs)
def validate(self, def validate(self,
value: int) -> None: value: int,
) -> None:
if not isinstance(value, int): if not isinstance(value, int):
raise ValueError() raise ValueError()

View file

@ -18,21 +18,19 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""IPOption
"""
from ipaddress import ip_address, ip_interface from ipaddress import ip_address, ip_interface
from ..error import ConfigError
from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option
from .stroption import StrOption from .stroption import StrOption
from ..function import valid_ip_netmask
class IPOption(StrOption): class IPOption(StrOption):
"represents the choice of an ip" """represents the choice of an ip
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'ip' _type = _('IP')
_display_name = _('IP')
def __init__(self, def __init__(self,
*args, *args,
@ -52,21 +50,19 @@ class IPOption(StrOption):
def _validate_cidr(self, value): def _validate_cidr(self, value):
try: try:
ip = ip_interface(value) ip_obj = ip_interface(value)
except ValueError: except ValueError as err:
raise ValueError() raise ValueError() from err
if ip.ip == ip.network.network_address: if ip_obj.ip == ip_obj.network.network_address:
raise ValueError(_("it's in fact a network address")) raise ValueError(_("it's in fact a network address"))
elif ip.ip == ip.network.broadcast_address: if ip_obj.ip == ip_obj.network.broadcast_address:
raise ValueError(_("it's in fact a broacast address")) raise ValueError(_("it's in fact a broacast address"))
def _validate_ip(self, value): def _validate_ip(self, value):
try: try:
new_value = str(ip_address(value)) str(ip_address(value))
if value != new_value: except ValueError as err:
raise ValueError(_(f'should be {new_value}')) raise ValueError() from err
except ValueError:
raise ValueError()
def validate(self, def validate(self,
value: str) -> None: value: str) -> None:
@ -81,14 +77,14 @@ class IPOption(StrOption):
def second_level_validation(self, def second_level_validation(self,
value: str, value: str,
warnings_only: bool) -> None: warnings_only: bool) -> None:
ip = ip_interface(value) ip_obj = ip_interface(value)
if not self.impl_get_extra('_allow_reserved') and ip.is_reserved: if not self.impl_get_extra('_allow_reserved') and ip_obj.is_reserved:
if warnings_only: if warnings_only:
msg = _("shouldn't be reserved IP") msg = _("shouldn't be reserved IP")
else: else:
msg = _("mustn't be reserved IP") msg = _("mustn't be reserved IP")
raise ValueError(msg) raise ValueError(msg)
if self.impl_get_extra('_private_only') and not ip.is_private: if self.impl_get_extra('_private_only') and not ip_obj.is_private:
if warnings_only: if warnings_only:
msg = _("should be private IP") msg = _("should be private IP")
else: else:

View file

@ -20,24 +20,26 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
import weakref import weakref
from itertools import chain from typing import List, Iterator, Optional
from typing import List, Iterator, Optional, Any
from ..i18n import _ from ..i18n import _
from ..setting import groups, undefined, OptionBag, Settings, ALLOWED_LEADER_PROPERTIES from ..setting import groups, undefined, OptionBag, ALLOWED_LEADER_PROPERTIES
from ..value import Values
from .optiondescription import OptionDescription from .optiondescription import OptionDescription
from .syndynoptiondescription import SynDynLeadership from .syndynoptiondescription import SynDynLeadership
from .baseoption import BaseOption from .baseoption import BaseOption
from .option import Option from .option import Option
from ..error import LeadershipError from ..error import LeadershipError
from ..autolib import Calculation, ParamOption from ..autolib import Calculation
class Leadership(OptionDescription): class Leadership(OptionDescription):
"""Leadership
"""
# pylint: disable=too-many-arguments
__slots__ = ('leader', __slots__ = ('leader',
'followers') 'followers',
)
def __init__(self, def __init__(self,
name: str, name: str,
@ -56,6 +58,21 @@ class Leadership(OptionDescription):
leader = children[0] leader = children[0]
for idx, child in enumerate(children): for idx, child in enumerate(children):
if __debug__: if __debug__:
self._check_child_is_valid(child)
if idx != 0:
if __debug__:
self._check_default_value(child)
# remove empty property for follower
child._properties = frozenset(child._properties - {'empty', 'unique'})
followers.append(child)
child._add_dependency(self)
child._leadership = weakref.ref(self)
if __debug__:
for prop in leader.impl_getproperties():
if prop not in ALLOWED_LEADER_PROPERTIES and not isinstance(prop, Calculation):
raise LeadershipError(_('leader cannot have "{}" property').format(prop))
def _check_child_is_valid(self, child: BaseOption):
if child.impl_is_symlinkoption(): if child.impl_is_symlinkoption():
raise ValueError(_('leadership "{0}" shall not have ' raise ValueError(_('leadership "{0}" shall not have '
"a symlinkoption").format(self.impl_get_display_name())) "a symlinkoption").format(self.impl_get_display_name()))
@ -67,171 +84,164 @@ class Leadership(OptionDescription):
'"{1}" is not a multi' '"{1}" is not a multi'
'').format(self.impl_get_display_name(), '').format(self.impl_get_display_name(),
child.impl_get_display_name())) child.impl_get_display_name()))
if idx != 0:
def _check_default_value(self, child: BaseOption):
default = child.impl_getdefault() default = child.impl_getdefault()
if default != []: if default != []:
if child.impl_is_submulti() and isinstance(default, tuple): if child.impl_is_submulti() and isinstance(default, (list, tuple)):
for val in default: for val in default:
if not isinstance(val, Calculation): if not isinstance(val, Calculation):
calculation = False calculation = False
break
else: else:
# empty default is valid # empty default is valid
calculation = True calculation = True
else: else:
calculation = isinstance(default, Calculation) calculation = isinstance(default, Calculation)
if not calculation: if not calculation:
raise ValueError(_('not allowed default value for follower option "{0}" ' raise ValueError(_('not allowed default value for follower option '
'in leadership "{1}"' f'"{child.impl_get_display_name()}" in leadership '
'').format(child.impl_get_display_name(), f'"{self.impl_get_display_name()}"'))
self.impl_get_display_name()))
if idx != 0:
# remove empty property for follower
child._properties = frozenset(child._properties - {'empty', 'unique'})
followers.append(child)
child._add_dependency(self)
child._leadership = weakref.ref(self)
if __debug__:
callback, callback_params = leader.impl_get_callback()
options = []
if callback is not None and callback_params is not None:
for callbk in chain(callback_params.args, callback_params.kwargs.values()):
if isinstance(callbk, ParamOption) and callbk.option in followers:
raise ValueError(_("callback of leader's option shall "
"not refered to a follower's ones"))
for prop in leader.impl_getproperties(): def _setsubdyn(self,
if prop not in ALLOWED_LEADER_PROPERTIES and not isinstance(prop, Calculation): subdyn,
raise LeadershipError(_('leader cannot have "{}" property').format(prop)) ) -> None:
for chld in self._children[1]:
chld._setsubdyn(subdyn)
super()._setsubdyn(subdyn)
def is_leader(self, def is_leader(self,
opt: Option) -> bool: opt: Option,
) -> bool:
"""the option is the leader
"""
leader = self.get_leader() leader = self.get_leader()
return opt == leader or (opt.impl_is_dynsymlinkoption() and opt.opt == leader) return opt == leader or (opt.impl_is_dynsymlinkoption() and opt.opt == leader)
def get_leader(self) -> Option: def get_leader(self) -> Option:
"""get leader
"""
return self._children[1][0] return self._children[1][0]
def get_followers(self) -> Iterator[Option]: def get_followers(self) -> Iterator[Option]:
"""get all followers
"""
for follower in self._children[1][1:]: for follower in self._children[1][1:]:
yield follower yield follower
def in_same_group(self, def in_same_leadership(self,
opt: Option) -> bool: opt: Option,
) -> bool:
"""check if followers are in same leadership
"""
if opt.impl_is_dynsymlinkoption(): if opt.impl_is_dynsymlinkoption():
opt = opt.opt opt = opt.opt
return opt in self._children[1] return opt in self._children[1]
async def reset(self, def reset(self, config_bag: 'ConfigBag') -> None:
values: Values, """reset follower value
option_bag: OptionBag) -> None: """
config_bag = option_bag.config_bag.copy() values = config_bag.context.get_values()
config_bag = config_bag.copy()
config_bag.remove_validation() config_bag.remove_validation()
for follower in self.get_followers(): for follower in self.get_followers():
soption_bag = OptionBag() soption_bag = OptionBag(follower,
soption_bag.set_option(follower,
None, None,
config_bag) config_bag,
soption_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(soption_bag) )
await values.reset(soption_bag) values.reset(soption_bag)
async def follower_force_store_value(self, def follower_force_store_value(self,
values,
value, value,
option_bag, config_bag: 'ConfigBag',
owner, owner,
dyn=None, dyn=None,
) -> None: ) -> None:
settings = option_bag.config_bag.context.cfgimpl_get_settings() """apply force_store_value to follower
"""
if value: if value:
if dyn is None: if dyn is None:
dyn = self dyn = self
for idx, follower in enumerate(await dyn.get_children(option_bag.config_bag)): values = config_bag.context.get_values()
foption_bag = OptionBag() for idx, follower in enumerate(dyn.get_children(config_bag)):
foption_bag.set_option(follower, if not idx:
None, # it's a master
option_bag.config_bag) apply_requires = True
if 'force_store_value' in await settings.getproperties(foption_bag):
if idx == 0:
indexes = [None] indexes = [None]
else: else:
apply_requires = False
indexes = range(len(value)) indexes = range(len(value))
foption_bag = OptionBag(follower,
None,
config_bag,
apply_requires=apply_requires,
)
if 'force_store_value' not in foption_bag.properties:
continue
for index in indexes: for index in indexes:
foption_bag = OptionBag() foption_bag_index = OptionBag(follower,
foption_bag.set_option(follower,
index, index,
option_bag.config_bag) config_bag,
foption_bag.properties = await settings.getproperties(foption_bag) )
await values._p_.setvalue(foption_bag.config_bag.connection, values.set_storage_value(foption_bag_index.path,
foption_bag.path, index,
await values.getvalue(foption_bag), values.get_value(foption_bag_index)[0],
owner, owner,
index,
) )
async def pop(self, def pop(self,
values: Values,
index: int, index: int,
option_bag: OptionBag, config_bag: 'ConfigBag',
followers: Optional[List[Option]]=undefined) -> None: followers: Optional[List[Option]]=undefined,
) -> None:
"""pop leader value and follower's one
"""
if followers is undefined: if followers is undefined:
# followers are not undefined only in SynDynLeadership # followers are not undefined only in SynDynLeadership
followers = self.get_followers() followers = self.get_followers()
config_bag = option_bag.config_bag.copy() config_bag = config_bag.copy()
config_bag.remove_validation() config_bag.remove_validation()
values = config_bag.context.get_values()
for follower in followers: for follower in followers:
follower_path = follower.impl_getpath() soption_bag = OptionBag(follower,
followerlen = await values._p_.get_max_length(config_bag.connection,
follower_path)
soption_bag = OptionBag()
soption_bag.set_option(follower,
index, index,
config_bag) config_bag,
# do not check force_default_on_freeze or force_metaconfig_on_freeze properties=set(), # do not check force_default_on_freeze
soption_bag.properties = set() # or force_metaconfig_on_freeze
is_default = await values.is_default_owner(soption_bag, )
validate_meta=False) values.reduce_index(soption_bag)
if not is_default and followerlen > index:
await values._p_.resetvalue_index(config_bag.connection,
follower_path,
index)
if followerlen > index + 1:
for idx in range(index + 1, followerlen):
if await values._p_.hasvalue(config_bag.connection,
follower_path,
idx):
await values._p_.reduce_index(config_bag.connection,
follower_path,
idx)
def reset_cache(self, def reset_cache(self,
path: str, path: str,
config_bag: 'ConfigBag', config_bag: 'ConfigBag',
resetted_opts: List[Option]) -> None: resetted_opts: List[Option],
) -> None:
self._reset_cache(path, self._reset_cache(path,
self.get_leader(), self.get_leader(),
self.get_followers(), self.get_followers(),
config_bag, config_bag,
resetted_opts) resetted_opts,
)
def _reset_cache(self, def _reset_cache(self,
path: str, path: str,
leader: Option, leader: Option,
followers: List[Option], followers: List[Option],
config_bag: 'ConfigBag', config_bag: 'ConfigBag',
resetted_opts: List[Option]) -> None: resetted_opts: List[Option],
) -> None:
super().reset_cache(path, super().reset_cache(path,
config_bag, config_bag,
resetted_opts) resetted_opts,
)
leader.reset_cache(leader.impl_getpath(), leader.reset_cache(leader.impl_getpath(),
config_bag, config_bag,
None) None)
for follower in followers: for follower in followers:
spath = follower.impl_getpath() follower.reset_cache(follower.impl_getpath(),
follower.reset_cache(spath,
config_bag, config_bag,
None) None,
# do not reset dependencies option )
# resetted_opts.append(spath)
def impl_is_leadership(self) -> None: def impl_is_leadership(self) -> None:
return True return True

View file

@ -18,6 +18,8 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
"""MACOption
"""
import re import re
from ..i18n import _ from ..i18n import _
@ -25,7 +27,8 @@ from .stroption import RegexpOption
class MACOption(RegexpOption): class MACOption(RegexpOption):
"""represents the choice of a mac address
"""
__slots__ = tuple() __slots__ = tuple()
_regexp = re.compile(r"^([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})$") _regexp = re.compile(r"^([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})$")
_type = 'macaddress' _type = _('mac address')
_display_name = _('mac address')

View file

@ -18,21 +18,18 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_interface, ip_network """NetmaskOption
from typing import List """
from ipaddress import ip_network
from ..error import ConfigError
from ..setting import undefined, OptionBag, Undefined
from ..i18n import _ from ..i18n import _
from .option import Option
from .stroption import StrOption from .stroption import StrOption
class NetmaskOption(StrOption): class NetmaskOption(StrOption):
"represents the choice of a netmask" """represents the choice of a netmask
"""
__slots__ = tuple() __slots__ = tuple()
_type = 'netmask' _type = _('netmask address')
_display_name = _('netmask address')
def validate(self, def validate(self,
value: str) -> None: value: str) -> None:
@ -41,6 +38,6 @@ class NetmaskOption(StrOption):
if val.startswith("0") and len(val) > 1: if val.startswith("0") and len(val) > 1:
raise ValueError() raise ValueError()
try: try:
ip_network('0.0.0.0/{0}'.format(value)) ip_network(f'0.0.0.0/{value}')
except ValueError: except ValueError as err:
raise ValueError() raise ValueError() from err

View file

@ -18,7 +18,9 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_address, ip_network """NetworkOption
"""
from ipaddress import ip_network
from ..i18n import _ from ..i18n import _
from .stroption import StrOption from .stroption import StrOption
@ -27,8 +29,7 @@ from .stroption import StrOption
class NetworkOption(StrOption): class NetworkOption(StrOption):
"represents the choice of a network" "represents the choice of a network"
__slots__ = tuple() __slots__ = tuple()
_type = 'network' _type = _('network address')
_display_name = _('network address')
def __init__(self, def __init__(self,
*args, *args,
@ -56,8 +57,8 @@ class NetworkOption(StrOption):
raise ValueError() raise ValueError()
try: try:
ip_network(value) ip_network(value)
except ValueError: except ValueError as err:
raise ValueError() raise ValueError() from err
def second_level_validation(self, def second_level_validation(self,
value: str, value: str,

View file

@ -20,21 +20,19 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
import warnings import warnings
import weakref from typing import Any, List, Optional, Dict
from typing import Any, List, Callable, Optional, Dict, Union, Tuple
from itertools import chain from itertools import chain
from .baseoption import BaseOption, submulti, STATIC_TUPLE from .baseoption import BaseOption, submulti
from ..i18n import _ from ..i18n import _
from ..setting import undefined, OptionBag, Undefined from ..setting import undefined, OptionBag
from ..autolib import Calculation, Params, ParamOption, ParamInformation, ParamSelfInformation from ..autolib import Calculation, ParamOption, ParamInformation, ParamSelfInformation
from ..error import (ConfigError, ValueWarning, ValueErrorWarning, from ..error import ValueWarning, ValueErrorWarning, ValueOptionError
ValueOptionError, display_list)
from .syndynoption import SynDynOption from .syndynoption import SynDynOption
#ALLOWED_CONST_LIST = ['_cons_not_equal']
class Option(BaseOption): class Option(BaseOption):
# pylint: disable=too-many-statements,too-many-branches,too-many-arguments,too-many-locals
""" """
Abstract base class for configuration option's. Abstract base class for configuration option's.
@ -55,7 +53,7 @@ class Option(BaseOption):
'_choice_values', '_choice_values',
'_choice_values_params', '_choice_values_params',
) )
_empty = '' _type = None
def __init__(self, def __init__(self,
name: str, name: str,
doc: str, doc: str,
@ -67,7 +65,6 @@ class Option(BaseOption):
warnings_only: bool=False, warnings_only: bool=False,
extra: Optional[Dict]=None): extra: Optional[Dict]=None):
_setattr = object.__setattr__ _setattr = object.__setattr__
_dependencies_information = [[], []]
if not multi and default_multi is not None: if not multi and default_multi is not None:
raise ValueError(_("default_multi is set whereas multi is False" raise ValueError(_("default_multi is set whereas multi is False"
" in option: {0}").format(name)) " in option: {0}").format(name))
@ -99,19 +96,11 @@ class Option(BaseOption):
is_multi=is_multi) is_multi=is_multi)
if validators is not None: if validators is not None:
if __debug__ and not isinstance(validators, list): if __debug__ and not isinstance(validators, list):
raise ValueError(_('validators must be a list of Calculation for "{}"').format(name)) raise ValueError(_(f'validators must be a list of Calculation for "{name}"'))
for validator in validators: for validator in validators:
if __debug__ and not isinstance(validator, Calculation): if __debug__ and not isinstance(validator, Calculation):
raise ValueError(_('validators must be a Calculation for "{}"').format(name)) raise ValueError(_('validators must be a Calculation for "{}"').format(name))
for param in chain(validator.params.args, validator.params.kwargs.values()): self.value_dependency(validator)
if isinstance(param, ParamOption):
param.option._add_dependency(self)
self._has_dependency = True
elif isinstance(param, ParamSelfInformation):
_dependencies_information[1].append(param.information_name)
elif isinstance(param, ParamInformation):
_dependencies_information[0].append(param.information_name)
self._validators = tuple(validators) self._validators = tuple(validators)
if extra is not None and extra != {}: if extra is not None and extra != {}:
_setattr(self, '_extra', extra) _setattr(self, '_extra', extra)
@ -121,25 +110,27 @@ class Option(BaseOption):
def test_multi_value(value): def test_multi_value(value):
if isinstance(value, Calculation): if isinstance(value, Calculation):
return return
option_bag = OptionBag() option_bag = OptionBag(self,
option_bag.set_option(self,
None, None,
undefined) undefined,
properties=None,
)
try: try:
self.validate(value) self.validate(value)
self.sync_validate_with_option(value, self.validate_with_option(value,
option_bag) option_bag,
loaded=True,
)
except ValueError as err: except ValueError as err:
str_err = str(err) str_err = str(err)
if not str_err: if not str_err:
raise ValueError(_('invalid default_multi value "{0}" ' raise ValueError(_('invalid default_multi value "{0}" '
'for option "{1}"').format(str(value), 'for option "{1}"').format(str(value),
self.impl_get_display_name())) self.impl_get_display_name())
else: ) from err
raise ValueError(_('invalid default_multi value "{0}" ' raise ValueError(_(f'invalid default_multi value "{value}" for option '
'for option "{1}", {2}').format(str(value), f'"{self.impl_get_display_name()}", {str_err}')
self.impl_get_display_name(), ) from err
str_err))
if _multi is submulti: if _multi is submulti:
if not isinstance(default_multi, Calculation): if not isinstance(default_multi, Calculation):
if not isinstance(default_multi, list): if not isinstance(default_multi, list):
@ -152,70 +143,90 @@ class Option(BaseOption):
else: else:
test_multi_value(default_multi) test_multi_value(default_multi)
_setattr(self, '_default_multi', default_multi) _setattr(self, '_default_multi', default_multi)
option_bag = OptionBag() option_bag = OptionBag(self,
option_bag.set_option(self,
None, None,
undefined) undefined,
self.sync_impl_validate(default, properties=None,
option_bag) )
self.sync_impl_validate(default, self.impl_validate(default,
option_bag, option_bag,
check_error=False) loaded=True,
self.value_dependencies(default, _dependencies_information) )
self.impl_validate(default,
option_bag,
check_error=False,
loaded=True,
)
self.value_dependencies(default)
if (is_multi and default != []) or \ if (is_multi and default != []) or \
(not is_multi and default is not None): (not is_multi and default is not None):
if is_multi and isinstance(default, list): if is_multi and isinstance(default, list):
default = tuple(default) default = tuple(default)
_setattr(self, '_default', default) _setattr(self, '_default', default)
if _dependencies_information[0] or _dependencies_information[1]:
self._dependencies_information = _dependencies_information
def value_dependencies(self, def value_dependencies(self,
value: Any, value: Any,
_dependencies_information: List[str],
) -> Any: ) -> Any:
"""parse dependancies to add dependencies
"""
if isinstance(value, list): if isinstance(value, list):
for val in value: for val in value:
if isinstance(value, list): if isinstance(value, list):
self.value_dependencies(val, _dependencies_information) self.value_dependencies(val)
elif isinstance(value, Calculation): elif isinstance(value, Calculation):
self.value_dependency(val, _dependencies_information) self.value_dependency(val)
elif isinstance(value, Calculation): elif isinstance(value, Calculation):
self.value_dependency(value, _dependencies_information) self.value_dependency(value)
def value_dependency(self, def value_dependency(self,
value: Any, value: Any,
_dependencies_information: List[str],
) -> Any: ) -> Any:
"""parse dependancy to add dependencies
"""
for param in chain(value.params.args, value.params.kwargs.values()): for param in chain(value.params.args, value.params.kwargs.values()):
if isinstance(param, ParamOption): if isinstance(param, ParamOption):
# pylint: disable=protected-access
param.option._add_dependency(self) param.option._add_dependency(self)
elif isinstance(param, ParamSelfInformation): self._has_dependency = True
_dependencies_information[1].append(param.information_name)
elif isinstance(param, ParamInformation): elif isinstance(param, ParamInformation):
_dependencies_information[0].append(param.information_name) dest = self
if isinstance(param, ParamSelfInformation):
opt = self
elif param.option:
dest = param.option
opt = self
else:
opt = None
if not getattr(dest, '_dependencies_information', {}):
dest._dependencies_information = {}
dest._dependencies_information.setdefault(param.information_name, []).append(opt)
#__________________________________________________________________________ #__________________________________________________________________________
# option's information # option's information
def impl_is_multi(self) -> bool: def impl_is_multi(self) -> bool:
"""is it a multi option
"""
return getattr(self, '_multi', 1) != 1 return getattr(self, '_multi', 1) != 1
def impl_is_submulti(self) -> bool: def impl_is_submulti(self) -> bool:
"""is it a submulti option
"""
return getattr(self, '_multi', 1) == 2 return getattr(self, '_multi', 1) == 2
def impl_is_dynsymlinkoption(self) -> bool: def impl_is_dynsymlinkoption(self) -> bool:
"""is a dynsymlinkoption?
"""
return False return False
def get_type(self) -> str: def get_type(self) -> str:
# _display_name for compatibility with older version than 3.0rc3 """get the type of option
return getattr(self, '_type', self._display_name) """
return self._type
def get_display_type(self) -> str:
return self._display_name
def impl_getdefault(self) -> Any: def impl_getdefault(self) -> Any:
"accessing the default value" """accessing the default value
"""
is_multi = self.impl_is_multi() is_multi = self.impl_is_multi()
default = getattr(self, '_default', undefined) default = getattr(self, '_default', undefined)
if default is undefined: if default is undefined:
@ -223,13 +234,13 @@ class Option(BaseOption):
default = [] default = []
else: else:
default = None default = None
else: elif is_multi and isinstance(default, tuple):
if is_multi and isinstance(default, list):
default = list(default) default = list(default)
return default return default
def impl_getdefault_multi(self) -> Any: def impl_getdefault_multi(self) -> Any:
"accessing the default value for a multi" """accessing the default value for a multi
"""
if self.impl_is_submulti(): if self.impl_is_submulti():
default_value = [] default_value = []
else: else:
@ -237,105 +248,35 @@ class Option(BaseOption):
return getattr(self, '_default_multi', default_value) return getattr(self, '_default_multi', default_value)
def impl_get_extra(self, def impl_get_extra(self,
key: str) -> Any: key: str,
) -> Any:
"""if extra parameters are store get it
"""
extra = getattr(self, '_extra', {}) extra = getattr(self, '_extra', {})
if isinstance(extra, tuple): if isinstance(extra, tuple):
if key in extra[0]: if key in extra[0]:
return extra[1][extra[0].index(key)] return extra[1][extra[0].index(key)]
return None return None
else:
return extra.get(key) return extra.get(key)
#__________________________________________________________________________ #__________________________________________________________________________
# validator # validator
def sync_impl_validate(self, def impl_validate(self,
value: Any, value: Any,
option_bag: OptionBag, option_bag: OptionBag,
check_error: bool=True) -> None: check_error: bool=True,
""" loaded: bool=False,
""" ) -> bool:
is_warnings_only = getattr(self, '_warnings_only', False)
def do_validation(_value,
_index):
if isinstance(_value, list):
raise ValueError(_('which must not be a list').format(_value,
self.impl_get_display_name()))
if _value is not None:
if check_error:
# option validation
self.validate(_value)
self.sync_validate_with_option(_value,
option_bag)
if ((check_error and not is_warnings_only) or
(not check_error and is_warnings_only)):
try:
self.second_level_validation(_value,
is_warnings_only)
except ValueError as err:
if is_warnings_only:
warnings.warn_explicit(ValueWarning(_value,
self._display_name,
self,
'{0}'.format(err),
_index),
ValueWarning,
self.__class__.__name__, 0)
else:
raise err
try:
err_index = None
if isinstance(value, Calculation):
pass
elif not self.impl_is_multi():
val = value
do_validation(val, None)
elif self.impl_is_submulti():
if not isinstance(value, list):
raise ValueError(_('which must be a list'))
for err_index, lval in enumerate(value):
if isinstance(lval, Calculation):
continue
if not isinstance(lval, list):
raise ValueError(_('which "{}" must be a list of list'
'').format(lval))
for val in lval:
if isinstance(val, Calculation):
continue
do_validation(val,
err_index)
else:
# it's a multi
if not isinstance(value, list):
raise ValueError(_('which must be a list'))
for err_index, val in enumerate(value):
if isinstance(val, Calculation):
continue
do_validation(val,
err_index)
except ValueError as err:
raise ValueOptionError(value,
self._display_name,
option_bag.ori_option,
'{0}'.format(err),
err_index)
async def impl_validate(self,
value: Any,
option_bag: OptionBag,
check_error: bool=True) -> None:
"""Return True if value is really valid """Return True if value is really valid
If not validate or invalid return it returns False If not validate or invalid return it returns False
""" """
config_bag = option_bag.config_bag config_bag = option_bag.config_bag
force_index = option_bag.index force_index = option_bag.index
is_warnings_only = getattr(self, '_warnings_only', False) is_warnings_only = getattr(self, '_warnings_only', False)
if check_error and config_bag is not undefined and \ if check_error and config_bag is not undefined and \
not 'validator' in config_bag.properties: not 'validator' in config_bag.properties:
return False return False
def _is_not_unique(value, option_bag): def _is_not_unique(value, option_bag):
# if set(value) has not same length than value # if set(value) has not same length than value
if config_bag is undefined or not check_error or \ if config_bag is undefined or not check_error or \
@ -350,10 +291,12 @@ class Option(BaseOption):
raise ValueError(_('the value "{}" is not unique' raise ValueError(_('the value "{}" is not unique'
'').format(val)) '').format(val))
async def calculation_validator(val, def calculation_validator(val,
_index): _index,
):
for validator in getattr(self, '_validators', []): for validator in getattr(self, '_validators', []):
calc_is_warnings_only = hasattr(validator, 'warnings_only') and validator.warnings_only calc_is_warnings_only = hasattr(validator, 'warnings_only') and \
validator.warnings_only
if ((check_error and not calc_is_warnings_only) or if ((check_error and not calc_is_warnings_only) or
(not check_error and calc_is_warnings_only)): (not check_error and calc_is_warnings_only)):
try: try:
@ -367,31 +310,38 @@ class Option(BaseOption):
soption_bag.index = _index soption_bag.index = _index
kwargs['orig_value'] = value kwargs['orig_value'] = value
await validator.execute(soption_bag, validator.execute(soption_bag,
leadership_must_have_index=True, **kwargs,
**kwargs) )
except ValueWarning as warn: except ValueWarning as warn:
warnings.warn_explicit(ValueWarning(val, warnings.warn_explicit(ValueWarning(val,
self._display_name, self.get_type(),
self, self,
'{0}'.format(warn), str(warn),
_index), _index,
),
ValueWarning, ValueWarning,
self.__class__.__name__, 356) self.__class__.__name__, 319)
async def do_validation(_value, def do_validation(_value,
_index): _index,
):
#
if isinstance(_value, list): if isinstance(_value, list):
raise ValueError(_('which must not be a list').format(_value, raise ValueError(_('which must not be a list').format(_value,
self.impl_get_display_name())) self.impl_get_display_name()),
)
if isinstance(_value, Calculation) and config_bag is undefined: if isinstance(_value, Calculation) and config_bag is undefined:
return False return
if _value is not None: if _value is not None:
if check_error: if check_error:
# option validation # option validation
self.validate(_value) self.validate(_value)
await self.validate_with_option(_value, self.validate_with_option(_value,
option_bag) option_bag,
loaded=loaded,
)
if ((check_error and not is_warnings_only) or if ((check_error and not is_warnings_only) or
(not check_error and is_warnings_only)): (not check_error and is_warnings_only)):
try: try:
@ -400,36 +350,40 @@ class Option(BaseOption):
except ValueError as err: except ValueError as err:
if is_warnings_only: if is_warnings_only:
warnings.warn_explicit(ValueWarning(_value, warnings.warn_explicit(ValueWarning(_value,
self._display_name, self.get_type(),
self, self,
'{0}'.format(err), str(err),
_index), _index),
ValueWarning, ValueWarning,
self.__class__.__name__, 0) self.__class__.__name__, 0)
else: else:
raise err raise err
await calculation_validator(_value, if not loaded:
_index) calculation_validator(_value,
try: _index,
)
val = value val = value
err_index = force_index err_index = force_index
try:
if not self.impl_is_multi(): if not self.impl_is_multi():
await do_validation(val, None) do_validation(val, None)
elif force_index is not None: elif force_index is not None:
if self.impl_is_submulti(): if self.impl_is_submulti():
if not isinstance(value, list): if not isinstance(value, list):
raise ValueError(_('which must be a list')) raise ValueError(_('which must be a list'))
for val in value: for val in value:
await do_validation(val, do_validation(val,
force_index) force_index,
_is_not_unique(value, option_bag) )
_is_not_unique(value,
option_bag,
)
else: else:
await do_validation(val, do_validation(val,
force_index) force_index,
)
elif isinstance(value, Calculation) and config_bag is undefined: elif isinstance(value, Calculation) and config_bag is undefined:
pass pass
elif not isinstance(value, list):
raise ValueError(_('which must be a list'))
elif self.impl_is_submulti(): elif self.impl_is_submulti():
for err_index, lval in enumerate(value): for err_index, lval in enumerate(value):
if isinstance(lval, Calculation): if isinstance(lval, Calculation):
@ -438,86 +392,89 @@ class Option(BaseOption):
raise ValueError(_('which "{}" must be a list of list' raise ValueError(_('which "{}" must be a list of list'
'').format(lval)) '').format(lval))
for val in lval: for val in lval:
await do_validation(val, do_validation(val,
err_index) err_index)
_is_not_unique(lval, option_bag) _is_not_unique(lval, option_bag)
elif not isinstance(value, list):
raise ValueError(_('which must be a list'))
else: else:
# FIXME subtimal, not several time is whole=True! # FIXME suboptimal, not several time for whole=True!
for err_index, val in enumerate(value): for err_index, val in enumerate(value):
await do_validation(val, do_validation(val,
err_index) err_index,
)
_is_not_unique(value, option_bag) _is_not_unique(value, option_bag)
except ValueError as err: except ValueError as err:
if config_bag is undefined or \ if config_bag is undefined or \
'demoting_error_warning' not in config_bag.properties: 'demoting_error_warning' not in config_bag.properties:
raise ValueOptionError(val, raise ValueOptionError(val,
self._display_name, self.get_type(),
option_bag.ori_option, option_bag.ori_option,
'{0}'.format(err), str(err),
err_index) from err err_index) from err
warnings.warn_explicit(ValueErrorWarning(val, warnings.warn_explicit(ValueErrorWarning(val,
self._display_name, self.get_type(),
option_bag.ori_option, option_bag.ori_option,
'{0}'.format(err), str(err),
err_index), err_index),
ValueErrorWarning, ValueErrorWarning,
self.__class__.__name__, 0) self.__class__.__name__, 0)
return False return False
return True return True
def _validate_calculator(self, def validate_with_option(self,
callback: Callable,
callback_params: Optional[Params]=None) -> None:
if callback is None:
return
default_multi = getattr(self, '_default_multi', None)
is_multi = self.impl_is_multi()
default = self.impl_getdefault()
if (not is_multi and (default is not None or default_multi is not None)) or \
(is_multi and (default != [] or default_multi is not None)):
raise ValueError(_('default value not allowed if option "{0}" '
'is calculated').format(self.impl_getname()))
def sync_validate_with_option(self,
value: Any, value: Any,
option_bag: OptionBag) -> None: option_bag: OptionBag,
pass loaded: bool,
) -> None:
async def validate_with_option(self, """validation function with option
value: Any, """
option_bag: OptionBag) -> None:
pass
def second_level_validation(self, def second_level_validation(self,
value: Any, value: Any,
warnings_only: bool) -> None: warnings_only: bool,
pass ) -> None:
"""less import validation function
"""
def impl_is_leader(self): def impl_is_leader(self):
"""check if option is a leader in a leadership
"""
leadership = self.impl_get_leadership() leadership = self.impl_get_leadership()
if leadership is None: if leadership is None:
return False return False
return leadership.is_leader(self) return leadership.is_leader(self)
def impl_is_follower(self): def impl_is_follower(self):
"""check if option is a leader in a follower
"""
leadership = self.impl_get_leadership() leadership = self.impl_get_leadership()
if leadership is None: if leadership is None:
return False return False
return not leadership.is_leader(self) return not leadership.is_leader(self)
def impl_get_leadership(self): def impl_get_leadership(self):
"""get leadership
"""
leadership = getattr(self, '_leadership', None) leadership = getattr(self, '_leadership', None)
if leadership is None: if leadership is None:
return leadership return leadership
#pylint: disable=not-callable
return leadership() return leadership()
def to_dynoption(self, def to_dynoption(self,
rootpath: str, rootpath: str,
suffix: str, suffix: str,
ori_dyn, dyn_parent,
) -> SynDynOption: ) -> SynDynOption:
"""tranforme a dynoption to a syndynoption
"""
return SynDynOption(self, return SynDynOption(self,
rootpath, rootpath,
suffix, suffix,
ori_dyn, dyn_parent,
) )
def validate(self, value: Any):
"""option needs a validate function
"""
raise NotImplementedError()

View file

@ -18,27 +18,32 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from copy import copy """OptionDescription
"""
import weakref
from typing import Optional, Iterator, Union, List from typing import Optional, Iterator, Union, List
from ..i18n import _ from ..i18n import _
from ..setting import ConfigBag, OptionBag, groups, undefined, owners, Undefined from ..setting import ConfigBag, OptionBag, groups, undefined, owners, Undefined
from .baseoption import BaseOption from .baseoption import BaseOption
from .syndynoptiondescription import SynDynOptionDescription, SynDynLeadership from .syndynoptiondescription import SubDynOptionDescription, SynDynOptionDescription
from ..error import ConfigError, ConflictError from ..error import ConfigError, ConflictError
class CacheOptionDescription(BaseOption): class CacheOptionDescription(BaseOption):
"""manage cache for option description
"""
__slots__ = ('_cache_force_store_values', __slots__ = ('_cache_force_store_values',
'_cache_dependencies_information', '_cache_dependencies_information',
) )
def impl_already_build_caches(self) -> bool: def impl_already_build_caches(self) -> bool:
"""is a readonly option?
"""
return self.impl_is_readonly() return self.impl_is_readonly()
async def _build_cache(self, def _build_cache(self,
path='',
_consistencies=None, _consistencies=None,
_consistencies_id=0, _consistencies_id=0,
currpath: List[str]=None, currpath: List[str]=None,
@ -49,6 +54,7 @@ class CacheOptionDescription(BaseOption):
) -> None: ) -> None:
"""validate options and set option has readonly option """validate options and set option has readonly option
""" """
# pylint: disable=too-many-branches,too-many-arguments
# _consistencies is None only when we start to build cache # _consistencies is None only when we start to build cache
if _consistencies is None: if _consistencies is None:
init = True init = True
@ -65,202 +71,231 @@ class CacheOptionDescription(BaseOption):
# cache already set # cache already set
raise ConfigError(_('option description seems to be part of an other ' raise ConfigError(_('option description seems to be part of an other '
'config')) 'config'))
for option in await self.get_children(config_bag=undefined, for option in self.get_children(config_bag=undefined, # pylint: disable=no-member
dyn=False): dyn=False,
):
if __debug__: if __debug__:
cache_option.append(option) cache_option.append(option)
sub_currpath = currpath + [option.impl_getname()] sub_currpath = currpath + [option.impl_getname()]
subpath = '.'.join(sub_currpath) subpath = '.'.join(sub_currpath)
if isinstance(option, OptionDescription): if isinstance(option, OptionDescription):
await option._build_cache(subpath, # pylint: disable=protected-access
_consistencies, option._build_cache(_consistencies,
_consistencies_id, _consistencies_id,
sub_currpath, sub_currpath,
cache_option, cache_option,
force_store_values, force_store_values,
dependencies_information, dependencies_information,
display_name) display_name,
)
else: else:
for information in option.get_dependencies_information(): for information, options in option.get_dependencies_information().items():
if None in options:
dependencies_information.setdefault(information, []).append(option) dependencies_information.setdefault(information, []).append(option)
is_multi = option.impl_is_multi()
if not option.impl_is_symlinkoption(): if not option.impl_is_symlinkoption():
properties = option.impl_getproperties() properties = option.impl_getproperties()
if 'force_store_value' in properties: if 'force_store_value' in properties:
force_store_values.append(option) force_store_values.append(option)
if __debug__ and ('force_default_on_freeze' in properties or \ # if __debug__ and ('force_default_on_freeze' in properties or \
'force_metaconfig_on_freeze' in properties) and \ # 'force_metaconfig_on_freeze' in properties) and \
'frozen' not in properties and \ # 'frozen' not in properties and \
option.impl_is_leader(): # option.impl_is_leader():
raise ConfigError(_('a leader ({0}) cannot have ' # raise ConfigError(_('a leader ({0}) cannot have '
'"force_default_on_freeze" or ' # '"force_default_on_freeze" or '
'"force_metaconfig_on_freeze" ' # '"force_metaconfig_on_freeze" '
'property without "frozen"' # 'property without "frozen"'
'').format(option.impl_get_display_name())) # '').format(option.impl_get_display_name()))
if option.impl_is_readonly(): if option.impl_is_readonly():
raise ConflictError(_('duplicate option: {0}').format(option)) raise ConflictError(_('duplicate option: {0}').format(option))
if not self.impl_is_readonly() and display_name: if not self.impl_is_readonly() and display_name:
option._display_name_function = display_name option._display_name_function = display_name # pylint: disable=protected-access
option._path = subpath option._path = subpath # pylint: disable=protected-access
option._set_readonly() option._set_readonly() # pylint: disable=protected-access
if init: if init:
self._cache_force_store_values = force_store_values self._cache_force_store_values = force_store_values # pylint: disable=attribute-defined-outside-init
self._cache_dependencies_information = dependencies_information self._cache_dependencies_information = dependencies_information # pylint: disable=attribute-defined-outside-init
self._path = self._name self._path = self._name # pylint: disable=attribute-defined-outside-init,no-member
self._set_readonly() self._set_readonly()
async def impl_build_force_store_values(self, def impl_build_force_store_values(self,
config_bag: ConfigBag, config_bag: ConfigBag,
) -> None: ) -> None:
async def do_option_bags(option): """set value to force_store_values option
"""
# pylint: disable=too-many-branches
def do_option_bags(option):
if option.issubdyn(): if option.issubdyn():
dynopt = option.getsubdyn() dynopt = option.getsubdyn()
rootpath = dynopt.impl_getpath() yield from dynopt.get_sub_children(option,
subpaths = [rootpath] + option.impl_getpath()[len(rootpath) + 1:].split('.')[1:] config_bag,
for suffix in await dynopt.get_suffixes(config_bag): index=None,
path_suffix = dynopt.convert_suffix_to_path(suffix)
subpath = '.'.join([subp + path_suffix for subp in subpaths])
doption = option.to_dynoption(subpath,
suffix,
dynopt,
) )
doption_bag = OptionBag() else:
doption_bag.set_option(doption, yield OptionBag(option,
None, None,
config_bag, config_bag,
properties=None,
) )
yield doption_bag
else:
option_bag = OptionBag()
option_bag.set_option(option,
None,
config_bag)
yield option_bag
if 'force_store_value' not in config_bag.properties: if 'force_store_value' not in config_bag.properties:
return return
values = config_bag.context.cfgimpl_get_values() values = config_bag.context.get_values()
for option in self._cache_force_store_values: for option in self._cache_force_store_values:
if option.impl_is_follower(): if option.impl_is_follower():
leader = option.impl_get_leadership().get_leader() leader = option.impl_get_leadership().get_leader()
async for leader_option_bag in do_option_bags(leader): for leader_option_bag in do_option_bags(leader):
leader_option_bag.properties = frozenset() leader_option_bag.properties = frozenset()
follower_len = len(await values.getvalue(leader_option_bag)) follower_len = len(values.get_value(leader_option_bag)[0])
if option.issubdyn(): if option.issubdyn():
subpath = leader_option_bag.option.rootpath subpath = leader_option_bag.option.rootpath
doption = option.to_dynoption(subpath, doption = option.to_dynoption(subpath,
leader_option_bag.option.impl_getsuffix(), leader_option_bag.option.impl_getsuffix(),
leader_option_bag.option.ori_dyn, leader_option_bag.option.dyn_parent,
) )
else: else:
doption = option doption = option
subpath = doption.impl_getpath() subpath = doption.impl_getpath()
for index in range(follower_len): for index in range(follower_len):
if await values._p_.hasvalue(config_bag.connection, option_bag = OptionBag(doption,
subpath,
index,
):
continue
option_bag = OptionBag()
option_bag.set_option(doption,
index, index,
config_bag, config_bag,
properties=frozenset(),
) )
option_bag.properties = frozenset() if values.hasvalue(subpath, index=index):
value = await values.getvalue(option_bag) continue
value = values.get_value(option_bag)[0]
if value is None: if value is None:
continue continue
await values._p_.setvalue(config_bag.connection, values.set_storage_value(subpath,
subpath,
value,
owners.forced,
index, index,
False)
else:
async for option_bag in do_option_bags(option):
option_bag.properties = frozenset()
value = await values.getvalue(option_bag)
if value is None:
continue
if await values._p_.hasvalue(config_bag.connection,
option_bag.option.impl_getpath(),
):
continue
await values._p_.setvalue(config_bag.connection,
option_bag.path,
value, value,
owners.forced, owners.forced,
)
else:
for option_bag in do_option_bags(option):
option_bag.properties = frozenset()
value = values.get_value(option_bag)[0]
if value is None:
continue
if values.hasvalue(option_bag.path):
continue
values.set_storage_value(option_bag.path,
None, None,
False, value,
owners.forced,
) )
class OptionDescriptionWalk(CacheOptionDescription): class OptionDescriptionWalk(CacheOptionDescription):
"""get child of option description
"""
__slots__ = ('_children',) __slots__ = ('_children',)
async def get_child(self, def get_child(self,
name: str, name: str,
config_bag: ConfigBag, config_bag: ConfigBag,
subpath: str, subpath: str,
*,
dynoption=None,
option_suffix: Optional[str]=None,
allow_dynoption: bool=False,
) -> Union[BaseOption, SynDynOptionDescription]: ) -> Union[BaseOption, SynDynOptionDescription]:
"""get a child
"""
# if not dyn # if not dyn
if name in self._children[0]: if name in self._children[0]: # pylint: disable=no-member
option = self._children[1][self._children[0].index(name)] option = self._children[1][self._children[0].index(name)] # pylint: disable=no-member
if option.issubdyn(): if option.impl_is_dynoptiondescription():
if allow_dynoption:
option_suffix = None
else:
raise AttributeError(_(f'unknown option "{name}" ' raise AttributeError(_(f'unknown option "{name}" '
"in root optiondescription (it's a dynamic option)" "in root optiondescription (it's a dynamic option)"
)) ))
if option.issubdyn():
return option.to_dynoption(subpath,
option_suffix,
option,
)
return option return option
# if dyn # if dyn
for child in self._children[1]: if dynoption:
if child.impl_is_dynoptiondescription(): self_opt = dynoption
cname = child.impl_getname() else:
if name.startswith(cname): self_opt = self
for suffix in await child.get_suffixes(config_bag): for child in self._children[1]: # pylint: disable=no-member
if name == cname + child.convert_suffix_to_path(suffix): if not child.impl_is_dynoptiondescription():
continue
for suffix in child.get_suffixes(config_bag,
dynoption,
):
if name != child.impl_getname(suffix):
continue
return child.to_dynoption(subpath, return child.to_dynoption(subpath,
suffix, suffix,
child) child,
if self.impl_get_group_type() == groups.root: )
if self.impl_get_group_type() == groups.root: # pylint: disable=no-member
raise AttributeError(_(f'unknown option "{name}" ' raise AttributeError(_(f'unknown option "{name}" '
'in root optiondescription' 'in root optiondescription'
)) ))
else:
raise AttributeError(_(f'unknown option "{name}" ' raise AttributeError(_(f'unknown option "{name}" '
f'in optiondescription "{self.impl_get_display_name()}"' f'in optiondescription "{self_opt.impl_get_display_name()}"'
)) ))
async def get_children(self, def get_children(self,
config_bag: Union[ConfigBag, Undefined], config_bag: Union[ConfigBag, Undefined],
*,
dyn: bool=True, dyn: bool=True,
#path: Optional[str]=None,
dynoption=None,
option_suffix: Optional[str]=None,
) -> Union[BaseOption, SynDynOptionDescription]: ) -> Union[BaseOption, SynDynOptionDescription]:
"""get children
"""
# if path:
# subpath = path
if dynoption:
self_opt = dynoption
else:
self_opt = self
if not dyn or config_bag is undefined or \ if not dyn or config_bag is undefined or \
config_bag.context.cfgimpl_get_description() == self: config_bag.context.get_description() == self:
subpath = '' subpath = ''
else: else:
subpath = self.impl_getpath() subpath = self_opt.impl_getpath()
children = [] for child in self._children[1]: # pylint: disable=no-member
for child in self._children[1]:
if dyn and child.impl_is_dynoptiondescription(): if dyn and child.impl_is_dynoptiondescription():
for suffix in await child.get_suffixes(config_bag): for suffix in child.get_suffixes(config_bag,
children.append(child.to_dynoption(subpath, dynoption,
):
yield child.to_dynoption(subpath,
suffix, suffix,
child)) child,
)
elif dyn and child.issubdyn() or child.impl_is_dynsymlinkoption():
yield child.to_dynoption(subpath,
option_suffix,
child,
)
else: else:
children.append(child) yield child
return children
async def get_children_recursively(self, def get_children_recursively(self,
bytype: Optional[BaseOption], bytype: Optional[BaseOption],
byname: Optional[str], byname: Optional[str],
config_bag: ConfigBag, config_bag: ConfigBag,
self_opt: BaseOption=None) -> Iterator[Union[BaseOption, SynDynOptionDescription]]: self_opt: BaseOption=None,
) -> Iterator[Union[BaseOption, SynDynOptionDescription]]:
"""get children recursively
"""
if self_opt is None: if self_opt is None:
self_opt = self self_opt = self
for option in await self_opt.get_children(config_bag): for option in self_opt.get_children(config_bag):
if option.impl_is_optiondescription(): if option.impl_is_optiondescription():
async for subopt in option.get_children_recursively(bytype, for subopt in option.get_children_recursively(bytype,
byname, byname,
config_bag): config_bag,
):
yield subopt yield subopt
elif (byname is None or option.impl_getname() == byname) and \ elif (byname is None or option.impl_getname() == byname) and \
(bytype is None or isinstance(option, bytype)): (bytype is None or isinstance(option, bytype)):
@ -310,25 +345,39 @@ class OptionDescription(OptionDescriptionWalk):
if dynopt_names: if dynopt_names:
for dynopt in dynopt_names: for dynopt in dynopt_names:
if child != dynopt and child.startswith(dynopt): if child != dynopt and child.startswith(dynopt):
raise ConflictError(_('the option\'s name "{}" start as ' raise ConflictError(_(f'the option\'s name "{child}" start as '
'the dynoptiondescription\'s name "{}"').format(child, dynopt)) f'the dynoptiondescription\'s name "{dynopt}"'))
old = child old = child
self._children = children_ self._children = children_
# the group_type is useful for filtering OptionDescriptions in a config # the group_type is useful for filtering OptionDescriptions in a config
self._group_type = groups.default self._group_type = groups.default
def _setsubdyn(self,
subdyn,
) -> None:
for child in self._children[1]:
child._setsubdyn(subdyn)
super()._setsubdyn(subdyn)
def impl_is_optiondescription(self) -> bool: def impl_is_optiondescription(self) -> bool:
"""the option is an option description
"""
return True return True
def impl_is_dynoptiondescription(self) -> bool: def impl_is_dynoptiondescription(self) -> bool:
"""the option is not dynamic
"""
return False return False
def impl_is_leadership(self) -> bool: def impl_is_leadership(self) -> bool:
"""the option is not a leadership
"""
return False return False
# ____________________________________________________________ # ____________________________________________________________
def impl_set_group_type(self, def impl_set_group_type(self,
group_type: groups.GroupType) -> None: group_type: groups.GroupType,
) -> None:
"""sets a given group object to an OptionDescription """sets a given group object to an OptionDescription
:param group_type: an instance of `GroupType` or `LeadershipGroupType` :param group_type: an instance of `GroupType` or `LeadershipGroupType`
@ -347,16 +396,27 @@ class OptionDescription(OptionDescriptionWalk):
self._group_type = group_type self._group_type = group_type
def impl_get_group_type(self) -> groups.GroupType: def impl_get_group_type(self) -> groups.GroupType:
"""get the group type of option description
"""
return self._group_type return self._group_type
def to_dynoption(self, def to_dynoption(self,
rootpath: str, rootpath: str,
suffix: str, suffix: str,
ori_dyn) -> SynDynOptionDescription: ori_dyn) -> SynDynOptionDescription:
"""get syn dyn option description
"""
if suffix is None:
return SubDynOptionDescription(self,
rootpath,
ori_dyn,
)
return SynDynOptionDescription(self, return SynDynOptionDescription(self,
rootpath, rootpath,
suffix, suffix,
ori_dyn) ori_dyn)
def impl_is_dynsymlinkoption(self) -> bool: def impl_is_dynsymlinkoption(self) -> bool:
"""option is not a dyn symlink option
"""
return False return False

Some files were not shown because too many files have changed in this diff Show more