async version of tiramisu

This commit is contained in:
Emmanuel Garette 2019-12-24 15:24:20 +01:00
parent 76e7fd93b2
commit 503d4b2cca
113 changed files with 12037 additions and 10420 deletions

View file

@ -191,8 +191,9 @@ def _getproperties(multi, isfollower, kwargs):
# define properties # define properties
properties = copy(PROPERTIES_LIST) properties = copy(PROPERTIES_LIST)
if multi and not isfollower: if multi and not isfollower:
default_props = ['empty'] default_props = ['empty', 'unique']
properties.append('empty') properties.append('empty')
properties.append('unique')
else: else:
default_props = [] default_props = []
extra_properties = kwargs.get('extra_properties') extra_properties = kwargs.get('extra_properties')
@ -248,8 +249,9 @@ def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
# define properties # define properties
properties = copy(PROPERTIES_LIST) properties = copy(PROPERTIES_LIST)
if multi and not isfollower: if multi and not isfollower:
default_props = ['empty'] default_props = ['empty', 'unique']
properties.append('empty') properties.append('empty')
properties.append('unique')
else: else:
default_props = [] default_props = []
extra_properties = kwargs.get('extra_properties') extra_properties = kwargs.get('extra_properties')
@ -662,8 +664,11 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
if not kwargs.get('propertyerror', False): if not kwargs.get('propertyerror', False):
leader_value = cfg_.forcepermissive.option(pathread).value.get() leader_value = 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)
@ -683,7 +688,12 @@ 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
@ -1192,7 +1202,7 @@ def autocheck_find(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs
do(confwrite) do(confwrite)
def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, consistency, callback, symlink, weakrefs, **kwargs): def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, callback, symlink, weakrefs, **kwargs):
def _build_make_dict(): def _build_make_dict():
dico = {} dico = {}
dico_value = {} dico_value = {}
@ -1284,31 +1294,6 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
if symlink: if symlink:
dico['extraoptrequirelink'] = 'value' dico['extraoptrequirelink'] = 'value'
dico_value['extraoptrequirelink'] = 'value' dico_value['extraoptrequirelink'] = 'value'
if consistency and has_value:
cpath = list(dico.keys())[0]
if "." in cpath:
cpath = cpath.rsplit('.', 1)[0] + '.'
else:
cpath = ''
if multi:
value = []
else:
value = None
if is_dyn:
dico[cpath + 'extraoptconsistencyval1'] = value
dico_value[cpath + 'extraoptconsistencyval1'] = value
if is_leader:
spath = cpath.split('.')
spath[-2] = spath[-2][:-1] + '2'
spath[-3] = spath[-3][:-1] + '2'
npath = '.'.join(spath) + 'extraoptconsistencyval2'
else:
npath = cpath[:-2] + '2.' + 'extraoptconsistencyval2'
dico[npath] = value
dico_value[npath] = value
else:
dico[cpath + 'extraoptconsistency'] = value
dico_value[cpath + 'extraoptconsistency'] = value
if is_leader: if is_leader:
for cpath in list(paths_.keys())[len(dyns):]: for cpath in list(paths_.keys())[len(dyns):]:
if cpath.endswith('.first') or cpath.endswith('.firstval1') or cpath.endswith('.firstval2'): if cpath.endswith('.first') or cpath.endswith('.firstval1') or cpath.endswith('.firstval2'):
@ -1372,8 +1357,6 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
text += u' with default multi' text += u' with default multi'
if require: if require:
text += u' with requirement' text += u' with requirement'
if consistency:
text += u' with consistency'
text += u', kwargs: {}'.format(kwargs) text += u', kwargs: {}'.format(kwargs)
print(text) print(text)
if not require: if not require:
@ -1528,7 +1511,7 @@ def check_deref(weakrefs):
assert wrf() is None assert wrf() is None
def make_conf(options, multi, default, default_multi, require, consistency, callback, symlink): def make_conf(options, multi, default, default_multi, require, callback, symlink):
weakrefs = [] weakrefs = []
dyn = [] dyn = []
goptions = [] goptions = []
@ -1591,7 +1574,8 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
if callback: if callback:
largs = [path + 'call', "{}'s callback option".format(path)] largs = [path + 'call', "{}'s callback option".format(path)]
objcall = tiramisu_option(*largs, **call_kwargs) objcall = tiramisu_option(*largs, **call_kwargs)
kwargs['callback_params'] = Params(ParamOption(objcall)) kwargs['default'] = Calculation(kwargs['callback'], Params(ParamOption(objcall)))
del kwargs['callback']
else: else:
objcall = None objcall = None
if symlink and not path.endswith('extraoptconsistency'): if symlink and not path.endswith('extraoptconsistency'):
@ -1601,16 +1585,8 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
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)
if not 'extraopt' in path and consistency:
if require:
if symlink:
gopt = goptions[2]
else:
gopt = goptions[1]
else:
gopt = goptions[0]
obj.impl_add_consistency('not_equal', gopt, warnings_only=True, transitive=False)
return obj, objcall, sobj return obj, objcall, sobj
def make_optiondescriptions(path, collected): def make_optiondescriptions(path, collected):
@ -1649,17 +1625,10 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
return obj return obj
collect_options = {} collect_options = {}
if require or consistency: if require:
noptions = OrderedDict() noptions = OrderedDict()
if require: if require:
noptions['extraoptrequire'] = {} noptions['extraoptrequire'] = {}
if consistency:
subpath = list(options.keys())[0]
if '.' in subpath:
subpath = subpath.rsplit('.', 1)[0] + '.'
else:
subpath = ''
noptions[subpath + 'extraoptconsistency'] = {}
noptions.update(options) noptions.update(options)
else: else:
noptions = options noptions = options
@ -1810,34 +1779,29 @@ def test_options(paths):
lpaths = list(paths.keys()) lpaths = list(paths.keys())
for meta in (False, True): # for meta in (False, True):
for callback in (False, True): # for callback in (False, True):
for consistency in (False, True): # for require in (False, True):
for require in (False, True): # for default_multi in (False, True):
for default_multi in (False, True): # for symlink in (False, True):
for symlink in (False, True):
if callback and default_multi:
continue
for default in (False, True):
for multi in (False, True, submulti):
pass
# for meta in (True,):
# for callback in (False,):
# for consistency in (True,):
# for require in (True,):
# for default_multi in (True,):
# for symlink in (False,):
# if callback and default_multi: # if callback and default_multi:
# continue # continue
# for default in (True,): # for default in (False, True):
# for multi in (submulti,): # for multi in (False, True, submulti):
if multi is submulti and default: for meta in (False,):
for callback in (False,):
for require in (False,):
for default_multi in (False,):
for symlink in (False,):
if callback and default_multi:
continue continue
if multi is submulti and consistency: for default in (False,):
for multi in (True,):
if multi is submulti and default:
continue continue
if multi is False and default_multi: if multi is False and default_multi:
continue continue
cfg, weakrefs, dyn = make_conf(paths, multi, default, default_multi, require, consistency, callback, symlink) cfg, weakrefs, dyn = make_conf(paths, multi, default, default_multi, require, callback, symlink)
if cfg is None: if cfg is None:
continue continue
if dyn: if dyn:
@ -1848,7 +1812,7 @@ def test_options(paths):
cnt += 1 cnt += 1
else: else:
check_all(cfg, paths, lpaths[index], meta, multi, default, check_all(cfg, paths, lpaths[index], meta, multi, default,
default_multi, require, consistency, callback, symlink, default_multi, require, callback, symlink,
weakrefs, **get_kwargs(lpaths[idx])) weakrefs, **get_kwargs(lpaths[idx]))
idx += 1 idx += 1
if idx == cnt: if idx == cnt:
@ -1856,7 +1820,7 @@ def test_options(paths):
else: else:
for lpath in lpaths: for lpath in lpaths:
check_all(cfg, paths, lpath, meta, multi, default, check_all(cfg, paths, lpath, meta, multi, default,
default_multi, require, consistency, callback, symlink, default_multi, require, callback, symlink,
weakrefs, **get_kwargs(lpath)) weakrefs, **get_kwargs(lpath))
del cfg del cfg
check_deref(weakrefs) check_deref(weakrefs)

View file

@ -19,11 +19,11 @@ except:
import pytest import pytest
def get_config(config, type, error=False): async def get_config(config, type, error=False):
if type == 'tiramisu': if type == 'tiramisu':
return config return config
if error: if error:
config.property.add('demoting_error_warning') await config.property.add('demoting_error_warning')
return TestConfig(config) return TestConfig(config)
@ -33,8 +33,8 @@ def value_list(values):
return tuple(values) return tuple(values)
def global_owner(config, config_type): async def global_owner(config, config_type):
return config.owner.get() return await config.owner.get()
@pytest.fixture(params=PARAMS) @pytest.fixture(params=PARAMS)

View file

@ -54,7 +54,10 @@
}, },
"model": { "model": {
"options.choice1.choice1": { "options.choice1.choice1": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -54,7 +54,10 @@
}, },
"model": { "model": {
"options.choice1.choice1": { "options.choice1.choice1": {
"required": true "required": true,
"properties": [
"unique"
]
}, },
"options.choice1.choice3": { "options.choice1.choice3": {
"null": { "null": {

View file

@ -55,6 +55,9 @@
"model": { "model": {
"options.choice1.choice1": { "options.choice1.choice1": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"choice 2" "choice 2"
], ],

View file

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

View file

@ -18,7 +18,10 @@
}, },
"model": { "model": {
"options.choice": { "options.choice": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -5,8 +5,8 @@ def get_description():
""" """
option1 = DomainnameOption('hostname1', "Domainname Description") option1 = DomainnameOption('hostname1', "Domainname Description")
option2 = DomainnameOption('hostname2', "Domainname without dot Description", allow_without_dot=True) option2 = DomainnameOption('hostname2', "Domainname without dot Description", allow_without_dot=True)
option3 = DomainnameOption('hostname3', "Hostname or IP Description", type_='hostname', allow_ip=True) option3 = DomainnameOption('hostname3', "Hostname or IP Description", type='hostname', allow_ip=True)
option4 = DomainnameOption('hostname4', "Netbios Description", type_='netbios') option4 = DomainnameOption('hostname4', "Netbios Description", type='netbios')
descr1 = OptionDescription("options", "Common configuration", [option1, option2, option3, option4]) descr1 = OptionDescription("options", "Common configuration", [option1, option2, option3, option4])
descr = OptionDescription("hostname1", "Simple hostnames", [descr1]) descr = OptionDescription("hostname1", "Simple hostnames", [descr1])
return descr return descr

View file

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

View file

@ -34,10 +34,19 @@
} }
}, },
"model": { "model": {
"options.unicode": {
"display": false,
"properties": [
"hidden"
]
},
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true, "required": true,
"display": false, "properties": [
"hidden": true "unique"
],
"hidden": true,
"display": false
} }
}, },
"global": { "global": {

View file

@ -1,15 +1,15 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True, properties=('hidden',)) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration", descr1 = Leadership("unicode", "Common configuration",
[option, option1, option2, option3]) [option, option1, option2, option3], properties=('hidden',))
descr = OptionDescription("options", "Common configuration", [descr1]) descr = OptionDescription("options", "Common configuration", [descr1])
descr = OptionDescription("unicode1_leader_hidden_followers", "Leader follower with unicode and hidden leader", [descr]) descr = OptionDescription("unicode1_leader_hidden_followers", "Leader follower with unicode and hidden leader", [descr])
return descr return descr

View file

@ -35,7 +35,10 @@
}, },
"model": { "model": {
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -1,13 +1,13 @@
from tiramisu.option import UnicodeOption, OptionDescription, Leadership from tiramisu.option import StrOption, OptionDescription, Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration 1", descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3]) [option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1]) descr = OptionDescription("options", "Common configuration 2", [descr1])

View file

@ -41,6 +41,9 @@
"model": { "model": {
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"val1", "val1",
"val2" "val2"

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
from tiramisu.setting import groups from tiramisu.setting import groups
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", ['val1', 'val2'], multi=True) option = StrOption('unicode', "Unicode leader", ['val1', 'val2'], multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2 with default multi", default_multi="follower2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2 with default multi", default_multi="follower2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration 1", descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3]) [option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1]) descr = OptionDescription("options", "Common configuration 2", [descr1])

View file

@ -36,6 +36,9 @@
"model": { "model": {
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"val1", "val1",
"val2" "val2"

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2 hidden", multi=True, properties=('hidden',)) option2 = StrOption('unicode2', "Unicode follower 2 hidden", multi=True, properties=('hidden',))
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration", descr1 = Leadership("unicode", "Common configuration",
[option, option1, option2, option3]) [option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration", [descr1]) descr = OptionDescription("options", "Common configuration", [descr1])
@ -16,10 +16,10 @@ def get_description():
return descr return descr
def get_values(api, allpath=False): async def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_hidden.' root = 'unicode1_leadership_hidden.'
else: else:
root = '' root = ''
api.option(root + 'options.unicode.unicode').value.set([u'val1', u'val2']) await api.option(root + 'options.unicode.unicode').value.set([u'val1', u'val2'])
api.option(root + 'options.unicode.unicode2', 0).value.set(u'super') await api.option(root + 'options.unicode.unicode2', 0).value.set(u'super')

View file

@ -34,7 +34,10 @@
}, },
"model": { "model": {
"options.unicode1.unicode1": { "options.unicode1.unicode1": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader") option = StrOption('unicode', "Unicode leader")
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode1", "Common configuration", descr1 = Leadership("unicode1", "Common configuration",
[option1, option2, option3]) [option1, option2, option3])
descr = OptionDescription("options", "Common configuration", [option, descr1]) descr = OptionDescription("options", "Common configuration", [option, descr1])

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2 not equal", multi=True) option2 = StrOption('unicode2', "Unicode follower 2 not equal", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3 not equal", multi=True) option3 = StrOption('unicode3', "Unicode follower 3 not equal", multi=True)
option2.impl_add_consistency('not_equal', option3) option2.impl_add_consistency('not_equal', option3)
descr1 = Leadership("unicode", "Common configuration 1", descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3]) [option, option1, option2, option3])

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True) option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", requires=[{'option': option2, option3 = StrOption('unicode3', "Unicode follower 3", requires=[{'option': option2,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',
'inverse': True}], 'inverse': True}],

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Value 'test' must show Leadership") option = StrOption('unicode', "Value 'test' must show Leadership")
option1 = UnicodeOption('unicode1', "Unicode leader", multi=True) option1 = StrOption('unicode1', "Unicode leader", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 2", multi=True) option3 = StrOption('unicode3', "Unicode follower 2", multi=True)
descr1 = Leadership("unicode1", "Common configuration", descr1 = Leadership("unicode1", "Common configuration",
[option1, option2, option3], requires=[{'option': option, [option1, option2, option3], requires=[{'option': option,
'expected': u'test', 'expected': u'test',

View file

@ -1,13 +1,13 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Values 'test' must show 'Unicode follower 2'", multi=True) option1 = StrOption('unicode1', "Values 'test' must show 'Unicode follower 2'", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 2", multi=True, option3 = StrOption('unicode3', "Unicode follower 2", multi=True,
requires=[{'option': option1, requires=[{'option': option1,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',

View file

@ -1,13 +1,13 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Values 'test' must show 'Unicode follower 2'", multi=True) option1 = StrOption('unicode1', "Values 'test' must show 'Unicode follower 2'", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 2", multi=True, option3 = StrOption('unicode3', "Unicode follower 2", multi=True,
requires=[{'option': option1, requires=[{'option': option1,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',
@ -19,11 +19,11 @@ def get_description():
return descr return descr
def get_values(api, allpath=False): async 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 = ''
api.option(root + 'options.unicode1.unicode1').value.set([u'test', u'pas test']) await api.option(root + 'options.unicode1.unicode1').value.set([u'test', u'pas test'])
api.option(root + 'options.unicode1.unicode2', 0).value.set(u'super1') await api.option(root + 'options.unicode1.unicode2', 0).value.set(u'super1')
api.option(root + 'options.unicode1.unicode3', 0).value.set(u'super1') await api.option(root + 'options.unicode1.unicode3', 0).value.set(u'super1')

View file

@ -1,13 +1,13 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Unicode leader", multi=True) option1 = StrOption('unicode1', "Unicode leader", multi=True)
option2 = UnicodeOption('unicode2', "Values 'test' must show 'Unicode follower 2'", multi=True) option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 2'", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 2", multi=True, option3 = StrOption('unicode3', "Unicode follower 2", multi=True,
requires=[{'option': option2, requires=[{'option': option2,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',

View file

@ -1,17 +1,17 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Value 'test' must show leader") option = StrOption('unicode', "Value 'test' must show leader")
option1 = UnicodeOption('unicode1', "Unicode leader", multi=True, requires=[{'option': option, option1 = StrOption('unicode1', "Unicode leader", multi=True, requires=[{'option': option,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',
'inverse': True}]) 'inverse': True}])
option2 = UnicodeOption('unicode2', "Unicode follower 1", multi=True) option2 = StrOption('unicode2', "Unicode follower 1", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 2", multi=True) option3 = StrOption('unicode3', "Unicode follower 2", multi=True)
descr1 = Leadership("unicode1", "Common configuration", descr1 = Leadership("unicode1", "Common configuration",
[option1, option2, option3]) [option1, option2, option3])
descr = OptionDescription("options", "Common configuration", [option, descr1]) descr = OptionDescription("options", "Common configuration", [option, descr1])

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Values 'test' must show 'Unicode follower 3'", multi=True) option = StrOption('unicode', "Values 'test' must show 'Unicode follower 3'", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", requires=[{'option': option, option3 = StrOption('unicode3', "Unicode follower 3", requires=[{'option': option,
'expected': u'test', 'expected': u'test',
'action': 'hidden', 'action': 'hidden',
'inverse': True}], 'inverse': True}],
@ -20,14 +20,14 @@ def get_description():
return descr return descr
def get_values(api, allpath=False): async def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_requires_value.' root = 'unicode1_leadership_requires_value.'
else: else:
root = '' root = ''
api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2']) await api.option(root + 'options.unicode.unicode').value.set([u'test', u'val2'])
api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1') await api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1')
api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2') await api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2')
api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test') await api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test')
api.option(root + 'options.unicode.unicode2', 1).value.set(u'test') await api.option(root + 'options.unicode.unicode2', 1).value.set(u'test')
api.option(root + 'options.unicode.unicode3', 1).value.set(u'super') await api.option(root + 'options.unicode.unicode3', 1).value.set(u'super')

View file

@ -36,7 +36,10 @@
}, },
"model": { "model": {
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription, submulti from tiramisu.option import StrOption, OptionDescription, submulti
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", multi=True) option = StrOption('unicode', "Unicode leader", multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2 submulti", multi=submulti) option2 = StrOption('unicode2', "Unicode follower 2 submulti", multi=submulti)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration 1", descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3]) [option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1]) descr = OptionDescription("options", "Common configuration 2", [descr1])

View file

@ -41,6 +41,9 @@
"model": { "model": {
"options.unicode.unicode": { "options.unicode.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"val3", "val3",
"val4" "val4"

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
from tiramisu import Leadership from tiramisu import Leadership
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode leader", ['val1', 'val2'], multi=True) option = StrOption('unicode', "Unicode leader", ['val1', 'val2'], multi=True)
option1 = UnicodeOption('unicode1', "Unicode follower 1", multi=True) option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = UnicodeOption('unicode2', "Unicode follower 2 with default multi", default_multi="follower2", multi=True) option2 = StrOption('unicode2', "Unicode follower 2 with default multi", default_multi="follower2", multi=True)
option3 = UnicodeOption('unicode3', "Unicode follower 3", multi=True) option3 = StrOption('unicode3', "Unicode follower 3", multi=True)
descr1 = Leadership("unicode", "Common configuration 1", descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3]) [option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1]) descr = OptionDescription("options", "Common configuration 2", [descr1])
@ -16,14 +16,14 @@ def get_description():
return descr return descr
def get_values(api, allpath=False): async def get_values(api, allpath=False):
if allpath: if allpath:
root = 'unicode1_leadership_value.' root = 'unicode1_leadership_value.'
else: else:
root = '' root = ''
api.option(root + 'options.unicode.unicode').value.set([u'val3', u'val4']) await api.option(root + 'options.unicode.unicode').value.set([u'val3', u'val4'])
api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1') await api.option(root + 'options.unicode.unicode1', 0).value.set(u'super1')
api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2') await api.option(root + 'options.unicode.unicode1', 1).value.set(u'super2')
api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test') await api.option(root + 'options.unicode.unicode2', 0).value.set(u'pas test')
api.option(root + 'options.unicode.unicode2', 1).value.set(u'test') await api.option(root + 'options.unicode.unicode2', 1).value.set(u'test')
api.option(root + 'options.unicode.unicode3', 1).value.set(u'super') await api.option(root + 'options.unicode.unicode3', 1).value.set(u'super')

View file

@ -1,8 +1,28 @@
{"updates": ["options.unicode.unicode", {
"updates": [
"options.unicode.unicode",
"options.unicode.unicode1", "options.unicode.unicode1",
"options.unicode.unicode2", "options.unicode.unicode2",
"options.unicode.unicode3"], "options.unicode.unicode3"
"model": {"options.unicode.unicode": {"required": true, ],
"value": ["val1", "val2"]}, "model": {
"options.unicode.unicode2": {"0": {"value": "follower2"}, "options.unicode.unicode": {
"1": {"value": "follower2"}}}} "required": true,
"properties": [
"unique"
],
"value": [
"val1",
"val2"
]
},
"options.unicode.unicode2": {
"0": {
"value": "follower2"
},
"1": {
"value": "follower2"
}
}
}
}

View file

@ -1,11 +1,32 @@
{"updates": ["options.unicode.unicode", {
"updates": [
"options.unicode.unicode",
"options.unicode.unicode1", "options.unicode.unicode1",
"options.unicode.unicode2", "options.unicode.unicode2",
"options.unicode.unicode3"], "options.unicode.unicode3"
"model": {"options.unicode.unicode": {"required": true, ],
"value": ["val3"], "model": {
"owner": "user"}, "options.unicode.unicode": {
"options.unicode.unicode1": {"0": {"value": "super1", "required": true,
"owner": "user"}}, "properties": [
"options.unicode.unicode2": {"0": {"value": "pas test", "unique"
"owner": "user"}}}} ],
"value": [
"val3"
],
"owner": "user"
},
"options.unicode.unicode1": {
"0": {
"value": "super1",
"owner": "user"
}
},
"options.unicode.unicode2": {
"0": {
"value": "pas test",
"owner": "user"
}
}
}
}

View file

@ -1,16 +1,49 @@
{"updates": ["options.unicode.unicode", {
"options.unicode.unicode2"], "updates": [
"model": {"options.unicode.unicode": {"required": true, "options.unicode.unicode",
"value": ["val3", "val4", "val5"], "options.unicode.unicode2"
"owner": "user"}, ],
"options.unicode.unicode1": {"0": {"value": "super1", "model": {
"owner": "user"}, "options.unicode.unicode": {
"1": {"value": "super2", "required": true,
"owner": "user"}}, "properties": [
"options.unicode.unicode2": {"0": {"value": "pas test", "unique"
"owner": "user"}, ],
"1": {"value": "test", "value": [
"owner": "user"}, "val3",
"2": {"value": "follower2"}}, "val4",
"options.unicode.unicode3": {"1": {"value": "super", "val5"
"owner": "user"}}}} ],
"owner": "user"
},
"options.unicode.unicode1": {
"0": {
"value": "super1",
"owner": "user"
},
"1": {
"value": "super2",
"owner": "user"
}
},
"options.unicode.unicode2": {
"0": {
"value": "pas test",
"owner": "user"
},
"1": {
"value": "test",
"owner": "user"
},
"2": {
"value": "follower2"
}
},
"options.unicode.unicode3": {
"1": {
"value": "super",
"owner": "user"
}
}
}
}

View file

@ -1,15 +1,49 @@
{"model": {"options.unicode.unicode": {"owner": "user", {
"updates": [
"options.unicode.unicode",
"options.unicode.unicode2"
],
"model": {
"options.unicode.unicode": {
"required": true, "required": true,
"value": ["val3", "val4", "val5"]}, "properties": [
"options.unicode.unicode1": {"0": {"owner": "user", "unique"
"value": "super1"}, ],
"1": {"owner": "user", "value": [
"value": "super2"}}, "val3",
"options.unicode.unicode2": {"0": {"owner": "user", "val4",
"value": "pas test"}, "val5"
"1": {"owner": "user", ],
"value": "test"}, "owner": "user"
"2": {"value": "follower2"}}, },
"options.unicode.unicode3": {"1": {"owner": "user", "options.unicode.unicode1": {
"value": "super"}}}, "0": {
"updates": ["options.unicode.unicode", "options.unicode.unicode2"]} "value": "super1",
"owner": "user"
},
"1": {
"value": "super2",
"owner": "user"
}
},
"options.unicode.unicode2": {
"0": {
"value": "pas test",
"owner": "user"
},
"1": {
"value": "test",
"owner": "user"
},
"2": {
"value": "follower2"
}
},
"options.unicode.unicode3": {
"1": {
"value": "super",
"owner": "user"
}
}
}
}

View file

@ -1,13 +1,43 @@
{"updates": ["options.unicode.unicode2"], {
"model": {"options.unicode.unicode": {"required": true, "updates": [
"value": ["val3", "val4"], "options.unicode.unicode2"
"owner": "user"}, ],
"options.unicode.unicode1": {"0": {"value": "super1", "model": {
"owner": "user"}, "options.unicode.unicode": {
"1": {"value": "super2", "required": true,
"owner": "user"}}, "properties": [
"options.unicode.unicode2": {"0": {"value": "pas test", "unique"
"owner": "user"}, ],
"1": {"value": "follower2"}}, "value": [
"options.unicode.unicode3": {"1": {"value": "super", "val3",
"owner": "user"}}}} "val4"
],
"owner": "user"
},
"options.unicode.unicode1": {
"0": {
"value": "super1",
"owner": "user"
},
"1": {
"value": "super2",
"owner": "user"
}
},
"options.unicode.unicode2": {
"0": {
"value": "pas test",
"owner": "user"
},
"1": {
"value": "follower2"
}
},
"options.unicode.unicode3": {
"1": {
"value": "super",
"owner": "user"
}
}
}
}

View file

@ -1,14 +1,44 @@
{"updates": ["options.unicode.unicode2"], {
"model": {"options.unicode.unicode": {"required": true, "updates": [
"value": ["val3", "val4"], "options.unicode.unicode2"
"owner": "user"}, ],
"options.unicode.unicode1": {"0": {"value": "super1", "model": {
"owner": "user"}, "options.unicode.unicode": {
"1": {"value": "super2", "required": true,
"owner": "user"}}, "properties": [
"options.unicode.unicode2": {"0": {"value": "pas test", "unique"
"owner": "user"}, ],
"1": {"value": "test2", "value": [
"owner": "user"}}, "val3",
"options.unicode.unicode3": {"1": {"value": "super", "val4"
"owner": "user"}}}} ],
"owner": "user"
},
"options.unicode.unicode1": {
"0": {
"value": "super1",
"owner": "user"
},
"1": {
"value": "super2",
"owner": "user"
}
},
"options.unicode.unicode2": {
"0": {
"value": "pas test",
"owner": "user"
},
"1": {
"value": "test2",
"owner": "user"
}
},
"options.unicode.unicode3": {
"1": {
"value": "super",
"owner": "user"
}
}
}
}

View file

@ -1,11 +1,11 @@
"""just a multi unicode option """just a multi unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode 1", properties=('mandatory',)) option = StrOption('unicode', "Unicode 1", properties=('mandatory',))
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode1_mandatory", "Mandatory unicode", [descr1]) descr = OptionDescription("unicode1_mandatory", "Mandatory unicode", [descr1])
return descr return descr

View file

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

View file

@ -14,7 +14,10 @@
}, },
"model": { "model": {
"options.unicode": { "options.unicode": {
"required": true "required": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -1,11 +1,11 @@
"""just a multi unicode option """just a multi unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Multi string 1", multi=True) option = StrOption('unicode', "Multi string 1", multi=True)
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode1_multi", "Multi unicode", [descr1]) descr = OptionDescription("unicode1_multi", "Multi unicode", [descr1])
return descr return descr

View file

@ -1,4 +1,17 @@
{"updates": ["options.unicode"], {
"model": {"options.unicode": {"owner": "user", "updates": [
"options.unicode"
],
"model": {
"options.unicode": {
"required": true, "required": true,
"value": ["val"]}}} "properties": [
"unique"
],
"value": [
"val"
],
"owner": "user"
}
}
}

View file

@ -15,6 +15,9 @@
"model": { "model": {
"options.unicode": { "options.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"display": false, "display": false,
"hidden": true "hidden": true
} }

View file

@ -1,11 +1,11 @@
"""just a multi unicode option """just a multi unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode 1", properties=('hidden',), multi=True) option = StrOption('unicode', "Unicode 1", properties=('hidden',), multi=True)
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode1_multi_hidden", "Hidden multi unicode", [descr1]) descr = OptionDescription("unicode1_multi_hidden", "Hidden multi unicode", [descr1])
return descr return descr

View file

@ -15,7 +15,10 @@
"model": { "model": {
"options.unicode": { "options.unicode": {
"required": true, "required": true,
"needs_len": true "needs_len": true,
"properties": [
"unique"
]
} }
}, },
"global": { "global": {

View file

@ -1,11 +1,11 @@
"""just a multi unicode option """just a multi unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode 1", multi=True, properties=('mandatory',)) option = StrOption('unicode', "Unicode 1", multi=True, properties=('mandatory',))
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode1_multi_mandatory", "Mandatory multi Unicode", [descr1]) descr = OptionDescription("unicode1_multi_mandatory", "Mandatory multi Unicode", [descr1])
return descr return descr

View file

@ -19,6 +19,9 @@
"model": { "model": {
"options.unicode": { "options.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"c", "c",
"d", "d",

View file

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

View file

@ -1,3 +1,17 @@
{"updates": ["options.unicode"], {
"model": {"options.unicode": {"required": true, "updates": [
"value": ["a", "b"]}}} "options.unicode"
],
"model": {
"options.unicode": {
"required": true,
"properties": [
"unique"
],
"value": [
"a",
"b"
]
}
}
}

View file

@ -1,4 +1,19 @@
{"updates": ["options.unicode"], {
"model": {"options.unicode": {"owner": "user", "updates": [
"options.unicode"
],
"model": {
"options.unicode": {
"required": true, "required": true,
"value": ["c", "f", "e"]}}} "properties": [
"unique"
],
"value": [
"c",
"f",
"e"
],
"owner": "user"
}
}
}

View file

@ -1,14 +1,14 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Unicode 1, not equal to 'a'") option1 = StrOption('unicode1', "Unicode 1, not equal to 'a'")
option2 = UnicodeOption('unicode1_multi', "Multi unicode 1, not equal to 'a' or 'b'", multi=True) option2 = StrOption('unicode1_multi', "Multi unicode 1, not equal to 'a' or 'b'", multi=True)
option3 = UnicodeOption('unicode2', "Unicode 2", default='a') option3 = StrOption('unicode2', "Unicode 2", default='a')
option4 = UnicodeOption('unicode2_multi', "Multi unicode 2", multi=True, default=['a', 'b']) option4 = StrOption('unicode2_multi', "Multi unicode 2", multi=True, default=['a', 'b'])
option5 = UnicodeOption('unicode3', "Unicode 3") option5 = StrOption('unicode3', "Unicode 3")
option6 = UnicodeOption('unicode3_multi', "Multi unicode 3", multi=True) option6 = StrOption('unicode3_multi', "Multi unicode 3", multi=True)
#option1.impl_add_consistency('not_equal', option3, option5) #option1.impl_add_consistency('not_equal', option3, option5)
#option2.impl_add_consistency('not_equal', option4, option6) #option2.impl_add_consistency('not_equal', option4, option6)
option3.impl_add_consistency('not_equal', option1) option3.impl_add_consistency('not_equal', option1)

View file

@ -19,6 +19,9 @@
"model": { "model": {
"options.unicode": { "options.unicode": {
"required": true, "required": true,
"properties": [
"unique"
],
"value": [ "value": [
"a", "a",
"b" "b"

View file

@ -1,11 +1,11 @@
"""just a multi unicode option """just a multi unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "String 1", ['a', 'b'], multi=True) option = StrOption('unicode', "String 1", ['a', 'b'], multi=True)
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode1_multi_value", "Multi unicode with default value 'a' and 'b'", [descr1]) descr = OptionDescription("unicode1_multi_value", "Multi unicode with default value 'a' and 'b'", [descr1])
return descr return descr

View file

@ -1,10 +1,10 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Unicode 1") option1 = StrOption('unicode1', "Unicode 1")
option2 = UnicodeOption('unicode2', "Unicode 2") option2 = StrOption('unicode2', "Unicode 2")
option2.impl_add_consistency('not_equal', option1) option2.impl_add_consistency('not_equal', option1)
descr1 = OptionDescription("options", "Common configuration", [option1, option2]) descr1 = OptionDescription("options", "Common configuration", [option1, option2])
descr = OptionDescription("unicode1_not_equal", "Unicode 1 and unicode 2 not equal", [descr1]) descr = OptionDescription("unicode1_not_equal", "Unicode 1 and unicode 2 not equal", [descr1])

View file

@ -1,13 +1,13 @@
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option1 = UnicodeOption('unicode1', "Value 'test' must show OptionDescription") option1 = StrOption('unicode1', "Value 'test' must show OptionDescription")
descr1 = OptionDescription("options", "Common configuration", [option1]) descr1 = OptionDescription("options", "Common configuration", [option1])
option2 = UnicodeOption('unicode2', "Unicode 2") option2 = StrOption('unicode2', "Unicode 2")
option3 = UnicodeOption('unicode3', "Unicode 3") option3 = StrOption('unicode3', "Unicode 3")
descr2 = OptionDescription("unicode1", "OptionDescription with 2 options", descr2 = OptionDescription("unicode1", "OptionDescription with 2 options",
[option2, option3], requires=[{'option': option1, [option2, option3], requires=[{'option': option1,
'expected': u'test', 'expected': u'test',

View file

@ -1,11 +1,11 @@
"""just an unicode option """just an unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Unicode 1", properties=('hidden',)) option = StrOption('unicode', "Unicode 1", properties=('hidden',))
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode_hidden", "Hidden unicode", [descr1]) descr = OptionDescription("unicode_hidden", "Hidden unicode", [descr1])
return descr return descr

View file

@ -1,11 +1,11 @@
"""just an unicode option """just an unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Expert unicode", properties=('expert',)) option = StrOption('unicode', "Expert unicode", properties=('expert',))
descr1 = OptionDescription("options", "Common configuration", [option]) descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("unicode_property", "Hidden because expert", [descr1]) descr = OptionDescription("unicode_property", "Hidden because expert", [descr1])
return descr return descr

View file

@ -1,11 +1,11 @@
"""just an unicode option """just an unicode option
""" """
from tiramisu.option import UnicodeOption, OptionDescription from tiramisu.option import StrOption, OptionDescription
def get_description(): def get_description():
"""generate description for this test """generate description for this test
""" """
option = UnicodeOption('unicode', "Expert unicode") option = StrOption('unicode', "Expert unicode")
descr1 = OptionDescription("options", "Common configuration", [option], properties=('expert',)) descr1 = OptionDescription("options", "Common configuration", [option], properties=('expert',))
descr = OptionDescription("unicode_property_optiondescription", "OptionDescription hidden because expert", [descr1]) descr = OptionDescription("unicode_property_optiondescription", "OptionDescription hidden because expert", [descr1])
return descr return descr

View file

@ -23,18 +23,20 @@ def datapath():
def list_data(ext='.py'): def list_data(ext='.py'):
# return ['choice1_requires.py'] # if ext == '.py':
# return ['choice1_leadership_hidden.py']
datadir = datapath() datadir = datapath()
filenames = listdir(datadir) filenames = listdir(datadir)
filenames.sort() filenames.sort()
ret = [] ret = []
for filename in filenames: for filename in filenames:
if filename.endswith(ext) and not filename.startswith('__'): # if filename.endswith(ext) and not filename.startswith('__'):
if filename.endswith(ext) and not filename.startswith('__') and not 'require' in filename and not 'not_equal' in filename and not 'callback' in filename and not filename == 'unicode2_copy.py' and not filename == 'unicode2_multi_copy.py':
ret.append(filename) ret.append(filename)
return ret return ret
def load_config(filename, async def load_config(filename,
add_extra_od=False, add_extra_od=False,
remote='minimum', remote='minimum',
clearable='minimum', clearable='minimum',
@ -44,20 +46,20 @@ def load_config(filename,
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 = Config(descr) config = await Config(descr)
config.property.add('demoting_error_warning') await config.property.add('demoting_error_warning')
if 'get_values' in dir(mod): if 'get_values' in dir(mod):
mod.get_values(config, add_extra_od) await 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))
config.property.read_write() await config.property.read_write()
if root is None: if root is None:
values = loads(dumps(config.option.dict(remotable=remote, clearable=clearable, form=form))) values = loads(dumps(await config.option.dict(remotable=remote, clearable=clearable, form=form)))
else: else:
values = loads(dumps(config.option(root).dict(remotable=remote, clearable=clearable, form=form))) values = loads(dumps(await config.option(root).dict(remotable=remote, clearable=clearable, form=form)))
return values return values
@ -148,7 +150,8 @@ def filename_mod(request):
return request.param return request.param
def test_jsons(filename): @pytest.mark.asyncio
async def test_jsons(filename):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -165,7 +168,7 @@ 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 = load_config(filename, values = await load_config(filename,
remote=remote, remote=remote,
clearable=clearable) clearable=clearable)
# #
@ -214,7 +217,8 @@ def test_jsons(filename):
assert values == expected, "error in file {}".format(filename) assert values == expected, "error in file {}".format(filename)
def test_jsons_subconfig(filename): @pytest.mark.asyncio
async def test_jsons_subconfig(filename):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -223,7 +227,7 @@ def test_jsons_subconfig(filename):
modulepath = splitext(filename)[0] modulepath = splitext(filename)[0]
if debug: if debug:
print(" ", filename) print(" ", filename)
values = load_config(filename, add_extra_od=True, root=modulepath) values = await 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())
@ -288,7 +292,8 @@ def test_jsons_subconfig(filename):
assert values == expected, "error in file {}".format(filename) assert values == expected, "error in file {}".format(filename)
def test_updates(filename_mod): @pytest.mark.asyncio
async def test_updates(filename_mod):
debug = False debug = False
# debug = True # debug = True
datadir = datapath() datadir = datapath()
@ -357,31 +362,31 @@ 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 = Config(descr) config = await Config(descr)
config.property.add('demoting_error_warning') await config.property.add('demoting_error_warning')
if 'get_values' in dir(mod): if 'get_values' in dir(mod):
mod.get_values(config, issub) await 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:
eval(fh.read()) await 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(config.value.dict(), fh, indent=2) dump(await config.value.dict(), fh, indent=2)
else: else:
assert config.value.dict() == dico_ori, "clearable {}, remote: {}, filename: {}".format(clearable, remote, filename_mod) assert await 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(suboption.dict(remotable=remote, clearable=clearable)))['model'] bodym['model'] = loads(dumps(await suboption.dict(remotable=remote, clearable=clearable)))['model']
else: else:
suboption.dict(remotable=remote, clearable=clearable) await suboption.dict(remotable=remote, clearable=clearable)
bodym = body bodym = body
if with_model: if with_model:
cal_values = suboption.updates(bodym) cal_values = await 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:
@ -394,10 +399,10 @@ def test_updates(filename_mod):
pprint(values) pprint(values)
assert cal_values == values assert cal_values == values
else: else:
assert suboption.updates(bodym) is None assert await 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(config.value.dict(), fh, indent=2) dump(await config.value.dict(), fh, indent=2)
else: else:
assert config.value.dict() == dico_mod assert await config.value.dict() == dico_mod

View file

@ -1,7 +1,7 @@
# coding: utf-8 # coding: utf-8
from time import sleep, time from time import sleep, time
from py.test import raises import pytest
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
@ -38,228 +38,238 @@ def make_description():
return OptionDescription('od1', '', [u1, u2, u3]) return OptionDescription('od1', '', [u1, u2, u3])
def test_cache_config(): @pytest.mark.asyncio
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
c = Config(od1) c = await Config(od1)
assert od1.impl_already_build_caches() is True assert od1.impl_already_build_caches() is True
c c
def test_cache(): @pytest.mark.asyncio
async def test_cache():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await 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._impl_properties_cache
cfg.option('u1').value.get() await 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()
cfg.option('u2').value.get() await 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()
def test_cache_importation(): @pytest.mark.asyncio
async def test_cache_importation():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await Config(od1)
cfg.option('u2').value.set(1) await cfg.option('u2').value.set(1)
export = cfg.value.exportation() export = await cfg.value.exportation()
assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
cfg.option('u2').value.set(2) await cfg.option('u2').value.set(2)
assert cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []} assert await cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []}
cfg.value.importation(export) await cfg.value.importation(export)
assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
def test_cache_importation_property(): @pytest.mark.asyncio
async def test_cache_importation_property():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await Config(od1)
cfg.option('u2').property.add('prop') await cfg.option('u2').property.add('prop')
export = cfg.property.exportation() export = await cfg.property.exportation()
assert cfg.option('u2').property.get() == {'prop'} assert await cfg.option('u2').property.get() == {'prop'}
cfg.option('u2').property.add('prop2') await cfg.option('u2').property.add('prop2')
assert cfg.option('u2').property.get() == {'prop', 'prop2'} assert await cfg.option('u2').property.get() == {'prop', 'prop2'}
cfg.property.importation(export) await cfg.property.importation(export)
assert cfg.option('u2').property.get() == {'prop'} assert await cfg.option('u2').property.get() == {'prop'}
def test_cache_importation_permissive(): @pytest.mark.asyncio
async def test_cache_importation_permissive():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await Config(od1)
cfg.option('u2').permissive.set(frozenset(['prop'])) await cfg.option('u2').permissive.set(frozenset(['prop']))
export = cfg.permissive.exportation() export = await cfg.permissive.exportation()
assert cfg.option('u2').permissive.get() == {'prop'} assert await cfg.option('u2').permissive.get() == {'prop'}
cfg.option('u2').permissive.set(frozenset(['prop', 'prop2'])) await cfg.option('u2').permissive.set(frozenset(['prop', 'prop2']))
assert cfg.option('u2').permissive.get() == {'prop', 'prop2'} assert await cfg.option('u2').permissive.get() == {'prop', 'prop2'}
cfg.permissive.importation(export) await cfg.permissive.importation(export)
assert cfg.option('u2').permissive.get() == {'prop'} assert await cfg.option('u2').permissive.get() == {'prop'}
def test_cache_reset(): @pytest.mark.asyncio
async def test_cache_reset():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await 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._impl_properties_cache
#when change a value #when change a value
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.option('u2').value.get() await 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()
cfg.option('u2').value.set(1) await 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' in settings.get_cached() assert 'u2' not in settings.get_cached()
#when remove a value #when remove a value
cfg.option('u1').value.get() await 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()
cfg.option('u2').value.reset() await 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
cfg.option('u1').value.get() await 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()
cfg.option('u2').property.add('test') await 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()
cfg.option('u1').value.get() await 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()
cfg.option('u2').property.pop('test') await cfg.option('u2').property.pop('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
cfg.option('u1').value.get() await 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()
cfg.property.add('test') await 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()
cfg.option('u1').value.get() await 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()
cfg.property.pop('test') await cfg.property.pop('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()
def test_cache_reset_multi(): @pytest.mark.asyncio
async def test_cache_reset_multi():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await 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._impl_properties_cache
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.option('u3').value.get() await 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
cfg.option('u3').value.set([1]) await 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
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.option('u3').value.get() await 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()
cfg.option('u3').value.set([1, 2]) await 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
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.option('u3').value.get() await 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()
cfg.option('u3').value.set([1]) await 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
cfg.option('u1').value.get() await 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()
cfg.option('u3').value.reset() await 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()
def test_reset_cache(): @pytest.mark.asyncio
async def test_reset_cache():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await 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._impl_properties_cache
cfg.option('u1').value.get() await 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()
cfg.cache.reset() await 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()
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.option('u2').value.get() await 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()
cfg.cache.reset() await 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()
def test_cache_not_cache(): @pytest.mark.asyncio
async def test_cache_not_cache():
od1 = make_description() od1 = make_description()
cfg = Config(od1) cfg = await 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._impl_properties_cache
cfg.property.pop('cache') await cfg.property.pop('cache')
cfg.option('u1').value.get() await 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()
def test_cache_leadership(): @pytest.mark.asyncio
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])
cfg = Config(od1) cfg = await Config(od1)
cfg.property.read_write() await 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._impl_properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
#assert settings.get_cached() == {} #assert settings.get_cached() == {}
# #
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() await 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])
@ -273,10 +283,10 @@ def test_cache_leadership():
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()) == set([0, None])
# #
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.set(['192.168.1.2', '192.168.1.1'])
cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() await 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])
@ -302,16 +312,17 @@ 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]
def test_cache_callback(): @pytest.mark.asyncio
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])
cfg = Config(od1) cfg = await Config(od1)
cfg.property.read_write() await cfg.property.read_write()
cfg.value.dict() await 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._impl_properties_cache
compare(values.get_cached(), {'val1': {None: ('val', None)}, compare(values.get_cached(), {'val1': {None: ('val', None)},
@ -319,48 +330,48 @@ def test_cache_callback():
'val3': {None: ('yes', None)}, 'val3': {None: ('yes', None)},
'val4': {None: ('val', None)}, 'val4': {None: ('val', None)},
'val5': {None: (['yes'], None)}}) 'val5': {None: (['yes'], None)}})
cfg.option('val1').value.set('new') await 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)}})
cfg.value.dict() await 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)}})
cfg.option('val3').value.set('new2') await 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)}})
cfg.value.dict() await 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)}})
cfg.option('val4').value.set('new3') await 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)}})
cfg.value.dict() await 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)}})
cfg.option('val5').value.set([undefined, 'new4']) await cfg.option('val5').value.set([undefined, 'new4'])
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', 'new4'], None)}}) 'val5': {None: (['yes', 'new4'], None)}})
cfg.value.dict() await 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)},
@ -368,14 +379,15 @@ def test_cache_callback():
'val5': {None: (['yes', 'new4'], None)}}) 'val5': {None: (['yes', 'new4'], None)}})
def test_cache_leader_and_followers(): @pytest.mark.asyncio
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])
cfg = Config(od1) cfg = await Config(od1)
cfg.property.read_write() await cfg.property.read_write()
cfg.value.dict() await 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']
@ -395,13 +407,13 @@ def test_cache_leader_and_followers():
# 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)}})
# #
cfg.option('val1.val1').value.set([undefined]) await cfg.option('val1.val1').value.set([undefined])
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}) '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)}})
cfg.value.dict() await cfg.value.dict()
#has value #has value
idx_val2 = 0 idx_val2 = 0
val_val2 = None val_val2 = None
@ -412,22 +424,23 @@ def test_cache_leader_and_followers():
'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)}})
cfg.option('val1.val1').value.set([undefined, undefined]) await cfg.option('val1.val1').value.set([undefined, undefined])
cfg.value.dict() await cfg.value.dict()
cfg.option('val1.val2', 1).value.set('oui') await 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)}
def test_cache_leader_callback(): @pytest.mark.asyncio
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])
cfg = Config(od1) cfg = await Config(od1)
cfg.property.read_write() await cfg.property.read_write()
cfg.value.dict() await 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']
@ -443,16 +456,18 @@ def test_cache_leader_callback():
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': {None: (val1_val2_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)}})
cfg.option('val1.val1').value.set([undefined]) await cfg.option('val1.val1').value.set([undefined])
compare(settings.get_cached(), {None: {None: (set(global_props), None)}, compare(settings.get_cached(), {None: {None: (set(global_props), None)},
'val1': {None: (set(), None, True)},
'val1.val1': {None: (val1_val1_props, None)}, 'val1.val1': {None: (val1_val1_props, None)},
'val1.val2': {None: (val1_val2_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)}})
cfg.value.dict() await cfg.value.dict()
def test_cache_requires(): @pytest.mark.asyncio
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'),
@ -461,42 +476,42 @@ 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,))
od = OptionDescription('service', '', [a, b]) od = OptionDescription('service', '', [a, b])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await 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._impl_properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
assert cfg.option('ip_address_service').value.get() == None assert await 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)}})
cfg.value.dict() await 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)}})
cfg.option('ip_address_service').value.set('1.1.1.1') await 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)}})
cfg.value.dict() await 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)}})
cfg.option('activate_service').value.set(False) await 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)}})
cfg.value.dict() await 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)}})
@ -504,7 +519,8 @@ def test_cache_requires():
compare(values.get_cached(), {'activate_service': {None: (False, None)}}) compare(values.get_cached(), {'activate_service': {None: (False, None)}})
def test_cache_global_properties(): @pytest.mark.asyncio
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'),
@ -513,47 +529,48 @@ 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,))
od = OptionDescription('service', '', [a, b]) od = OptionDescription('service', '', [a, b])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await 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._impl_properties_cache
assert values.get_cached() == {} assert values.get_cached() == {}
assert cfg.option('ip_address_service').value.get() == None assert await 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)}})
cfg.property.pop('disabled') await cfg.property.pop('disabled')
assert cfg.option('ip_address_service').value.get() == None assert await 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)}})
cfg.property.add('test') await cfg.property.add('test')
assert cfg.option('ip_address_service').value.get() == None assert await 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)}})
def test_callback_value_incr(): @pytest.mark.asyncio
async def test_callback_value_incr():
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])
cfg = Config(od1) cfg = await Config(od1)
assert cfg.cache.get_expiration_time() == 5 assert await cfg.cache.get_expiration_time() == 5
cfg.cache.set_expiration_time(1) await cfg.cache.set_expiration_time(1)
assert cfg.cache.get_expiration_time() == 1 assert await cfg.cache.get_expiration_time() == 1
cfg.property.read_write() await cfg.property.read_write()
assert cfg.option('val1').value.get() == 1 assert await cfg.option('val1').value.get() == 1
sleep(1) sleep(1)
assert cfg.option('val2').value.get() == 1 assert await cfg.option('val2').value.get() == 1
sleep(1) sleep(1)
assert cfg.option('val1').value.get() == 1 assert await cfg.option('val1').value.get() == 1
assert cfg.option('val2').value.get() == 1 assert await cfg.option('val2').value.get() == 1
sleep(2) sleep(2)
assert cfg.option('val1').value.get() == 2 assert await cfg.option('val1').value.get() == 2
assert cfg.option('val2').value.get() == 2 assert await cfg.option('val2').value.get() == 2
assert cfg.option('val1').value.get() == 2 assert await cfg.option('val1').value.get() == 2
assert cfg.option('val2').value.get() == 2 assert await cfg.option('val2').value.get() == 2

View file

@ -1,5 +1,6 @@
# 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()
@ -30,130 +31,147 @@ def return_error(*args, **kwargs):
raise Exception('test') raise Exception('test')
def test_choiceoption(config_type): @pytest.mark.asyncio
async def test_choiceoption(config_type):
choice = ChoiceOption('choice', '', values=('val1', 'val2')) choice = ChoiceOption('choice', '', values=('val1', 'val2'))
odesc = OptionDescription('od', '', [choice]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
owner = global_owner(cfg, config_type) owner = await global_owner(cfg, config_type)
assert cfg.option('choice').owner.get() == owners.default assert await cfg.option('choice').owner.get() == owners.default
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
cfg.option('choice').value.set('val1') await cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
assert not cfg.option('choice').owner.isdefault() assert not await cfg.option('choice').owner.isdefault()
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.get() == owners.default assert await cfg.option('choice').owner.get() == owners.default
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.get() == owners.default await cfg.option('choice').value.set('no')
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.get() == owners.default
assert await cfg.option('choice').owner.isdefault()
# #
assert value_list(cfg.option('choice').value.list()) == ('val1', 'val2') assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2')
def test_choiceoption_function(config_type): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
owner = global_owner(cfg, config_type) owner = await global_owner(cfg, config_type)
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
cfg.option('choice').value.set('val1') await cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.isdefault() await cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault()
# #
assert value_list(cfg.option('choice').value.list()) == ('val1', 'val2') assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2')
def test_choiceoption_function_error(): @pytest.mark.asyncio
async def test_choiceoption_function_error():
choice = ChoiceOption('choice', '', values=Calculation(return_error)) choice = ChoiceOption('choice', '', values=Calculation(return_error))
odesc = OptionDescription('od', '', [choice]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')") with pytest.raises(ConfigError):
await cfg.option('choice').value.set('val1')
def test_choiceoption_function_error_args(): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')") with pytest.raises(ConfigError):
await cfg.option('choice').value.set('val1')
def test_choiceoption_function_error_kwargs(): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')") with pytest.raises(ConfigError):
await cfg.option('choice').value.set('val1')
def test_choiceoption_calc_function(config_type): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
owner = global_owner(cfg, config_type) owner = await global_owner(cfg, config_type)
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
cfg.option('choice').value.set('val1') await cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.isdefault() await cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault()
def test_choiceoption_calc_opt_function(config_type): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
owner = cfg.owner.get() owner = await cfg.owner.get()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
cfg.option('choice').value.set('val1') await cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.isdefault() await cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault()
def test_choiceoption_calc_opt_function_propertyerror(): @pytest.mark.asyncio
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]) odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('no')") with pytest.raises(ConfigError):
await cfg.option('choice').value.set('no')
#def test_choiceoption_calc_opt_multi_function(config_type): #def test_choiceoption_calc_opt_multi_function(config_type):
def test_choiceoption_calc_opt_multi_function(): @pytest.mark.asyncio
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)
@ -168,31 +186,35 @@ def test_choiceoption_calc_opt_multi_function():
values=Calculation(return_val, Params(ParamOption(str_))), values=Calculation(return_val, Params(ParamOption(str_))),
multi=True) multi=True)
odesc = OptionDescription('od', '', [str_, choice, ch2]) odesc = OptionDescription('od', '', [str_, choice, ch2])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
owner = cfg.owner.get() owner = await cfg.owner.get()
cfg = get_config(cfg, config_type, True) cfg = await get_config(cfg, config_type, True)
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
assert cfg.option('choice').value.get() == [] assert await cfg.option('choice').value.get() == []
# #
cfg.option('choice').value.set(['val1']) await cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
raises(ValueError, "cfg.option('choice').value.set([undefined])") with pytest.raises(ValueError):
await cfg.option('choice').value.set([undefined])
# #
cfg.option('choice').value.set(['val1']) await cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.isdefault() await cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('ch2').value.get()") with pytest.raises(ValueError):
await cfg.option('ch2').value.get()
def test_choiceoption_calc_opt_multi_function_kwargs(config_type): @pytest.mark.asyncio
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',
"", "",
@ -205,31 +227,35 @@ def test_choiceoption_calc_opt_multi_function_kwargs(config_type):
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]) odesc = OptionDescription('od', '', [str_, choice, ch2])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
owner = cfg.owner.get() owner = await cfg.owner.get()
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
assert cfg.option('choice').value.get() == [] assert await cfg.option('choice').value.get() == []
# #
cfg.option('choice').value.set(['val1']) await cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
raises(ValueError, "cfg.option('choice').value.set([undefined])") with pytest.raises(ValueError):
await cfg.option('choice').value.set([undefined])
# #
cfg.option('choice').value.set(['val1']) await cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner assert await cfg.option('choice').owner.get() == owner
# #
cfg.option('choice').value.reset() await cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault() assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('choice').value.set('no')") with pytest.raises(ValueError):
assert cfg.option('choice').owner.isdefault() await cfg.option('choice').value.set('no')
assert await cfg.option('choice').owner.isdefault()
# #
raises(ValueError, "cfg.option('ch2').value.get()") with pytest.raises(ValueError):
await cfg.option('ch2').value.get()
def test_choiceoption_calc_not_list(): @pytest.mark.asyncio
async def test_choiceoption_calc_not_list():
str_ = StrOption('str', '', 'val1') str_ = StrOption('str', '', 'val1')
choice = ChoiceOption('choice', choice = ChoiceOption('choice',
"", "",
@ -237,6 +263,7 @@ def test_choiceoption_calc_not_list():
values=Calculation(return_val, Params(ParamOption(str_))), values=Calculation(return_val, Params(ParamOption(str_))),
multi=True) multi=True)
odesc = OptionDescription('od', '', [str_, choice]) odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc) cfg = await Config(odesc)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set(['val1'])") with pytest.raises(ConfigError):
await cfg.option('choice').value.set(['val1'])

View file

@ -2,13 +2,13 @@
"""theses tests are much more to test that config, option description, vs... """theses tests are much more to test that config, option description, vs...
**it's there** and answers via attribute access""" **it's there** and answers via attribute access"""
from py.test import raises
import weakref 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 from .config import config_type, get_config, value_list, global_owner
import pytest
from tiramisu import Config from tiramisu import Config
from tiramisu.config import SubConfig from tiramisu.config import SubConfig
from tiramisu.i18n import _ from tiramisu.i18n import _
@ -45,135 +45,154 @@ def make_description():
return descr return descr
def test_base_config(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
#dmo = cfg.unwrap_from_path('dummy') #dmo = await cfg.unwrap_from_path('dummy')
#assert dmo.impl_getname() == 'dummy' #assert dmo.impl_getname() == 'dummy'
def test_base_config_name(): @pytest.mark.asyncio
async def test_base_config_name():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr, session_id='cfg') cfg = await Config(descr, session_id='cfg')
cfg.config.name() == 'cfg' await cfg.config.name() == 'cfg'
#raises(ValueError, "Config(descr, session_id='unvalid name')") #raises(ValueError, "Config(descr, session_id='unvalid name')")
# #
# #
#def test_not_config(): #@pytest.mark.asyncio
#async def test_not_config():
# assert raises(TypeError, "Config('str')") # assert raises(TypeError, "Config('str')")
def test_base_path(): @pytest.mark.asyncio
async def test_base_path():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
Config(descr) await Config(descr)
base = OptionDescription('config', '', [descr]) base = OptionDescription('config', '', [descr])
base base
raises(ConfigError, "Config(base)") with pytest.raises(ConfigError):
await Config(base)
def test_base_config_force_permissive(): @pytest.mark.asyncio
async def test_base_config_force_permissive():
descr = make_description() descr = make_description()
config = Config(descr) cfg = await Config(descr)
config.property.read_write() await cfg.property.read_write()
config.permissive.add('hidden') await cfg.permissive.add('hidden')
raises(PropertiesOptionError, "config.option('boolop').value.get()") with pytest.raises(PropertiesOptionError):
assert config.forcepermissive.option('boolop').value.get() is True await cfg.option('boolop').value.get()
assert await cfg.forcepermissive.option('boolop').value.get() is True
def test_base_config_in_a_tree(): @pytest.mark.asyncio
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() descr = make_description()
config = Config(descr) cfg = await Config(descr)
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
# #
config.option('bool').value.set(False) await cfg.option('bool').value.set(False)
# #
assert config.option('gc.name').value.get() == 'ref' assert await cfg.option('gc.name').value.get() == 'ref'
config.option('gc.name').value.set('framework') await cfg.option('gc.name').value.set('framework')
assert config.option('gc.name').value.get() == 'framework' assert await cfg.option('gc.name').value.get() == 'framework'
# #
assert config.option('objspace').value.get() == 'std' assert await cfg.option('objspace').value.get() == 'std'
config.option('objspace').value.set('thunk') await cfg.option('objspace').value.set('thunk')
assert config.option('objspace').value.get() == 'thunk' assert await cfg.option('objspace').value.get() == 'thunk'
# #
assert config.option('gc.float').value.get() == 2.3 assert await cfg.option('gc.float').value.get() == 2.3
config.option('gc.float').value.set(3.4) await cfg.option('gc.float').value.set(3.4)
assert config.option('gc.float').value.get() == 3.4 assert await cfg.option('gc.float').value.get() == 3.4
# #
assert config.option('int').value.get() == 0 assert await cfg.option('int').value.get() == 0
config.option('int').value.set(123) await cfg.option('int').value.set(123)
assert config.option('int').value.get() == 123 assert await cfg.option('int').value.get() == 123
# #
assert config.option('wantref').value.get() is False assert await cfg.option('wantref').value.get() is False
config.option('wantref').value.set(True) await cfg.option('wantref').value.set(True)
assert config.option('wantref').value.get() is True assert await cfg.option('wantref').value.get() is True
# #
assert config.option('str').value.get() == 'abc' assert await cfg.option('str').value.get() == 'abc'
config.option('str').value.set('def') await cfg.option('str').value.set('def')
assert config.option('str').value.get() == 'def' assert await cfg.option('str').value.get() == 'def'
# #
raises(AttributeError, "config.option('gc.foo').value.get()") with pytest.raises(AttributeError):
await cfg.option('gc.foo').value.get()
## ##
config = Config(descr) cfg = await Config(descr)
assert config.option('bool').value.get() is True assert await cfg.option('bool').value.get() is True
assert config.option('gc.name').value.get() == 'ref' assert await cfg.option('gc.name').value.get() == 'ref'
assert config.option('wantframework').value.get() is False assert await cfg.option('wantframework').value.get() is False
def test_not_valid_properties(): @pytest.mark.asyncio
raises(AssertionError, "stroption = StrOption('str', 'Test string option', default='abc', properties='mandatory')") async def test_not_valid_properties():
with pytest.raises(AssertionError):
stroption = StrOption('str', 'Test string option', default='abc', properties='mandatory')
def test_information_config(): @pytest.mark.asyncio
async def test_information_config():
descr = make_description() descr = make_description()
config = Config(descr) cfg = await Config(descr)
string = 'some informations' string = 'some informations'
# #
assert list(config.information.list()) == [] assert list(await cfg.information.list()) == []
config.information.set('info', string) await cfg.information.set('info', string)
assert config.information.get('info') == string assert await cfg.information.get('info') == string
assert list(config.information.list()) == ['info'] assert list(await cfg.information.list()) == ['info']
# #
raises(ValueError, "config.information.get('noinfo')") with pytest.raises(ValueError):
assert config.information.get('noinfo', 'default') == 'default' await cfg.information.get('noinfo')
config.information.reset('info') assert await cfg.information.get('noinfo', 'default') == 'default'
raises(ValueError, "config.information.get('info')") await cfg.information.reset('info')
raises(ValueError, "config.information.reset('noinfo')") with pytest.raises(ValueError):
assert list(config.information.list()) == [] await cfg.information.get('info')
with pytest.raises(ValueError):
await cfg.information.reset('noinfo')
assert list(await cfg.information.list()) == []
def test_information_option(): @pytest.mark.asyncio
async def test_information_option():
descr = make_description() descr = make_description()
config = Config(descr) cfg = await Config(descr)
string = 'some informations' string = 'some informations'
# #
list(config.option('gc.name').information.list()) == [] list(await cfg.option('gc.name').information.list()) == []
config.option('gc.name').information.set('info', string) await cfg.option('gc.name').information.set('info', string)
assert config.option('gc.name').information.get('info') == string assert await cfg.option('gc.name').information.get('info') == string
list(config.option('gc.name').information.list()) == ['info'] list(await cfg.option('gc.name').information.list()) == ['info']
# #
raises(ValueError, "config.option('gc.name').information.get('noinfo')") with pytest.raises(ValueError):
assert config.option('gc.name').information.get('noinfo', 'default') == 'default' await cfg.option('gc.name').information.get('noinfo')
config.option('gc.name').information.reset('info') assert await cfg.option('gc.name').information.get('noinfo', 'default') == 'default'
raises(ValueError, "config.option('gc.name').information.get('info')") await cfg.option('gc.name').information.reset('info')
raises(ValueError, "config.option('gc.name').information.reset('noinfo')") with pytest.raises(ValueError):
list(config.option('gc.name').information.list()) == [] await cfg.option('gc.name').information.get('info')
with pytest.raises(ValueError):
await cfg.option('gc.name').information.reset('noinfo')
list(await cfg.option('gc.name').information.list()) == []
# #
assert config.option('wantref').information.get('info') == 'default value' assert await cfg.option('wantref').information.get('info') == 'default value'
config.option('wantref').information.set('info', 'default value') await cfg.option('wantref').information.set('info', 'default value')
assert config.option('wantref').information.get('info') == 'default value' assert await cfg.option('wantref').information.get('info') == 'default value'
config.option('wantref').information.reset('info') await cfg.option('wantref').information.reset('info')
assert config.option('wantref').information.get('info') == 'default value' assert await cfg.option('wantref').information.get('info') == 'default value'
def to_tuple(val): def to_tuple(val):
@ -189,7 +208,8 @@ def to_tuple(val):
return tuple(ret) return tuple(ret)
def test_get_modified_values(): @pytest.mark.asyncio
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é')
@ -198,172 +218,193 @@ def test_get_modified_values():
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]) root = OptionDescription('root', '', [d1])
config = Config(root) cfg = await Config(root)
assert to_tuple(config.value.exportation()) == ((), (), (), ()) assert to_tuple(await cfg.value.exportation()) == ((), (), (), ())
assert not config.option('od.g5').option.ismulti() assert not await cfg.option('od.g5').option.ismulti()
assert not config.option('od.g5').option.issubmulti() assert not await cfg.option('od.g5').option.issubmulti()
config.option('od.g5').value.set('yes') await cfg.option('od.g5').value.set('yes')
assert to_tuple(config.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',)) assert to_tuple(await cfg.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',))
config.option('od.g4').value.set(False) await cfg.option('od.g4').value.set(False)
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user'))
config.option('od.g4').value.set(undefined) await cfg.option('od.g4').value.set(undefined)
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user'))
config.option('od.g4').value.reset() await cfg.option('od.g4').value.reset()
assert to_tuple(config.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',)) assert to_tuple(await cfg.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',))
assert config.option('od.g6').option.ismulti() assert await cfg.option('od.g6').option.ismulti()
config.option('od.g6').value.set([undefined]) await cfg.option('od.g6').value.set([undefined])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user'))
config.option('od.g6').value.set([]) await cfg.option('od.g6').value.set([])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))
config.option('od.g6').value.set(['3']) await cfg.option('od.g6').value.set(['3'])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user'))
config.option('od.g6').value.set([]) await cfg.option('od.g6').value.set([])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user')) assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))
def test_get_modified_values_not_modif(config_type): @pytest.mark.asyncio
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]) root = OptionDescription('root', '', [d1])
config = Config(root) cfg = await Config(root)
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
assert config.option('od.g1').value.get() == [] assert await cfg.option('od.g1').value.get() == []
value = config.option('od.g1').value.get() value = await cfg.option('od.g1').value.get()
value.append('val') value.append('val')
assert config.option('od.g1').value.get() == [] assert await cfg.option('od.g1').value.get() == []
def test_duplicated_option(): @pytest.mark.asyncio
async def test_duplicated_option():
g1 = IntOption('g1', '', 1) g1 = IntOption('g1', '', 1)
g1 g1
#in same OptionDescription #in same OptionDescription
raises(ConflictError, "d1 = OptionDescription('od', '', [g1, g1])") with pytest.raises(ConflictError):
d1 = OptionDescription('od', '', [g1, g1])
def test_duplicated_option_diff_od(): @pytest.mark.asyncio
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
raises(ConflictError, 'Config(d2)') with pytest.raises(ConflictError):
await Config(d2)
def test_cannot_assign_value_to_option_description(): @pytest.mark.asyncio
async def test_cannot_assign_value_to_option_description():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
raises(APIError, "cfg.option('gc').value.set(3)") with pytest.raises(APIError):
await cfg.option('gc').value.set(3)
def test_config_multi(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('test', '', [i1, i2, i3])
config = Config(od) cfg = await Config(od)
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
assert config.option('test1').value.get() == [] assert await cfg.option('test1').value.get() == []
assert config.option('test2').value.get() == [] assert await cfg.option('test2').value.get() == []
config.option('test2').value.set([undefined]) await cfg.option('test2').value.set([undefined])
assert config.option('test2').value.get() == [1] assert await cfg.option('test2').value.get() == [1]
assert config.option('test3').value.get() == [2] assert await cfg.option('test3').value.get() == [2]
config.option('test3').value.set([undefined, undefined]) await cfg.option('test3').value.set([undefined, undefined])
assert config.option('test3').value.get() == [2, 1] assert await cfg.option('test3').value.get() == [2, 1]
def test_prefix_error(): @pytest.mark.asyncio
async def test_prefix_error():
i1 = IntOption('test1', '') i1 = IntOption('test1', '')
od = OptionDescription('test', '', [i1]) od = OptionDescription('test', '', [i1])
config = Config(od) cfg = await Config(od)
config.property.read_write() await cfg.property.read_write()
config.option('test1').value.set(1) await cfg.option('test1').value.set(1)
try: try:
config.option('test1').value.set('yes') await 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:
config.option('test1').value.set('yes') await 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')
def test_no_validation(): @pytest.mark.asyncio
async def test_no_validation():
# FIXME # FIXME
config_type = 'tiramisu' config_type = 'tiramisu'
i1 = IntOption('test1', '') i1 = IntOption('test1', '')
od = OptionDescription('test', '', [i1]) od = OptionDescription('test', '', [i1])
config = Config(od) config = await Config(od)
config.property.read_write() await config.property.read_write()
cfg = get_config(config, config_type) cfg = await get_config(config, config_type)
cfg.option('test1').value.set(1) await cfg.option('test1').value.set(1)
raises(ValueError, "cfg.option('test1').value.set('yes')") with pytest.raises(ValueError):
assert cfg.option('test1').value.get() == 1 await cfg.option('test1').value.set('yes')
config.property.pop('validator') assert await cfg.option('test1').value.get() == 1
cfg = get_config(config, config_type) await config.property.pop('validator')
cfg.option('test1').value.set('yes') cfg = await get_config(config, config_type)
assert cfg.option('test1').value.get() == 'yes' await cfg.option('test1').value.set('yes')
cfg.property.add('validator') assert await cfg.option('test1').value.get() == 'yes'
raises(ValueError, "cfg.option('test1').value.get()") await cfg.property.add('validator')
cfg.option('test1').value.reset() with pytest.raises(ValueError):
assert cfg.option('test1').value.get() is None await cfg.option('test1').value.get()
await cfg.option('test1').value.reset()
assert await cfg.option('test1').value.get() is None
def test_subconfig(): @pytest.mark.asyncio
async def test_subconfig():
i = IntOption('i', '') i = IntOption('i', '')
o = OptionDescription('val', '', [i]) o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o]) o2 = OptionDescription('val', '', [o])
c = Config(o2) cfg = await Config(o2)
c cfg
raises(TypeError, "SubConfig(i, weakref.ref(c))") with pytest.raises(TypeError):
await SubConfig(i, weakref.ref(cfg))
def test_config_subconfig(): @pytest.mark.asyncio
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])
conf1 = Config(od2, session_id='conf1') cfg = await Config(od2, session_id='conf1')
raises(ConfigError, "conf2 = Config(od1, session_id='conf2')") with pytest.raises(ConfigError):
conf2 = await Config(od1, session_id='conf2')
def test_config_invalidsession(): @pytest.mark.asyncio
async def test_config_invalidsession():
i = IntOption('i', '') i = IntOption('i', '')
o = OptionDescription('val', '', [i]) o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o]) o2 = OptionDescription('val', '', [o])
raises(ValueError, 'Config(o2, session_id=2)') with pytest.raises(ValueError):
await Config(o2, session_id=2)
def test_config_od_name(config_type): @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])
c = Config(o2) cfg = await Config(o2)
c = get_config(c, config_type) cfg = await get_config(cfg, config_type)
assert c.option('val.i').option.name() == 'i' assert await cfg.option('val.i').option.name() == 'i'
assert c.option('val.s').option.name() == 's' assert await cfg.option('val.s').option.name() == 's'
assert c.option('val.s').option.name(follow_symlink=True) == 'i' assert await cfg.option('val.s').option.name(follow_symlink=True) == 'i'
def test_config_od_type(config_type): @pytest.mark.asyncio
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])
c = Config(o2) cfg = await Config(o2)
c = get_config(c, config_type) cfg = await get_config(cfg, config_type)
assert c.option('val.i').option.type() == 'integer' assert await cfg.option('val.i').option.type() == 'integer'
def test_config_default(config_type): @pytest.mark.asyncio
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])
c = Config(o2) cfg = await Config(o2)
c = get_config(c, config_type) cfg = await get_config(cfg, config_type)
assert c.option('val.i').value.default() == 8 assert await cfg.option('val.i').value.default() == 8
c.option('val.i').value.set(9) await cfg.option('val.i').value.set(9)
assert c.option('val.i').value.get() == 9 assert await cfg.option('val.i').value.get() == 9
assert c.option('val.i').value.default() == 8 assert await cfg.option('val.i').value.default() == 8

View file

@ -1,5 +1,5 @@
"configuration objects global API" "configuration objects global API"
from py.test import raises import pytest
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
@ -9,11 +9,14 @@ 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 from tiramisu.error import PropertiesOptionError, ValueWarning
from tiramisu.storage import list_sessions from tiramisu.storage import list_sessions
import warnings
def teardown_function(function): def teardown_function(function):
# test_od_not_list emit a warnings because of doesn't create a Config
with warnings.catch_warnings(record=True) as w:
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
@ -49,44 +52,50 @@ def _is_same_opt(opt1, opt2):
assert opt1 == opt2 assert opt1 == opt2
def test_od_not_list(): @pytest.mark.asyncio
async def test_od_not_list():
b = BoolOption('bool', '', multi=True) b = BoolOption('bool', '', multi=True)
raises(AssertionError, "OptionDescription('od', '', b)") with pytest.raises(AssertionError):
OptionDescription('od', '', b)
def test_str(): @pytest.mark.asyncio
async def test_str():
descr = make_description() descr = make_description()
c = Config(descr) c = await Config(descr)
c # does not crash c # does not crash
def test_make_dict(config_type): @pytest.mark.asyncio
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", "", [ descr = 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)])
config = Config(descr) cfg = await Config(descr)
config.property.read_write() await cfg.property.read_write()
config.permissive.add('hidden') await cfg.permissive.add('hidden')
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
d = config.value.dict() d = await cfg.value.dict()
assert d == {"s1.a": False, "int": 42} assert d == {"s1.a": False, "int": 42}
config.option('int').value.set(43) await cfg.option('int').value.set(43)
config.option('s1.a').value.set(True) await cfg.option('s1.a').value.set(True)
d = config.value.dict() d = await cfg.value.dict()
assert d == {"s1.a": True, "int": 43} assert d == {"s1.a": True, "int": 43}
d2 = config.value.dict(flatten=True) d2 = await cfg.value.dict(flatten=True)
assert d2 == {'a': True, 'int': 43} assert d2 == {'a': True, 'int': 43}
if config_type == 'tiramisu': if config_type == 'tiramisu':
# FIXME # FIXME
raises(ValueError, 'd2 = config.value.dict(withvalue="3")') with pytest.raises(ValueError):
d = config.forcepermissive.value.dict() d2 = await cfg.value.dict(withvalue="3")
d = await cfg.forcepermissive.value.dict()
assert d == {"s1.a": True, "s1.b": False, "int": 43} assert d == {"s1.a": True, "s1.b": False, "int": 43}
def test_make_dict_with_disabled(config_type): @pytest.mark.asyncio
async def test_make_dict_with_disabled(config_type):
descr = OptionDescription("opt", "", [ descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
@ -95,16 +104,17 @@ 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)])
config = Config(descr) cfg = await Config(descr)
config.property.read_only() await cfg.property.read_only()
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
assert config.value.dict() == {"s1.a": False, "int": 42} assert await cfg.value.dict() == {"s1.a": False, "int": 42}
if config_type == 'tiramisu': if config_type == 'tiramisu':
assert config.forcepermissive.value.dict() == {"s1.a": False, "int": 42} assert await cfg.forcepermissive.value.dict() == {"s1.a": False, "int": 42}
assert config.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False} assert await cfg.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False}
def test_make_dict_with_disabled_withoption(): @pytest.mark.asyncio
async def test_make_dict_with_disabled_withoption():
descr = OptionDescription("opt", "", [ descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
@ -113,14 +123,15 @@ def test_make_dict_with_disabled_withoption():
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)])
config = Config(descr) cfg = await Config(descr)
config.property.read_only() await cfg.property.read_only()
assert config.value.dict(withoption="a") == {"s1.a": False} assert await cfg.value.dict(withoption="a") == {"s1.a": False}
assert config.forcepermissive.value.dict(withoption="a") == {"s1.a": False} assert await cfg.forcepermissive.value.dict(withoption="a") == {"s1.a": False}
assert config.unrestraint.value.dict(withoption="a") == {"s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False} assert await cfg.unrestraint.value.dict(withoption="a") == {"s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False}
def test_make_dict_with_disabled_in_callback(config_type): @pytest.mark.asyncio
async def test_make_dict_with_disabled_in_callback(config_type):
descr = OptionDescription("opt", "", [ descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
BoolOption("a", "", default=False), BoolOption("a", "", default=False),
@ -129,14 +140,15 @@ 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)])
config = Config(descr) cfg = await Config(descr)
config.property.read_only() await cfg.property.read_only()
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
d = config.value.dict() d = await cfg.value.dict()
assert d == {"s1.a": False, "int": 42} assert d == {"s1.a": False, "int": 42}
def test_make_dict_fullpath(config_type): @pytest.mark.asyncio
async def test_make_dict_fullpath(config_type):
descr = OptionDescription("root", "", [ descr = OptionDescription("root", "", [
OptionDescription("opt", "", [ OptionDescription("opt", "", [
OptionDescription("s1", "", [ OptionDescription("s1", "", [
@ -147,249 +159,321 @@ 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)])
config = Config(descr) cfg = await Config(descr)
config.property.read_only() await cfg.property.read_only()
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
assert config.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42} assert await cfg.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
if config_type == 'tiramisu': if config_type == 'tiramisu':
# FIXME # FIXME
assert config.option('opt').value.dict() == {"s1.a": False, "int": 42} assert await cfg.option('opt').value.dict() == {"s1.a": False, "int": 42}
assert config.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42} assert await cfg.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
if config_type == 'tiramisu': if config_type == 'tiramisu':
# FIXME # FIXME
assert config.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42} assert await cfg.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42}
def test_find_in_config(): @pytest.mark.asyncio
async def test_find_in_config():
"finds option in config" "finds option in config"
descr = make_description() descr = make_description()
conf = Config(descr) cfg = await Config(descr)
conf.property.read_only() await cfg.property.read_only()
conf.permissive.add('hidden') await cfg.permissive.add('hidden')
ret = list(conf.option.find('dummy')) ret = list(await cfg.option.find('dummy'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get())
# #
ret = conf.option.find('dummy', first=True).option.get() ret_find = await cfg.option.find('dummy', first=True)
_is_same_opt(ret, conf.option('gc.dummy').option.get()) ret = await ret_find.option.get()
_is_same_opt(ret, await cfg.option('gc.dummy').option.get())
# #
ret = list(conf.option.find('float')) ret = list(await cfg.option.find('float'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.option('gc.float').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get())
_is_same_opt(ret[1].option.get(), conf.option('float').option.get()) _is_same_opt(await ret[1].option.get(), await cfg.option('float').option.get())
# #
_is_same_opt(conf.option.find('bool', first=True).option.get(), conf.option('gc.gc2.bool').option.get()) ret = await cfg.option.find('bool', first=True)
_is_same_opt(conf.option.find('bool', value=True, first=True).option.get(), conf.option('bool').option.get()) _is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get())
_is_same_opt(conf.option.find('dummy', first=True).option.get(), conf.option('gc.dummy').option.get()) ret = await cfg.option.find('bool', value=True, first=True)
_is_same_opt(conf.option.find('float', first=True).option.get(), conf.option('gc.float').option.get()) _is_same_opt(await ret.option.get(), await cfg.option('bool').option.get())
ret = await cfg.option.find('dummy', first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get())
ret = await cfg.option.find('float', first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.float').option.get())
#FIXME cannot find an option without name #FIXME cannot find an option without name
#ret = conf.find(bytype=ChoiceOption) #ret = await cfg.find(bytype=ChoiceOption)
#assert len(ret) == 2 #assert len(ret) == 2
#_is_same_opt(ret[0], conf.unwrap_from_path('gc.name')) #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name'))
#_is_same_opt(ret[1], conf.unwrap_from_path('objspace')) #_is_same_opt(ret[1], await cfg.unwrap_from_path('objspace'))
# #
#_is_same_opt(conf.find_first(bytype=ChoiceOption), conf.unwrap_from_path('gc.name')) #_is_same_opt(await cfg.find_first(bytype=ChoiceOption), await cfg.unwrap_from_path('gc.name'))
#ret = conf.find(byvalue='ref') #ret = await cfg.find(byvalue='ref')
#assert len(ret) == 1 #assert len(ret) == 1
#_is_same_opt(ret[0], conf.unwrap_from_path('gc.name')) #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name'))
#_is_same_opt(conf.find_first(byvalue='ref'), conf.unwrap_from_path('gc.name')) #_is_same_opt(await cfg.find_first(byvalue='ref'), await cfg.unwrap_from_path('gc.name'))
# #
ret = list(conf.option.find('prop')) ret = list(await cfg.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get())
# #
ret = list(conf.option.find('prop', value=None)) ret = list(await cfg.option.find('prop', value=None))
assert len(ret) == 1 assert len(ret) == 1
ret = list(conf.option.find('prop')) ret = list(await cfg.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get())
# #
conf.property.read_write() await cfg.property.read_write()
raises(AttributeError, "assert conf.option.find('prop').option.get()") with pytest.raises(AttributeError):
ret = list(conf.unrestraint.option.find(name='prop')) ret = await cfg.option.find('prop')
assert await ret.option.get()
ret = list(await cfg.unrestraint.option.find(name='prop'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(ret[1].option.get(), conf.forcepermissive.option('gc.prop').option.get()) _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get())
# #
ret = list(conf.forcepermissive.option.find('prop')) ret = list(await cfg.forcepermissive.option.find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.forcepermissive.option('gc.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.forcepermissive.option('gc.prop').option.get())
# #
_is_same_opt(conf.forcepermissive.option.find('prop', first=True).option.get(), conf.forcepermissive.option('gc.prop').option.get()) ret = await cfg.forcepermissive.option.find('prop', first=True)
_is_same_opt(await ret.option.get(), await cfg.forcepermissive.option('gc.prop').option.get())
# combinaison of filters # combinaison of filters
ret = list(conf.unrestraint.option.find('prop', type=BoolOption)) ret = list(await cfg.unrestraint.option.find('prop', type=BoolOption))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(conf.unrestraint.option.find('prop', type=BoolOption, first=True).option.get(), conf.unrestraint.option('gc.gc2.prop').option.get()) ret = await 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())
# #
ret = list(conf.option.find('dummy', value=False)) ret = list(await cfg.option.find('dummy', value=False))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get())
# #
_is_same_opt(conf.option.find('dummy', value=False, first=True).option.get(), conf.option('gc.dummy').option.get()) ret = await cfg.option.find('dummy', value=False, first=True)
#subconfig _is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get())
ret = list(conf.option('gc').find('dummy')) #subcfgig
ret = list(await cfg.option('gc').find('dummy'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get())
# #
ret = list(conf.option('gc').find('float')) ret = list(await cfg.option('gc').find('float'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.float').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get())
# #
ret = list(conf.option('gc').find('bool')) ret = list(await cfg.option('gc').find('bool'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.gc2.bool').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.gc2.bool').option.get())
_is_same_opt(conf.option('gc').find('bool', value=False, first=True).option.get(), conf.option('gc.gc2.bool').option.get()) ret = await cfg.option('gc').find('bool', value=False, first=True)
_is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get())
# #
raises(AttributeError, "assert conf.option('gc').find('bool', value=True, first=True).option.get()") with pytest.raises(AttributeError):
ret = await cfg.option('gc').find('bool', value=True, first=True)
assert await ret.option.get()
# #
raises(AttributeError, "conf.option('gc').find('wantref').option.get()") with pytest.raises(AttributeError):
ret = await cfg.option('gc').find('wantref')
await ret.option.get()
# #
ret = list(conf.unrestraint.option('gc').find('prop')) ret = list(await cfg.unrestraint.option('gc').find('prop'))
assert len(ret) == 2 assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(ret[1].option.get(), conf.forcepermissive.option('gc.prop').option.get()) _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get())
# #
conf.property.read_only() await cfg.property.read_only()
ret = list(conf.option('gc').find('prop')) ret = list(await cfg.option('gc').find('prop'))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get()) _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get())
# not OptionDescription # not OptionDescription
raises(AttributeError, "conf.option.find('gc', first=True)") with pytest.raises(AttributeError):
raises(AttributeError, "conf.option.find('gc2', first=True)") await cfg.option.find('gc', first=True)
with pytest.raises(AttributeError):
await cfg.option.find('gc2', first=True)
def test_find_multi(): @pytest.mark.asyncio
async def test_find_multi():
b = BoolOption('bool', '', multi=True, properties=('notunique',)) b = BoolOption('bool', '', multi=True, properties=('notunique',))
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
conf = Config(o) cfg = await Config(o)
# #
raises(AttributeError, "list(conf.option.find('bool', value=True))") with pytest.raises(AttributeError):
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))") list(await cfg.option.find('bool', value=True))
conf.option('bool').value.set([False]) with pytest.raises(AttributeError):
raises(AttributeError, "list(conf.option.find('bool', value=True))") list(await cfg.option.find('bool', value=True, first=True))
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))") await cfg.option('bool').value.set([False])
conf.option('bool').value.set([False, False]) with pytest.raises(AttributeError):
raises(AttributeError, "list(conf.option.find('bool', value=True))") list(await cfg.option.find('bool', value=True))
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))") with pytest.raises(AttributeError):
conf.option('bool').value.set([False, False, True]) list(await cfg.option.find('bool', value=True, first=True))
ret = list(conf.option.find('bool', value=True)) await cfg.option('bool').value.set([False, False])
with pytest.raises(AttributeError):
list(await cfg.option.find('bool', value=True))
with pytest.raises(AttributeError):
list(await cfg.option.find('bool', value=True, first=True))
await cfg.option('bool').value.set([False, False, True])
ret = list(await cfg.option.find('bool', value=True))
assert len(ret) == 1 assert len(ret) == 1
_is_same_opt(ret[0].option.get(), b) _is_same_opt(await ret[0].option.get(), b)
_is_same_opt(conf.option.find('bool', value=True, first=True).option.get(), b) ret = await cfg.option.find('bool', value=True, first=True)
_is_same_opt(await ret.option.get(), b)
def test_does_not_find_in_config(): @pytest.mark.asyncio
async def test_does_not_find_in_config():
descr = make_description() descr = make_description()
conf = Config(descr) cfg = await Config(descr)
raises(AttributeError, "list(conf.option.find('IDontExist'))") with pytest.raises(AttributeError):
list(await cfg.option.find('IDontExist'))
def test_filename(config_type): @pytest.mark.asyncio
async def test_filename(config_type):
a = FilenameOption('a', '') a = FilenameOption('a', '')
o = OptionDescription('o', '', [a]) o = OptionDescription('o', '', [a])
cfg = Config(o) cfg = await Config(o)
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
cfg.option('a').value.set('/') await cfg.option('a').value.set('/')
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/')
cfg.option('a').value.set('/tmp/text.txt') await cfg.option('a').value.set('/tmp/text.txt')
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/')
cfg.option('a').value.set('tmp/text.txt') await cfg.option('a').value.set('tmp/text.txt')
raises(ValueError, "cfg.option('a').value.set('/tmp/with space.txt')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('/tmp/with$.txt')") await cfg.option('a').value.set('/tmp/with space.txt')
with pytest.raises(ValueError):
await cfg.option('a').value.set('/tmp/with$.txt')
def test_invalid_option(): @pytest.mark.asyncio
async def test_invalid_option():
ChoiceOption('a', '', ('1', '2')) ChoiceOption('a', '', ('1', '2'))
raises(TypeError, "ChoiceOption('a', '', [1, 2])") with pytest.raises(TypeError):
raises(TypeError, "ChoiceOption('a', '', 1)") ChoiceOption('a', '', [1, 2])
raises(ValueError, "ChoiceOption('a', '', (1,), 3)") with pytest.raises(TypeError):
ChoiceOption('a', '', 1)
with pytest.raises(ValueError):
ChoiceOption('a', '', (1,), 3)
FloatOption('a', '') FloatOption('a', '')
raises(ValueError, "FloatOption('a', '', 'string')") with pytest.raises(ValueError):
FloatOption('a', '', 'string')
StrOption('a', '') StrOption('a', '')
raises(ValueError, "StrOption('a', '', 1)") with pytest.raises(ValueError):
StrOption('a', '', 1)
u = StrOption('a', '') u = StrOption('a', '')
SymLinkOption('a', u) SymLinkOption('a', u)
raises(ValueError, "SymLinkOption('a', 'string')") with pytest.raises(ValueError):
SymLinkOption('a', 'string')
IPOption('a', '') IPOption('a', '')
raises(ValueError, "IPOption('a', '', 1)") with pytest.raises(ValueError):
raises(ValueError, "IPOption('a', '', 'string')") IPOption('a', '', 1)
with pytest.raises(ValueError):
IPOption('a', '', 'string')
PortOption('a', '') PortOption('a', '')
raises(ValueError, "PortOption('a', '', 'string')") with pytest.raises(ValueError):
raises(ValueError, "PortOption('a', '', '11:12:13', allow_range=True)") PortOption('a', '', 'string')
raises(ValueError, "PortOption('a', '', 11111111111111111111)") with pytest.raises(ValueError):
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False)") PortOption('a', '', '11:12:13', allow_range=True)
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True)") with pytest.raises(ValueError):
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True)") PortOption('a', '', 11111111111111111111)
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True)") with pytest.raises(ValueError):
raises(ValueError, "PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False)") PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False)
with pytest.raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True)
with pytest.raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True)
with pytest.raises(ValueError):
PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True)
with pytest.raises(ValueError):
PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False)
NetworkOption('a', '') NetworkOption('a', '')
raises(ValueError, "NetworkOption('a', '', 'string')") with pytest.raises(ValueError):
NetworkOption('a', '', 'string')
NetmaskOption('a', '') NetmaskOption('a', '')
raises(ValueError, "NetmaskOption('a', '', 'string')") with pytest.raises(ValueError):
NetmaskOption('a', '', 'string')
BroadcastOption('a', '') BroadcastOption('a', '')
raises(ValueError, "BroadcastOption('a', '', 'string')") with pytest.raises(ValueError):
BroadcastOption('a', '', 'string')
DomainnameOption('a', '') DomainnameOption('a', '')
raises(ValueError, "DomainnameOption('a', '', 'string')") with pytest.raises(ValueError):
raises(ValueError, "DomainnameOption('a', '', type='string')") DomainnameOption('a', '', 'string')
raises(ValueError, "DomainnameOption('a', '', allow_ip='string')") with pytest.raises(ValueError):
raises(ValueError, "DomainnameOption('a', '', allow_without_dot='string')") DomainnameOption('a', '', type='string')
raises(ValueError, "DomainnameOption('a', '', 1)") with pytest.raises(ValueError):
DomainnameOption('a', '', allow_ip='string')
with pytest.raises(ValueError):
DomainnameOption('a', '', allow_without_dot='string')
with pytest.raises(ValueError):
DomainnameOption('a', '', 1)
# #
ChoiceOption('a', '', (1,), multi=True, default_multi=1) ChoiceOption('a', '', (1,), multi=True, default_multi=1)
raises(ValueError, "ChoiceOption('a', '', (1,), default_multi=1)") with pytest.raises(ValueError):
raises(ValueError, "ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2)") ChoiceOption('a', '', (1,), default_multi=1)
raises(ValueError, "FloatOption('a', '', multi=True, default_multi='string')") with pytest.raises(ValueError):
raises(ValueError, "StrOption('a', '', multi=True, default_multi=1)") ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2)
raises(ValueError, "IPOption('a', '', multi=True, default_multi=1)") with pytest.raises(ValueError):
raises(ValueError, "IPOption('a', '', multi=True, default_multi='string')") FloatOption('a', '', multi=True, default_multi='string')
raises(ValueError, "PortOption('a', '', multi=True, default_multi='string')") with pytest.raises(ValueError):
raises(ValueError, "PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True)") StrOption('a', '', multi=True, default_multi=1)
raises(ValueError, "PortOption('a', '', multi=True, default_multi=11111111111111111111)") with pytest.raises(ValueError):
raises(ValueError, "NetworkOption('a', '', multi=True, default_multi='string')") IPOption('a', '', multi=True, default_multi=1)
raises(ValueError, "NetmaskOption('a', '', multi=True, default_multi='string')") with pytest.raises(ValueError):
raises(ValueError, "BroadcastOption('a', '', multi=True, default_multi='string')") IPOption('a', '', multi=True, default_multi='string')
raises(ValueError, "DomainnameOption('a', '', multi=True, default_multi='string')") with pytest.raises(ValueError):
raises(ValueError, "DomainnameOption('a', '', multi=True, default_multi=1)") PortOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError):
PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True)
with pytest.raises(ValueError):
PortOption('a', '', multi=True, default_multi=11111111111111111111)
with pytest.raises(ValueError):
NetworkOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError):
NetmaskOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError):
BroadcastOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError):
DomainnameOption('a', '', multi=True, default_multi='string')
with pytest.raises(ValueError):
DomainnameOption('a', '', multi=True, default_multi=1)
def test_help(): @pytest.mark.asyncio
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])
cfg = Config(od2) cfg = await 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)
#FIXMEcfg.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)
def test_config_reset(): @pytest.mark.asyncio
async def test_config_reset():
descr = make_description() descr = make_description()
c = Config(descr) cfg = await Config(descr)
c.owner.set('test') await cfg.owner.set('test')
assert c.owner.get() == 'test' assert await cfg.owner.get() == 'test'
assert not c.option('gc.gc2.bool').value.get() assert not await cfg.option('gc.gc2.bool').value.get()
assert not c.option('boolop').property.get() assert not await cfg.option('boolop').property.get()
assert not c.option('boolop').permissive.get() assert not await cfg.option('boolop').permissive.get()
assert not c.option('wantref').information.get('info', None) assert not await cfg.option('wantref').information.get('info', None)
# #
c.option('gc.gc2.bool').value.set(True) await cfg.option('gc.gc2.bool').value.set(True)
c.option('boolop').property.add('test') await cfg.option('boolop').property.add('test')
c.option('float').permissive.set(frozenset(['test'])) await cfg.option('float').permissive.set(frozenset(['test']))
c.option('wantref').information.set('info', 'info') await cfg.option('wantref').information.set('info', 'info')
assert c.option('gc.gc2.bool').value.get() assert await cfg.option('gc.gc2.bool').value.get()
assert c.option('boolop').property.get() assert await cfg.option('boolop').property.get()
assert c.option('float').permissive.get() assert await cfg.option('float').permissive.get()
assert c.option('wantref').information.get('info', None) assert await cfg.option('wantref').information.get('info', None)
# #
assert c.owner.get() == 'test' assert await cfg.owner.get() == 'test'
c.config.reset() await cfg.config.reset()
assert c.owner.get() == 'test' assert await cfg.owner.get() == 'test'
assert not c.option('gc.gc2.bool').value.get() assert not await cfg.option('gc.gc2.bool').value.get()
assert not c.option('boolop').property.get() assert not await cfg.option('boolop').property.get()
assert not c.option('float').permissive.get() assert not await cfg.option('float').permissive.get()
assert not c.option('wantref').information.get('info', None) assert not await cfg.option('wantref').information.get('info', None)

View file

@ -3,7 +3,7 @@ do_autopath()
from .config import config_type, get_config, value_list, global_owner from .config import config_type, get_config, value_list, global_owner
import warnings, sys import warnings, sys
from py.test import raises 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
@ -15,65 +15,78 @@ def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_domainname(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('a', '', [d, f, g, h])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
# #
cfg.option('d').value.set('toto.com') await cfg.option('d').value.set('toto.com')
raises(ValueError, "cfg.option('d').value.set('toto')") with pytest.raises(ValueError):
cfg.option('d').value.set('toto3.com') await cfg.option('d').value.set('toto')
raises(ValueError, "cfg.option('d').value.set('toto_super.com')") await cfg.option('d').value.set('toto3.com')
cfg.option('d').value.set('toto-.com') with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('toto..com')") await cfg.option('d').value.set('toto_super.com')
await cfg.option('d').value.set('toto-.com')
with pytest.raises(ValueError):
await cfg.option('d').value.set('toto..com')
# #
cfg.option('f').value.set('toto.com') await cfg.option('f').value.set('toto.com')
cfg.option('f').value.set('toto') await cfg.option('f').value.set('toto')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')") with pytest.raises(ValueError):
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
raises(ValueError, "cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien')") await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
cfg.option('f').value.set('d') with pytest.raises(ValueError):
cfg.option('f').value.set('d.t') await cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien')
await cfg.option('f').value.set('d')
await cfg.option('f').value.set('d.t')
# #
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('f').value.set('192.168.1.1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('f').value.set('192.168.1.0/24')") await cfg.option('f').value.set('192.168.1.1')
with pytest.raises(ValueError):
await cfg.option('f').value.set('192.168.1.0/24')
# #
cfg.option('g').value.set('toto.com') await cfg.option('g').value.set('toto.com')
cfg.option('g').value.set('192.168.1.0') await cfg.option('g').value.set('192.168.1.0')
cfg.option('g').value.set('192.168.1.29') await cfg.option('g').value.set('192.168.1.29')
raises(ValueError, "cfg.option('g').value.set('192.168.1.0/24')") with pytest.raises(ValueError):
await cfg.option('g').value.set('192.168.1.0/24')
# #
cfg.option('h').value.set('toto.com') await cfg.option('h').value.set('toto.com')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('h').value.set('192.168.1.0')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('h').value.set('192.168.1.29')") await cfg.option('h').value.set('192.168.1.0')
with pytest.raises(ValueError):
await cfg.option('h').value.set('192.168.1.29')
# it's a network address # it's a network address
cfg.option('h').value.set('192.168.1.0/24') await cfg.option('h').value.set('192.168.1.0/24')
# but not here # but not here
raises(ValueError, "cfg.option('h').value.set('192.168.1.1/24')") with pytest.raises(ValueError):
await cfg.option('h').value.set('192.168.1.1/24')
def test_domainname_upper(config_type): @pytest.mark.asyncio
async def test_domainname_upper(config_type):
d = DomainnameOption('d', '') d = DomainnameOption('d', '')
od = OptionDescription('a', '', [d]) od = OptionDescription('a', '', [d])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('d').value.set('toto.com') await 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:
cfg.option('d').value.set('TOTO.COM') await 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
@ -82,7 +95,7 @@ def test_domainname_upper(config_type):
assert has_error is True assert has_error is True
has_error = False has_error = False
try: try:
cfg.option('d').value.set('toTo.com') await 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
@ -91,129 +104,154 @@ def test_domainname_upper(config_type):
assert has_error is True assert has_error is True
def test_domainname_warning(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('a', '', [d, f, g])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('d').value.set('toto.com') await cfg.option('d').value.set('toto.com')
raises(ValueError, "cfg.option('d').value.set('toto')") with pytest.raises(ValueError):
cfg.option('d').value.set('toto3.com') await cfg.option('d').value.set('toto')
await 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:
cfg.option('d').value.set('toto_super.com') await 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:
cfg.option('d').value.set('toto-.com') await cfg.option('d').value.set('toto-.com')
assert len(w) == 0 assert len(w) == 0
raises(ValueError, "cfg.option('d').value.set('toto..com')") with pytest.raises(ValueError):
await cfg.option('d').value.set('toto..com')
# #
cfg.option('f').value.set('toto.com') await cfg.option('f').value.set('toto.com')
cfg.option('f').value.set('toto') await cfg.option('f').value.set('toto')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')") with pytest.raises(ValueError):
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx')") with pytest.raises(ValueError):
cfg.option('f').value.set('d') await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx')
cfg.option('f').value.set('d.t') await cfg.option('f').value.set('d')
await cfg.option('f').value.set('d.t')
# #
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('f').value.set('192.168.1.1')") with pytest.raises(ValueError):
cfg.option('g').value.set('toto.com') await cfg.option('f').value.set('192.168.1.1')
cfg.option('g').value.set('192.168.1.0') await cfg.option('g').value.set('toto.com')
cfg.option('g').value.set('192.168.1.29') await cfg.option('g').value.set('192.168.1.0')
await cfg.option('g').value.set('192.168.1.29')
def test_special_domain_name(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('a', '', [d, e])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('d').value.set('1toto.com') await cfg.option('d').value.set('1toto.com')
cfg.option('d').value.set('123toto.com') await cfg.option('d').value.set('123toto.com')
cfg.option('e').value.set('toto') await cfg.option('e').value.set('toto')
cfg.option('e').value.set('1toto') await cfg.option('e').value.set('1toto')
def test_domainname_netbios(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('a', '', [d, e])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('d').value.set('toto.com')") with pytest.raises(ValueError):
cfg.option('d').value.set('toto') await cfg.option('d').value.set('toto.com')
raises(ValueError, "cfg.option('d').value.set('domainnametoolong')") await cfg.option('d').value.set('toto')
with pytest.raises(ValueError):
await cfg.option('d').value.set('domainnametoolong')
def test_domainname_hostname(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('a', '', [d, e])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('d').value.set('toto.com')") with pytest.raises(ValueError):
cfg.option('d').value.set('toto') await cfg.option('d').value.set('toto.com')
cfg.option('d').value.set('domainnametoolong') await cfg.option('d').value.set('toto')
await cfg.option('d').value.set('domainnametoolong')
def test_email(config_type): @pytest.mark.asyncio
async def test_email(config_type):
e = EmailOption('e', '') e = EmailOption('e', '')
od = OptionDescription('a', '', [e]) od = OptionDescription('a', '', [e])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('e').value.set('foo-bar.baz@example.com') await cfg.option('e').value.set('foo-bar.baz@example.com')
cfg.option('e').value.set('root@foo.com') await cfg.option('e').value.set('root@foo.com')
cfg.option('e').value.set('root@domain') await cfg.option('e').value.set('root@domain')
raises(ValueError, "cfg.option('e').value.set(1)") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('e').value.set('root')") await cfg.option('e').value.set(1)
raises(ValueError, "cfg.option('e').value.set('root[]@domain')") with pytest.raises(ValueError):
await cfg.option('e').value.set('root')
with pytest.raises(ValueError):
await cfg.option('e').value.set('root[]@domain')
def test_url(config_type): @pytest.mark.asyncio
async def test_url(config_type):
u = URLOption('u', '') u = URLOption('u', '')
od = OptionDescription('a', '', [u]) od = OptionDescription('a', '', [u])
cfg = Config(od) cfg = await Config(od)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('u').value.set('http://foo.com') await cfg.option('u').value.set('http://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/') await cfg.option('u').value.set('https://foo.com/')
raises(ValueError, "cfg.option('u').value.set(1)") with pytest.raises(ValueError):
await cfg.option('u').value.set(1)
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('u').value.set('ftp://foo.com')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('u').value.set('foo.com')") await cfg.option('u').value.set('ftp://foo.com')
raises(ValueError, "cfg.option('u').value.set(':/foo.com')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('u').value.set('foo.com/http://')") await cfg.option('u').value.set('foo.com')
cfg.option('u').value.set('https://foo.com/index.html') with pytest.raises(ValueError):
cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2') await cfg.option('u').value.set(':/foo.com')
with pytest.raises(ValueError):
await cfg.option('u').value.set('foo.com/http://')
await 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')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('u').value.set('https://foo.com/index\\n.html')") with pytest.raises(ValueError):
cfg.option('u').value.set('https://foo.com:8443') await cfg.option('u').value.set('https://foo.com/index\\n.html')
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/index.html') await cfg.option('u').value.set('https://foo.com:8443/')
await cfg.option('u').value.set('https://foo.com:8443/index.html')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('u').value.set('https://foo.com:84438989')") with pytest.raises(ValueError):
cfg.option('u').value.set('https://foo.com:8443/INDEX') await cfg.option('u').value.set('https://foo.com:84438989')
await cfg.option('u').value.set('https://foo.com:8443/INDEX')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('u').value.set('https://FOO.COM:8443')") with pytest.raises(ValueError):
await cfg.option('u').value.set('https://FOO.COM:8443')

View file

@ -3,7 +3,7 @@ do_autopath()
from .config import config_type, get_config, value_list, global_owner from .config import config_type, get_config, value_list, global_owner
import warnings import warnings
from py.test import raises 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
@ -14,157 +14,198 @@ def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_ip(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [a, b, d])
config = Config(od) cfg = await Config(od)
config = get_config(config, config_type) cfg = await get_config(cfg, config_type)
config.option('a').value.set('192.168.1.1') await cfg.option('a').value.set('192.168.1.1')
config.option('a').value.set('192.168.1.0') await cfg.option('a').value.set('192.168.1.0')
config.option('a').value.set('88.88.88.88') await cfg.option('a').value.set('88.88.88.88')
config.option('a').value.set('0.0.0.0') await cfg.option('a').value.set('0.0.0.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "config.option('a').value.set('255.255.255.0')") with pytest.raises(ValueError):
config.option('b').value.set('192.168.1.1') await cfg.option('a').value.set('255.255.255.0')
config.option('b').value.set('192.168.1.0') await cfg.option('b').value.set('192.168.1.1')
await cfg.option('b').value.set('192.168.1.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "config.option('b').value.set('88.88.88.88')") with pytest.raises(ValueError):
config.option('b').value.set('0.0.0.0') await cfg.option('b').value.set('88.88.88.88')
await cfg.option('b').value.set('0.0.0.0')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "config.option('b').value.set('255.255.255.0')") with pytest.raises(ValueError):
raises(ValueError, "config.option('a').value.set('333.0.1.20')") await cfg.option('b').value.set('255.255.255.0')
with pytest.raises(ValueError):
await cfg.option('a').value.set('333.0.1.20')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "IPOption('a', 'ip', default='192.000.023.01')") with pytest.raises(ValueError):
IPOption('a', 'ip', default='192.000.023.01')
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
config.option('d').value.set('88.88.88.88') await cfg.option('d').value.set('88.88.88.88')
assert len(w) == 1 assert len(w) == 1
def test_ip_cidr(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [b, c])
config = Config(od) cfg = await Config(od)
raises(ValueError, "config.option('b').value.set('192.168.1.1')") with pytest.raises(ValueError):
config.option('b').value.set('192.168.1.1/24') await cfg.option('b').value.set('192.168.1.1')
raises(ValueError, "config.option('b').value.set('192.168.1.1/32')") await cfg.option('b').value.set('192.168.1.1/24')
with pytest.raises(ValueError):
await cfg.option('b').value.set('192.168.1.1/32')
# #
config.option('c').value.set('192.168.1.1') await cfg.option('c').value.set('192.168.1.1')
raises(ValueError, "config.option('c').value.set('192.168.1.1/24')") with pytest.raises(ValueError):
raises(ValueError, "config.option('c').value.set('192.168.1.1/32')") await cfg.option('c').value.set('192.168.1.1/24')
with pytest.raises(ValueError):
await cfg.option('c').value.set('192.168.1.1/32')
def test_ip_default(): @pytest.mark.asyncio
async def test_ip_default():
a = IPOption('a', '', '88.88.88.88') a = IPOption('a', '', '88.88.88.88')
od = OptionDescription('od', '', [a]) od = OptionDescription('od', '', [a])
c = Config(od) cfg = await Config(od)
c.option('a').value.get() == '88.88.88.88' await cfg.option('a').value.get() == '88.88.88.88'
def test_ip_reserved(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [a, b, c])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
cfg = Config(od) cfg = await Config(od)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('a').value.set('240.94.1.1')") with pytest.raises(ValueError):
cfg.option('b').value.set('240.94.1.1') await cfg.option('a').value.set('240.94.1.1')
await 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:
cfg.option('c').value.set('240.94.1.1') await cfg.option('c').value.set('240.94.1.1')
assert len(w) == 1 assert len(w) == 1
def test_network(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [a, b])
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
cfg = Config(od) cfg = await Config(od)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('a').value.set('192.168.1.1') await cfg.option('a').value.set('192.168.1.1')
cfg.option('a').value.set('192.168.1.0') await cfg.option('a').value.set('192.168.1.0')
cfg.option('a').value.set('88.88.88.88') await cfg.option('a').value.set('88.88.88.88')
cfg.option('a').value.set('0.0.0.0') await cfg.option('a').value.set('0.0.0.0')
raises(ValueError, "cfg.option('a').value.set(1)") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('1.1.1.1.1')") await cfg.option('a').value.set(1)
with pytest.raises(ValueError):
await cfg.option('a').value.set('1.1.1.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('a').value.set('255.255.255.0')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('192.168.001.0')") await cfg.option('a').value.set('255.255.255.0')
raises(ValueError, "cfg.option('a').value.set('333.168.1.1')") with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.001.0')
with pytest.raises(ValueError):
await 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:
cfg.option('b').value.set('255.255.255.0') await cfg.option('b').value.set('255.255.255.0')
assert len(w) == 1 assert len(w) == 1
def test_network_cidr(config_type): @pytest.mark.asyncio
async def test_network_cidr(config_type):
a = NetworkOption('a', '', cidr=True) a = NetworkOption('a', '', cidr=True)
od = OptionDescription('od', '', [a]) od = OptionDescription('od', '', [a])
cfg = Config(od) cfg = await Config(od)
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
cfg.option('a').value.set('192.168.1.1/32') await cfg.option('a').value.set('192.168.1.1/32')
cfg.option('a').value.set('192.168.1.0/24') await cfg.option('a').value.set('192.168.1.0/24')
cfg.option('a').value.set('88.88.88.88/32') await cfg.option('a').value.set('88.88.88.88/32')
cfg.option('a').value.set('0.0.0.0/0') await cfg.option('a').value.set('0.0.0.0/0')
raises(ValueError, "cfg.option('a').value.set('192.168.1.1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('192.168.1.1/24')") await cfg.option('a').value.set('192.168.1.1')
raises(ValueError, "cfg.option('a').value.set('2001:db00::0/24')") with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1/24')
with pytest.raises(ValueError):
await cfg.option('a').value.set('2001:db00::0/24')
def test_network_invalid(): @pytest.mark.asyncio
raises(ValueError, "NetworkOption('a', '', default='toto')") async def test_network_invalid():
with pytest.raises(ValueError):
NetworkOption('a', '', default='toto')
def test_netmask(config_type): @pytest.mark.asyncio
async def test_netmask(config_type):
a = NetmaskOption('a', '') a = NetmaskOption('a', '')
od = OptionDescription('od', '', [a]) od = OptionDescription('od', '', [a])
cfg = Config(od) cfg = await Config(od)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('a').value.set('192.168.1.1.1')") with pytest.raises(ValueError):
await cfg.option('a').value.set('192.168.1.1.1')
if config_type != 'tiramisu-api': if config_type != 'tiramisu-api':
# FIXME # FIXME
raises(ValueError, "cfg.option('a').value.set('192.168.1.1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('192.168.1.0')") await cfg.option('a').value.set('192.168.1.1')
raises(ValueError, "cfg.option('a').value.set('88.88.88.88')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('255.255.255.000')") await cfg.option('a').value.set('192.168.1.0')
raises(ValueError, "cfg.option('a').value.set(2)") with pytest.raises(ValueError):
cfg.option('a').value.set('0.0.0.0') await cfg.option('a').value.set('88.88.88.88')
cfg.option('a').value.set('255.255.255.0') with pytest.raises(ValueError):
await cfg.option('a').value.set('255.255.255.000')
with pytest.raises(ValueError):
await cfg.option('a').value.set(2)
await cfg.option('a').value.set('0.0.0.0')
await cfg.option('a').value.set('255.255.255.0')
def test_broadcast(config_type): @pytest.mark.asyncio
async def test_broadcast(config_type):
a = BroadcastOption('a', '') a = BroadcastOption('a', '')
od = OptionDescription('od', '', [a]) od = OptionDescription('od', '', [a])
cfg = Config(od) cfg = await Config(od)
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('a').value.set('192.168.1.255.1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('192.168.001.255')") await cfg.option('a').value.set('192.168.1.255.1')
raises(ValueError, "cfg.option('a').value.set('192.168.0.300')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set(1)") await cfg.option('a').value.set('192.168.001.255')
raises(ValueError, "cfg.option('a').value.set(2)") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('2001:db8::1')") await cfg.option('a').value.set('192.168.0.300')
cfg.option('a').value.set('0.0.0.0') with pytest.raises(ValueError):
cfg.option('a').value.set('255.255.255.0') await cfg.option('a').value.set(1)
with pytest.raises(ValueError):
await cfg.option('a').value.set(2)
with pytest.raises(ValueError):
await cfg.option('a').value.set('2001:db8::1')
await cfg.option('a').value.set('0.0.0.0')
await cfg.option('a').value.set('255.255.255.0')
def test_port(config_type): @pytest.mark.asyncio
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)
@ -172,63 +213,85 @@ def test_port(config_type):
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]) od = OptionDescription('od', '', [a, b, c, d, e, f])
cfg = Config(od) cfg = await Config(od)
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('a').value.set('0')") with pytest.raises(ValueError):
cfg.option('a').value.set('1') await cfg.option('a').value.set('0')
cfg.option('a').value.set('1023') await cfg.option('a').value.set('1')
cfg.option('a').value.set('1024') await cfg.option('a').value.set('1023')
cfg.option('a').value.set('49151') await cfg.option('a').value.set('1024')
raises(ValueError, "cfg.option('a').value.set('49152')") await cfg.option('a').value.set('49151')
raises(ValueError, "cfg.option('a').value.set('65535')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('65536')") await cfg.option('a').value.set('49152')
with pytest.raises(ValueError):
await cfg.option('a').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('a').value.set('65536')
cfg.option('b').value.set('0') await cfg.option('b').value.set('0')
cfg.option('b').value.set('1') await cfg.option('b').value.set('1')
cfg.option('b').value.set('1023') await cfg.option('b').value.set('1023')
cfg.option('b').value.set('1024') await cfg.option('b').value.set('1024')
cfg.option('b').value.set('49151') await cfg.option('b').value.set('49151')
raises(ValueError, "cfg.option('b').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('b').value.set('65535')") await cfg.option('b').value.set('49152')
raises(ValueError, "cfg.option('b').value.set('65536')") with pytest.raises(ValueError):
await cfg.option('b').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('b').value.set('65536')
cfg.option('c').value.set('0') await cfg.option('c').value.set('0')
cfg.option('c').value.set('1') await cfg.option('c').value.set('1')
cfg.option('c').value.set('1023') await cfg.option('c').value.set('1023')
raises(ValueError, "cfg.option('c').value.set('1024')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('c').value.set('49151')") await cfg.option('c').value.set('1024')
raises(ValueError, "cfg.option('c').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('c').value.set('65535')") await cfg.option('c').value.set('49151')
raises(ValueError, "cfg.option('c').value.set('65536')") with pytest.raises(ValueError):
await cfg.option('c').value.set('49152')
with pytest.raises(ValueError):
await cfg.option('c').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('c').value.set('65536')
cfg.option('d').value.set('0') await cfg.option('d').value.set('0')
raises(ValueError, "cfg.option('d').value.set('1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('1023')") await cfg.option('d').value.set('1')
raises(ValueError, "cfg.option('d').value.set('1024')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('49151')") await cfg.option('d').value.set('1023')
raises(ValueError, "cfg.option('d').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('65535')") await cfg.option('d').value.set('1024')
raises(ValueError, "cfg.option('d').value.set('65536')") with pytest.raises(ValueError):
await cfg.option('d').value.set('49151')
with pytest.raises(ValueError):
await cfg.option('d').value.set('49152')
with pytest.raises(ValueError):
await cfg.option('d').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('d').value.set('65536')
cfg.option('e').value.set('0') await cfg.option('e').value.set('0')
cfg.option('e').value.set('1') await cfg.option('e').value.set('1')
cfg.option('e').value.set('1023') await cfg.option('e').value.set('1023')
cfg.option('e').value.set('1024') await cfg.option('e').value.set('1024')
cfg.option('e').value.set('49151') await cfg.option('e').value.set('49151')
cfg.option('e').value.set('49152') await cfg.option('e').value.set('49152')
cfg.option('e').value.set('65535') await cfg.option('e').value.set('65535')
raises(ValueError, "cfg.option('f').value.set('0')") with pytest.raises(ValueError):
cfg.option('f').value.set('1') await cfg.option('f').value.set('0')
cfg.option('f').value.set('1023') await cfg.option('f').value.set('1')
cfg.option('f').value.set('1024') await cfg.option('f').value.set('1023')
cfg.option('f').value.set('49151') await cfg.option('f').value.set('1024')
cfg.option('f').value.set('49152') await cfg.option('f').value.set('49151')
cfg.option('f').value.set('65535') await cfg.option('f').value.set('49152')
raises(ValueError, "cfg.option('f').value.set('65536')") await cfg.option('f').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('f').value.set('65536')
def test_port_range(config_type): @pytest.mark.asyncio
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)
@ -236,72 +299,102 @@ def test_port_range(config_type):
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]) od = OptionDescription('od', '', [a, b, c, d, e, f])
cfg = Config(od) cfg = await Config(od)
# FIXME cfg = get_config(cfg, config_type) # FIXME cfg = await get_config(cfg, config_type)
raises(ValueError, "cfg.option('a').value.set('0')") with pytest.raises(ValueError):
cfg.option('a').value.set('1') await cfg.option('a').value.set('0')
cfg.option('a').value.set('1023') await cfg.option('a').value.set('1')
cfg.option('a').value.set('1024') await cfg.option('a').value.set('1023')
cfg.option('a').value.set('49151') await cfg.option('a').value.set('1024')
raises(ValueError, "cfg.option('a').value.set('49152')") await cfg.option('a').value.set('49151')
raises(ValueError, "cfg.option('a').value.set('65535')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('65536')") await cfg.option('a').value.set('49152')
cfg.option('a').value.set('1:49151') with pytest.raises(ValueError):
raises(ValueError, "cfg.option('a').value.set('0:49151')") await cfg.option('a').value.set('65535')
raises(ValueError, "cfg.option('a').value.set('1:49152')") with pytest.raises(ValueError):
await cfg.option('a').value.set('65536')
await cfg.option('a').value.set('1:49151')
with pytest.raises(ValueError):
await cfg.option('a').value.set('0:49151')
with pytest.raises(ValueError):
await cfg.option('a').value.set('1:49152')
cfg.option('b').value.set('0') await cfg.option('b').value.set('0')
cfg.option('b').value.set('1') await cfg.option('b').value.set('1')
cfg.option('b').value.set('1023') await cfg.option('b').value.set('1023')
cfg.option('b').value.set('1024') await cfg.option('b').value.set('1024')
cfg.option('b').value.set('49151') await cfg.option('b').value.set('49151')
raises(ValueError, "cfg.option('b').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('b').value.set('65535')") await cfg.option('b').value.set('49152')
raises(ValueError, "cfg.option('b').value.set('65536')") with pytest.raises(ValueError):
cfg.option('b').value.set('0:49151') await cfg.option('b').value.set('65535')
raises(ValueError, "cfg.option('b').value.set('0:49152')") with pytest.raises(ValueError):
await cfg.option('b').value.set('65536')
await cfg.option('b').value.set('0:49151')
with pytest.raises(ValueError):
await cfg.option('b').value.set('0:49152')
cfg.option('c').value.set('0') await cfg.option('c').value.set('0')
cfg.option('c').value.set('1') await cfg.option('c').value.set('1')
cfg.option('c').value.set('1023') await cfg.option('c').value.set('1023')
raises(ValueError, "cfg.option('c').value.set('1024')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('c').value.set('49151')") await cfg.option('c').value.set('1024')
raises(ValueError, "cfg.option('c').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('c').value.set('65535')") await cfg.option('c').value.set('49151')
raises(ValueError, "cfg.option('c').value.set('65536')") with pytest.raises(ValueError):
cfg.option('c').value.set('0:1023') await cfg.option('c').value.set('49152')
raises(ValueError, "cfg.option('c').value.set('0:1024')") with pytest.raises(ValueError):
await cfg.option('c').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('c').value.set('65536')
await cfg.option('c').value.set('0:1023')
with pytest.raises(ValueError):
await cfg.option('c').value.set('0:1024')
cfg.option('d').value.set('0') await cfg.option('d').value.set('0')
raises(ValueError, "cfg.option('d').value.set('1')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('1023')") await cfg.option('d').value.set('1')
raises(ValueError, "cfg.option('d').value.set('1024')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('49151')") await cfg.option('d').value.set('1023')
raises(ValueError, "cfg.option('d').value.set('49152')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('65535')") await cfg.option('d').value.set('1024')
raises(ValueError, "cfg.option('d').value.set('65536')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('d').value.set('0:0')") await cfg.option('d').value.set('49151')
raises(ValueError, "cfg.option('d').value.set('0:1')") with pytest.raises(ValueError):
await cfg.option('d').value.set('49152')
with pytest.raises(ValueError):
await cfg.option('d').value.set('65535')
with pytest.raises(ValueError):
await cfg.option('d').value.set('65536')
with pytest.raises(ValueError):
await cfg.option('d').value.set('0:0')
with pytest.raises(ValueError):
await cfg.option('d').value.set('0:1')
cfg.option('e').value.set('0') await cfg.option('e').value.set('0')
cfg.option('e').value.set('1') await cfg.option('e').value.set('1')
cfg.option('e').value.set('1023') await cfg.option('e').value.set('1023')
cfg.option('e').value.set('1024') await cfg.option('e').value.set('1024')
cfg.option('e').value.set('49151') await cfg.option('e').value.set('49151')
cfg.option('e').value.set('49152') await cfg.option('e').value.set('49152')
cfg.option('e').value.set('65535') await cfg.option('e').value.set('65535')
cfg.option('e').value.set('0:65535') await cfg.option('e').value.set('0:65535')
raises(ValueError, "cfg.option('e').value.set('0:65536')") with pytest.raises(ValueError):
await cfg.option('e').value.set('0:65536')
raises(ValueError, "cfg.option('f').value.set('0')") with pytest.raises(ValueError):
cfg.option('f').value.set('1') await cfg.option('f').value.set('0')
cfg.option('f').value.set('1023') await cfg.option('f').value.set('1')
cfg.option('f').value.set('1024') await cfg.option('f').value.set('1023')
cfg.option('f').value.set('49151') await cfg.option('f').value.set('1024')
cfg.option('f').value.set('49152') await cfg.option('f').value.set('49151')
cfg.option('f').value.set('65535') await cfg.option('f').value.set('49152')
raises(ValueError, "cfg.option('f').value.set('65536')") await cfg.option('f').value.set('65535')
cfg.option('f').value.set('1:65535') with pytest.raises(ValueError):
cfg.option('f').value.set('3:4') await cfg.option('f').value.set('65536')
raises(ValueError, "cfg.option('f').value.set('0:65535')") await cfg.option('f').value.set('1:65535')
raises(ValueError, "cfg.option('f').value.set('4:3')") await cfg.option('f').value.set('3:4')
with pytest.raises(ValueError):
await cfg.option('f').value.set('0:65535')
with pytest.raises(ValueError):
await cfg.option('f').value.set('4:3')

View file

@ -2,6 +2,7 @@
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
import weakref import weakref
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, \
@ -20,43 +21,48 @@ def funcname(*args, **kwargs):
return value return value
def test_deref_storage(): @pytest.mark.asyncio
async def test_deref_storage():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_values()._p_) w = weakref.ref(c._config_bag.context.cfgimpl_get_values()._p_)
del(c) del(c)
assert w() is None assert w() is None
def test_deref_value(): @pytest.mark.asyncio
async def test_deref_value():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_values()) w = weakref.ref(c._config_bag.context.cfgimpl_get_values())
del(c) del(c)
assert w() is None assert w() is None
def test_deref_setting(): @pytest.mark.asyncio
async def test_deref_setting():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_settings()) w = weakref.ref(c._config_bag.context.cfgimpl_get_settings())
del(c) del(c)
assert w() is None assert w() is None
def test_deref_config(): @pytest.mark.asyncio
async def test_deref_config():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(c) w = weakref.ref(c)
del(c) del(c)
assert w() is None assert w() is None
def test_deref_option(): @pytest.mark.asyncio
async def test_deref_option():
global IS_DEREFABLE global IS_DEREFABLE
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
@ -71,7 +77,8 @@ def test_deref_option():
assert w() is None assert w() is None
def test_deref_optiondescription(): @pytest.mark.asyncio
async def test_deref_optiondescription():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
b = BoolOption('b', '') b = BoolOption('b', '')
@ -83,12 +90,13 @@ def test_deref_optiondescription():
assert w() is None assert w() is None
def test_deref_option_cache(): @pytest.mark.asyncio
async def test_deref_option_cache():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
o._build_cache() await 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
@ -96,12 +104,13 @@ def test_deref_option_cache():
assert w() is None assert w() is None
def test_deref_optiondescription_cache(): @pytest.mark.asyncio
async def test_deref_optiondescription_cache():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
o._build_cache() await 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
@ -109,12 +118,13 @@ def test_deref_optiondescription_cache():
assert w() is None assert w() is None
def test_deref_option_config(): @pytest.mark.asyncio
async def test_deref_option_config():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(b) w = weakref.ref(b)
del(b) del(b)
assert w() is not None assert w() is not None
@ -124,12 +134,13 @@ def test_deref_option_config():
assert w() is None assert w() is None
def test_deref_optiondescription_config(): @pytest.mark.asyncio
async def test_deref_optiondescription_config():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o) c = await Config(o)
w = weakref.ref(o) w = weakref.ref(o)
del(b) del(b)
assert w() is not None assert w() is not None
@ -139,13 +150,14 @@ def test_deref_optiondescription_config():
assert w() is None assert w() is None
def test_deref_validator(): @pytest.mark.asyncio
async def test_deref_validator():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return 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]) od = OptionDescription('root', '', [a, b])
cfg = Config(od) cfg = await Config(od)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(od)
@ -170,13 +182,14 @@ def test_deref_validator():
assert z() is None assert z() is None
def test_deref_callback(): @pytest.mark.asyncio
async def test_deref_callback():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return 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]) od = OptionDescription('root', '', [a, b])
cfg = Config(od) cfg = await Config(od)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(od)
@ -201,13 +214,14 @@ def test_deref_callback():
assert z() is None assert z() is None
def test_deref_symlink(): @pytest.mark.asyncio
async def test_deref_symlink():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return return
a = BoolOption("a", "", default=False) a = BoolOption("a", "", default=False)
b = SymLinkOption("b", a) b = SymLinkOption("b", a)
od = OptionDescription('root', '', [a, b]) od = OptionDescription('root', '', [a, b])
cfg = Config(od) cfg = await Config(od)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(od)
@ -232,14 +246,15 @@ def test_deref_symlink():
assert z() is None assert z() is None
def test_deref_dyn(): @pytest.mark.asyncio
async def test_deref_dyn():
if not IS_DEREFABLE: if not IS_DEREFABLE:
return 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]) od = OptionDescription('od', '', [dod, a])
cfg = Config(od) cfg = await Config(od)
w = weakref.ref(a) w = weakref.ref(a)
x = weakref.ref(b) x = weakref.ref(b)
y = weakref.ref(od) y = weakref.ref(od)

View file

@ -1,7 +1,7 @@
# coding: utf-8 # coding: utf-8
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from py.test import raises 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, \
@ -47,49 +47,52 @@ def make_description():
return descr return descr
def test_copy(): @pytest.mark.asyncio
cfg = Config(make_description()) async def test_copy():
ncfg = cfg.config.copy() cfg = await Config(make_description())
assert cfg.option('creole.general.numero_etab').value.get() == None ncfg = await cfg.config.copy()
cfg.option('creole.general.numero_etab').value.set('oui') assert await cfg.option('creole.general.numero_etab').value.get() == None
assert cfg.option('creole.general.numero_etab').value.get() == 'oui' await cfg.option('creole.general.numero_etab').value.set('oui')
assert ncfg.option('creole.general.numero_etab').value.get() == None assert await cfg.option('creole.general.numero_etab').value.get() == 'oui'
# _diff_opts(cfg.cfgimpl_get_description(), ncfg.cfgimpl_get_description()) assert await ncfg.option('creole.general.numero_etab').value.get() == None
# _diff_opts(await cfg.cfgimpl_get_description(), nawait cfg.cfgimpl_get_description())
# _diff_conf(cfg, ncfg) # _diff_conf(cfg, ncfg)
# cfg.creole.general.numero_etab = 'oui' # await cfg.creole.general.numero_etab = 'oui'
# raises(AssertionError, "_diff_conf(cfg, ncfg)") # raises(AssertionError, "_diff_conf(cfg, ncfg)")
# ncfg.creole.general.numero_etab = 'oui' # nawait cfg.creole.general.numero_etab = 'oui'
# _diff_conf(cfg, ncfg) # _diff_conf(cfg, ncfg)
def to_tuple(val): def to_tuple(val):
return tuple([tuple(v) for v in val]) return tuple([tuple(v) for v in val])
def test_copy_force_store_value(): @pytest.mark.asyncio
async def test_copy_force_store_value():
descr = make_description() descr = make_description()
conf = Config(descr) conf = await Config(descr)
conf2 = Config(descr) conf2 = await Config(descr)
assert to_tuple(conf.value.exportation()) == ((), (), (), ()) assert to_tuple(await conf.value.exportation()) == ((), (), (), ())
assert to_tuple(conf2.value.exportation()) == ((), (), (), ()) assert to_tuple(await conf2.value.exportation()) == ((), (), (), ())
# #
conf.property.read_write() await conf.property.read_write()
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(conf2.value.exportation()) == ((), (), (), ()) assert to_tuple(await conf2.value.exportation()) == ((), (), (), ())
# #
conf2.property.read_only() await conf2.property.read_only()
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
# #
conf.option('creole.general.wantref').value.set(True) await conf.option('creole.general.wantref').value.set(True)
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',)) assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',))
assert to_tuple(conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
def test_copy_force_store_value_metaconfig(): @pytest.mark.asyncio
async def test_copy_force_store_value_metaconfig():
descr = make_description() descr = make_description()
meta = MetaConfig([], optiondescription=descr) meta = await MetaConfig([], optiondescription=descr)
conf = meta.config.new(session_id='conf') conf = await meta.config.new(session_id='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 to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(meta.value.exportation()) == ((), (), (), ()) assert to_tuple(await meta.value.exportation()) == ((), (), (), ())

File diff suppressed because it is too large Load diff

View file

@ -3,12 +3,12 @@
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from py.test import raises 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, ParamContext, ParamOption, ParamValue, calc_value 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 tiramisu.storage import list_sessions
@ -79,153 +79,159 @@ def return_val3(context, value):
return value return value
def test_freeze_whole_config(): @pytest.mark.asyncio
async def test_freeze_whole_config():
descr = make_description_freeze() descr = make_description_freeze()
api = Config(descr) cfg = await Config(descr)
api.property.read_write() await cfg.property.read_write()
api.property.add('everything_frozen') await cfg.property.add('everything_frozen')
assert api.option('gc.dummy').value.get() is False assert await cfg.option('gc.dummy').value.get() is False
prop = [] prop = []
try: try:
api.option('gc.dummy').value.set(True) await 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 api.option('gc.dummy').value.get() is False assert await cfg.option('gc.dummy').value.get() is False
# #
api.property.pop('everything_frozen') await cfg.property.pop('everything_frozen')
api.option('gc.dummy').value.set(True) await cfg.option('gc.dummy').value.set(True)
assert api.option('gc.dummy').value.get() is True assert await cfg.option('gc.dummy').value.get() is True
# #
api.property.add('everything_frozen') await cfg.property.add('everything_frozen')
owners.addowner("everythingfrozen2") owners.addowner("everythingfrozen2")
prop = [] prop = []
try: try:
api.option('gc.dummy').owner.set('everythingfrozen2') await 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
def test_freeze_one_option(): @pytest.mark.asyncio
async def test_freeze_one_option():
"freeze an option " "freeze an option "
descr = make_description_freeze() descr = make_description_freeze()
api = Config(descr) cfg = await Config(descr)
api.property.read_write() await cfg.property.read_write()
#freeze only one option #freeze only one option
api.option('gc.dummy').property.add('frozen') await cfg.option('gc.dummy').property.add('frozen')
assert api.option('gc.dummy').value.get() is False assert await cfg.option('gc.dummy').value.get() is False
prop = [] prop = []
try: try:
api.option('gc.dummy').value.set(True) await 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
def test_frozen_value(): @pytest.mark.asyncio
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]) descr = OptionDescription("options", "", [s])
api = Config(descr) cfg = await Config(descr)
api.property.read_write() await cfg.property.read_write()
api.property.add('frozen') await cfg.property.add('frozen')
api.option('string').property.add('frozen') await cfg.option('string').property.add('frozen')
prop = [] prop = []
try: try:
api.option('string').value.set('egg') await 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
def test_freeze(): @pytest.mark.asyncio
async def test_freeze():
"freeze a whole configuration object" "freeze a whole configuration object"
descr = make_description_freeze() descr = make_description_freeze()
api = Config(descr) cfg = await Config(descr)
api.property.read_write() await cfg.property.read_write()
api.property.add('frozen') await cfg.property.add('frozen')
api.option('gc.name').property.add('frozen') await cfg.option('gc.name').property.add('frozen')
prop = [] prop = []
try: try:
api.option('gc.name').value.set('framework') await 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
def test_freeze_multi(): @pytest.mark.asyncio
async def test_freeze_multi():
descr = make_description_freeze() descr = make_description_freeze()
api = Config(descr) cfg = await Config(descr)
api.property.read_write() await cfg.property.read_write()
api.property.add('frozen') await cfg.property.add('frozen')
api.option('boolop').property.add('frozen') await cfg.option('boolop').property.add('frozen')
prop = [] prop = []
try: try:
api.option('boolop').value.set([True]) await 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
def test_force_store_value(): @pytest.mark.asyncio
async def test_force_store_value():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) cfg = await Config(descr)
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced')))
conf.option('wantref').value.set(True) await cfg.option('wantref').value.set(True)
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced'))) compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced')))
conf.option('wantref').value.reset() await cfg.option('wantref').value.reset()
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced')))
def test_force_store_value_leadership_follower(): @pytest.mark.asyncio
async def test_force_store_value_leadership_follower():
b = IntOption('int', 'Test int option', multi=True) b = IntOption('int', 'Test int option', multi=True)
c = StrOption('str', 'Test string option', multi=True, properties=('force_store_value',)) c = StrOption('str', 'Test string option', multi=True, properties=('force_store_value',))
descr = Leadership("int", "", [b, c]) descr = Leadership("int", "", [b, c])
raises(ConfigError, "conf = Config(descr)") with pytest.raises(ConfigError):
cfg = await Config(descr)
#def test_force_store_value_leadership(): #@pytest.mark.asyncio
#async def test_force_store_value_leadership():
# 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])
# api = Config(descr) # cfg = await Config(descr)
# assert api.value.get() == {'int': ('forced', ())} # assert await cfg.value.get() == {'int': ('forced', ())}
def test_force_store_value_leadership_sub(): @pytest.mark.asyncio
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]) odr = OptionDescription('odr', '', [descr])
api = Config(odr) cfg = await Config(odr)
compare(api.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',))) compare(await cfg.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',)))
def test_force_store_value_callback(): @pytest.mark.asyncio
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]) descr = OptionDescription("int", "", [b])
api = Config(descr) cfg = await Config(descr)
compare(api.value.exportation(), (('int',), (None,), (1,), ('forced',))) compare(await cfg.value.exportation(), (('int',), (None,), (1,), ('forced',)))
def test_force_store_value_callback_params(): @pytest.mark.asyncio
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]) descr = OptionDescription("int", "", [b])
api = Config(descr) cfg = await Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',))) compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',)))
def test_force_store_value_callback_params_2(): @pytest.mark.asyncio
b = IntOption('int', 'Test int option', Calculation(return_val3, Params(ParamContext(), {'value': ParamValue(2)})), properties=('force_store_value',)) async def test_force_store_value_callback_params_with_opt():
descr = OptionDescription("int", "", [b])
api = Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',)))
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]) descr = OptionDescription("int", "", [a, b])
api = Config(descr) cfg = await Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',))) compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',)))

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
# FIXME from .config import config_type, get_config # FIXME from .config import config_type, get_config
from py.test import raises import pytest
from tiramisu import Config from tiramisu import Config
from tiramisu import IntOption, StrOption, OptionDescription, \ from tiramisu import IntOption, StrOption, OptionDescription, \
SymLinkOption, Leadership, undefined, Calculation, Params, \ SymLinkOption, Leadership, undefined, Calculation, Params, \
@ -75,471 +75,508 @@ def make_description3():
return descr return descr
def test_mandatory_ro(): @pytest.mark.asyncio
async def test_mandatory_ro():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str1').value.get() await cfg.option('str1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str1').value.set('yes') await cfg.option('str1').value.set('yes')
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('str1').value.get() == 'yes' assert await cfg.option('str1').value.get() == 'yes'
def test_mandatory_ro_dict(): @pytest.mark.asyncio
async def test_mandatory_ro_dict():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
print(cfg.value.dict()) await cfg.value.dict()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str1').value.set('yes') await cfg.option('str1').value.set('yes')
cfg.option('unicode2').value.set('yes') await cfg.option('unicode2').value.set('yes')
cfg.property.read_only() await cfg.property.read_only()
try: try:
cfg.value.dict() await cfg.value.dict()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str3').value.set(['yes']) await cfg.option('str3').value.set(['yes'])
cfg.property.read_only() await cfg.property.read_only()
assert cfg.value.dict() == {'str': 'abc', 'str1': 'yes', 'str3': ['yes'], 'unicode2': 'yes'} assert await cfg.value.dict() == {'str': 'abc', 'str1': 'yes', 'str3': ['yes'], 'unicode2': 'yes'}
def test_mandatory_rw(): @pytest.mark.asyncio
async def test_mandatory_rw():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
# not mandatory in rw # not mandatory in rw
cfg.option('str1').value.get() await cfg.option('str1').value.get()
cfg.option('str1').value.set('yes') await cfg.option('str1').value.set('yes')
assert cfg.option('str1').value.get() == 'yes' assert await cfg.option('str1').value.get() == 'yes'
def test_mandatory_default(): @pytest.mark.asyncio
async def test_mandatory_default():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
#not mandatory in rw #not mandatory in rw
cfg.option('str').value.get() await cfg.option('str').value.get()
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.set('yes') await cfg.option('str').value.set('yes')
cfg.property.read_only() await cfg.property.read_only()
cfg.option('str').value.get() await cfg.option('str').value.get()
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.set(None) await cfg.option('str').value.set(None)
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str').value.get() await cfg.option('str').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_delete(): @pytest.mark.asyncio
async def test_mandatory_delete():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
cfg.option('str').value.get() await cfg.option('str').value.get()
try: try:
cfg.option('str1').value.get() await cfg.option('str1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str1').value.set('yes') await cfg.option('str1').value.set('yes')
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('str1').value.get() == 'yes' assert await cfg.option('str1').value.get() == 'yes'
cfg.property.pop('everything_frozen') await cfg.property.pop('everything_frozen')
prop = [] prop = []
try: try:
cfg.option('str1').value.reset() await cfg.option('str1').value.reset()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.option('str').value.reset() await cfg.option('str').value.reset()
assert cfg.option('str1').value.get() == 'yes' assert await cfg.option('str1').value.get() == 'yes'
#valeur vide : None, '', u'', ... #valeur vide : None, '', u'', ...
def test_mandatory_none(): @pytest.mark.asyncio
async def test_mandatory_none():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str1').value.set(None) await cfg.option('str1').value.set(None)
assert cfg.option('str1').owner.get() == 'user' assert await cfg.option('str1').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str1').value.get() await cfg.option('str1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_empty(): @pytest.mark.asyncio
async def test_mandatory_empty():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str1').value.set('') await cfg.option('str1').value.set('')
assert cfg.option('str1').owner.get() == 'user' assert await cfg.option('str1').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str1').value.get() await cfg.option('str1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_multi_none(): @pytest.mark.asyncio
async def test_mandatory_multi_none():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str3').value.set([None]) await cfg.option('str3').value.set([None])
assert cfg.option('str3').owner.get() == 'user' assert await cfg.option('str3').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str3').value.get() await cfg.option('str3').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str3').value.set(['yes', None]) await cfg.option('str3').value.set(['yes', None])
assert cfg.option('str3').owner.get() == 'user' assert await cfg.option('str3').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str3').value.get() await cfg.option('str3').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_multi_empty(): @pytest.mark.asyncio
async def test_mandatory_multi_empty():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str3').value.set([]) await cfg.option('str3').value.set([])
assert cfg.option('str3').owner.get() == 'user' assert await cfg.option('str3').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str3').value.get() await cfg.option('str3').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str3').value.set(['']) await cfg.option('str3').value.set([''])
assert cfg.option('str3').owner.get() == 'user' assert await cfg.option('str3').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str3').value.get() await cfg.option('str3').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str3').value.set(['yes', '']) await cfg.option('str3').value.set(['yes', ''])
assert cfg.option('str3').owner.get() == 'user' assert await cfg.option('str3').owner.get() == 'user'
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('str3').value.get() await cfg.option('str3').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_multi_append(): @pytest.mark.asyncio
async def test_mandatory_multi_append():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str3').value.set(['yes']) await cfg.option('str3').value.set(['yes'])
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str3').value.get().append(None) ret = await cfg.option('str3').value.get()
ret.append(None)
def test_mandatory_disabled(): @pytest.mark.asyncio
async def test_mandatory_disabled():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str1').value.get() await cfg.option('str1').value.get()
cfg.option('str1').property.add('disabled') await cfg.option('str1').property.add('disabled')
cfg.property.read_only() await cfg.property.read_only()
pop = [] pop = []
try: try:
cfg.option('str1').value.get() await cfg.option('str1').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
search_prop = {'disabled'} search_prop = {'disabled'}
assert set(prop) == search_prop assert set(prop) == search_prop
def test_mandatory_unicode(): @pytest.mark.asyncio
async def test_mandatory_unicode():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('unicode2').value.get() await cfg.option('unicode2').value.get()
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('unicode2').value.get() await cfg.option('unicode2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
cfg.property.read_write() await cfg.property.read_write()
cfg.option('unicode2').value.set(u'') await cfg.option('unicode2').value.set(u'')
cfg.property.read_only() await cfg.property.read_only()
prop = [] prop = []
try: try:
cfg.option('unicode2').value.get() await cfg.option('unicode2').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
def test_mandatory_warnings_ro(): @pytest.mark.asyncio
async def test_mandatory_warnings_ro():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_only() await cfg.property.read_only()
proc = [] proc = []
try: try:
cfg.option('str').value.get() await cfg.option('str').value.get()
except PropertiesOptionError as err: except PropertiesOptionError as err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
assert list(cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3']
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.set('a') await cfg.option('str').value.set('a')
cfg.property.read_only() await cfg.property.read_only()
assert list(cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_rw(): @pytest.mark.asyncio
async def test_mandatory_warnings_rw():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.get() await cfg.option('str').value.get()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3']
cfg.option('str').value.set('a') await cfg.option('str').value.set('a')
assert list(cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_disabled(): @pytest.mark.asyncio
async def test_mandatory_warnings_disabled():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.get() await cfg.option('str').value.get()
assert set(cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
cfg.option('str').property.add('disabled') await cfg.option('str').property.add('disabled')
assert set(cfg.value.mandatory()) == {'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str1', 'unicode2', 'str3'}
def test_mandatory_warnings_hidden(): @pytest.mark.asyncio
async def test_mandatory_warnings_hidden():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.permissive.add('hidden') await cfg.permissive.add('hidden')
cfg.option('str').value.get() await cfg.option('str').value.get()
assert set(cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
cfg.option('str').property.add('hidden') await cfg.option('str').property.add('hidden')
assert set(cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
def test_mandatory_warnings_frozen(): @pytest.mark.asyncio
async def test_mandatory_warnings_frozen():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.get() await cfg.option('str').value.get()
assert set(cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
cfg.option('str').property.add('frozen') await cfg.option('str').property.add('frozen')
cfg.property.read_only() await cfg.property.read_only()
assert set(cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
def test_mandatory_leader(): @pytest.mark.asyncio
async def test_mandatory_leader():
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,
properties=('mandatory', )) properties=('mandatory', ))
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True) multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()") with pytest.raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.value.dict()") await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
with pytest.raises(PropertiesOptionError):
await cfg.value.dict()
def test_mandatory_warnings_leader(): @pytest.mark.asyncio
async def test_mandatory_warnings_leader():
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,
properties=('mandatory', )) properties=('mandatory', ))
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True) multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
assert list(cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
def test_mandatory_leader_empty(): @pytest.mark.asyncio
async def test_mandatory_leader_empty():
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", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True) multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
# #
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined])
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').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', 0).value.get() == None
cfg.property.read_only() await cfg.property.read_only()
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()") with pytest.raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()") await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.property.read_write() with pytest.raises(PropertiesOptionError):
cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] await cfg.property.read_write()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
# #
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([''])
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['']
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
cfg.property.read_only() await cfg.property.read_only()
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()") with pytest.raises(PropertiesOptionError):
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()") await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.property.read_write() with pytest.raises(PropertiesOptionError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
await cfg.property.read_write()
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip2']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip2'])
cfg.property.read_only() await cfg.property.read_only()
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()") with pytest.raises(PropertiesOptionError):
cfg.property.read_write() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.property.read_write()
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
def test_mandatory_warnings_leader_empty(): @pytest.mark.asyncio
async def test_mandatory_warnings_leader_empty():
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", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True) multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined])
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').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', 0).value.get() == None
assert list(cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
# #
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([''])
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['']
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert list(cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
assert list(cfg.value.mandatory()) == [] assert list(await cfg.value.mandatory()) == []
def test_mandatory_follower(): @pytest.mark.asyncio
async def test_mandatory_follower():
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", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True, properties=('mandatory', )) multi=True, properties=('mandatory', ))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [],
'ip_admin_eth0.netmask_admin_eth0': []} 'ip_admin_eth0.netmask_admin_eth0': []}
cfg.property.read_write()
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('') await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
raises(PropertiesOptionError, "cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
# #
cfg.property.read_write() await cfg.property.read_write()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('ip') await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('')
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'ip' with pytest.raises(PropertiesOptionError):
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip'], await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
#
await cfg.property.read_write()
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('ip')
await cfg.property.read_only()
assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'ip'
assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip'],
'ip_admin_eth0.netmask_admin_eth0': ['ip']} 'ip_admin_eth0.netmask_admin_eth0': ['ip']}
def test_mandatory_warnings_follower(): @pytest.mark.asyncio
async def test_mandatory_warnings_follower():
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", netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau",
multi=True, properties=('mandatory', )) multi=True, properties=('mandatory', ))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1]) descr = OptionDescription('o', '', [interface1])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
assert cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
# #
cfg.property.read_write() await cfg.property.read_write()
assert list(cfg.value.mandatory()) == [] assert list(await cfg.value.mandatory()) == []
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
assert list(cfg.value.mandatory()) == ['ip_admin_eth0.netmask_admin_eth0'] assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.netmask_admin_eth0']
def test_mandatory_warnings_symlink(): @pytest.mark.asyncio
async def test_mandatory_warnings_symlink():
descr = make_description_sym() descr = make_description_sym()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.get() await cfg.option('str').value.get()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'str3'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3']
cfg.option('str').property.add('frozen') await cfg.option('str').property.add('frozen')
cfg.property.read_only() await cfg.property.read_only()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'str3'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3']
#def test_mandatory_warnings_validate(): #@pytest.mark.asyncio
#async def test_mandatory_warnings_validate():
# descr = make_description3() # descr = make_description3()
# cfg = Config(descr) # cfg = await Config(descr)
# cfg.option('str').value.set('') # await cfg.option('str').value.set('')
# raises(ValueError, "list(cfg.value.mandatory())") # raises(ValueError, "list(await cfg.value.mandatory())")
# cfg.option('str').value.set('test') # await cfg.option('str').value.set('test')
# raises(ValueError, "list(cfg.value.mandatory())") # raises(ValueError, "list(await cfg.value.mandatory())")
def test_mandatory_warnings_validate_empty(): @pytest.mark.asyncio
async def test_mandatory_warnings_validate_empty():
descr = make_description2() descr = make_description2()
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_only() await cfg.property.read_only()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'str3'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3']
def test_mandatory_warnings_requires(): @pytest.mark.asyncio
async def test_mandatory_warnings_requires():
stroption = StrOption('str', 'Test string option', default="abc", stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', )) properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option', stroption1 = StrOption('str1', 'Test string option',
@ -553,19 +590,20 @@ def test_mandatory_warnings_requires():
'no_condition_is_invalid': ParamValue(True)})) 'no_condition_is_invalid': ParamValue(True)}))
stroption3 = StrOption('str3', 'Test string option', multi=True, properties=(mandatory_property,)) stroption3 = StrOption('str3', 'Test string option', multi=True, properties=(mandatory_property,))
descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3]) descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3])
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.get() await cfg.option('str').value.get()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2']
cfg.property.read_only() await cfg.property.read_only()
assert list(cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2']
cfg.property.read_write() await cfg.property.read_write()
cfg.option('str').value.set('yes') await cfg.option('str').value.set('yes')
assert list(cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_requires_leadership(): @pytest.mark.asyncio
async def test_mandatory_warnings_requires_leadership():
stroption = StrOption('str', 'Test string option', default="abc", stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', )) properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option', multi=True) stroption1 = StrOption('str1', 'Test string option', multi=True)
@ -578,15 +616,16 @@ def test_mandatory_warnings_requires_leadership():
stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,)) stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,))
leadership = Leadership('leader', 'leadership', [stroption1, stroption2]) leadership = Leadership('leader', 'leadership', [stroption1, stroption2])
descr = OptionDescription('tiram', '', [stroption, leadership]) descr = OptionDescription('tiram', '', [stroption, leadership])
cfg = Config(descr) cfg = await Config(descr)
cfg.option('str').value.set('') await cfg.option('str').value.set('')
cfg.option('leader.str1').value.set(['str']) await cfg.option('leader.str1').value.set(['str'])
assert list(cfg.value.mandatory()) == ['str'] assert list(await cfg.value.mandatory()) == ['str']
cfg.option('str').value.set('yes') await cfg.option('str').value.set('yes')
assert list(cfg.value.mandatory()) == ['leader.str2'] assert list(await cfg.value.mandatory()) == ['leader.str2']
def test_mandatory_warnings_requires_leadership_follower(): @pytest.mark.asyncio
async def test_mandatory_warnings_requires_leadership_follower():
stroption = StrOption('str', 'Test string option', multi=True) stroption = StrOption('str', 'Test string option', multi=True)
stroption1 = StrOption('str1', 'Test string option', multi=True) stroption1 = StrOption('str1', 'Test string option', multi=True)
mandatory_property = Calculation(calc_value, mandatory_property = Calculation(calc_value,
@ -598,18 +637,19 @@ def test_mandatory_warnings_requires_leadership_follower():
stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,)) stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,))
leadership = Leadership('leader', 'leadership', [stroption, stroption1, stroption2]) leadership = Leadership('leader', 'leadership', [stroption, stroption1, stroption2])
descr = OptionDescription('tiram', '', [leadership]) descr = OptionDescription('tiram', '', [leadership])
cfg = Config(descr) cfg = await Config(descr)
cfg.option('leader.str').value.set(['str']) await cfg.option('leader.str').value.set(['str'])
assert list(cfg.value.mandatory()) == [] assert list(await cfg.value.mandatory()) == []
cfg.option('leader.str1', 0).value.set('yes') await cfg.option('leader.str1', 0).value.set('yes')
assert list(cfg.value.mandatory()) == ['leader.str2'] assert list(await cfg.value.mandatory()) == ['leader.str2']
def test_mandatory_od_disabled(): @pytest.mark.asyncio
async def test_mandatory_od_disabled():
descr = make_description() descr = make_description()
descr = OptionDescription('od', '', [descr]) descr = OptionDescription('od', '', [descr])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
assert list(cfg.value.mandatory()) == ['tiram.str1', 'tiram.unicode2', 'tiram.str3'] assert list(await cfg.value.mandatory()) == ['tiram.str1', 'tiram.unicode2', 'tiram.str3']
cfg.option('tiram').property.add('disabled') await cfg.option('tiram').property.add('disabled')
assert list(cfg.value.mandatory()) == [] assert list(await cfg.value.mandatory()) == []

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
from tiramisu import IntOption, OptionDescription, MetaConfig from tiramisu import IntOption, OptionDescription, MetaConfig
from tiramisu.error import ConfigError from tiramisu.error import ConfigError
from pytest import raises import pytest
def make_metaconfig(): async 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', '')
@ -12,80 +12,84 @@ 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 MetaConfig([], optiondescription=od2, session_id='metacfg1') return await MetaConfig([], optiondescription=od2, session_id='metacfg1')
def test_multi_parents_path(): @pytest.mark.asyncio
async def test_multi_parents_path():
""" """
metacfg1 (1) --- metacfg1 (1) ---
| -- cfg1 | -- cfg1
metacfg2 (2) --- metacfg2 (2) ---
""" """
metacfg1 = make_metaconfig() metacfg1 = await make_metaconfig()
cfg1 = metacfg1.config.new(type='config', session_id="cfg1") cfg1 = await metacfg1.config.new(type='config', session_id="cfg1")
metacfg2 = MetaConfig([cfg1], session_id='metacfg2') metacfg2 = await MetaConfig([cfg1], session_id='metacfg2')
# #
assert metacfg1.config.path() == 'metacfg1' assert await metacfg1.config.path() == 'metacfg1'
assert metacfg2.config.path() == 'metacfg2' assert await metacfg2.config.path() == 'metacfg2'
assert cfg1.config.path() == 'metacfg2.metacfg1.cfg1' assert await cfg1.config.path() == 'metacfg2.metacfg1.cfg1'
def test_multi_parents_path_same(): @pytest.mark.asyncio
async def test_multi_parents_path_same():
""" """
--- metacfg2 (1) --- --- metacfg2 (1) ---
metacfg1 --| | -- cfg1 metacfg1 --| | -- cfg1
--- metacfg3 (2) --- --- metacfg3 (2) ---
""" """
metacfg1 = make_metaconfig() metacfg1 = await make_metaconfig()
metacfg2 = metacfg1.config.new(type='metaconfig', session_id="metacfg2") metacfg2 = await metacfg1.config.new(type='metaconfig', session_id="metacfg2")
metacfg3 = metacfg1.config.new(type='metaconfig', session_id="metacfg3") metacfg3 = await metacfg1.config.new(type='metaconfig', session_id="metacfg3")
cfg1 = metacfg2.config.new(type='config', session_id="cfg1") cfg1 = await metacfg2.config.new(type='config', session_id="cfg1")
metacfg3.config.add(cfg1) await metacfg3.config.add(cfg1)
# #
assert metacfg2.config.path() == 'metacfg1.metacfg2' assert await metacfg2.config.path() == 'metacfg1.metacfg2'
assert metacfg3.config.path() == 'metacfg1.metacfg3' assert await metacfg3.config.path() == 'metacfg1.metacfg3'
assert cfg1.config.path() == 'metacfg1.metacfg3.metacfg1.metacfg2.cfg1' assert await cfg1.config.path() == 'metacfg1.metacfg3.metacfg1.metacfg2.cfg1'
metacfg1.option('od1.i1').value.set(1) await metacfg1.option('od1.i1').value.set(1)
metacfg3.option('od1.i1').value.set(2) await metacfg3.option('od1.i1').value.set(2)
assert cfg1.option('od1.i1').value.get() == 1 assert await cfg1.option('od1.i1').value.get() == 1
orideep = cfg1.config.deepcopy(metaconfig_prefix="test_", session_id='test_cfg1') orideep = await cfg1.config.deepcopy(metaconfig_prefix="test_", session_id='test_cfg1')
deep = orideep deep = orideep
while True: while True:
try: try:
children = list(deep.config.list()) children = list(await deep.config.list())
except: except:
break break
assert len(children) < 2 assert len(children) < 2
deep = children[0] deep = children[0]
assert deep.config.path() == 'test_metacfg3.test_metacfg1.test_metacfg2.test_cfg1' assert await deep.config.path() == 'test_metacfg3.test_metacfg1.test_metacfg2.test_cfg1'
assert cfg1.option('od1.i1').value.get() == 1 assert await cfg1.option('od1.i1').value.get() == 1
del orideep del orideep
raises(ConfigError, "deep.config.path()") with pytest.raises(ConfigError):
await deep.config.path()
def test_multi_parents_value(): @pytest.mark.asyncio
metacfg1 = make_metaconfig() async def test_multi_parents_value():
cfg1 = metacfg1.config.new(type='config', session_id="cfg1") metacfg1 = await make_metaconfig()
metacfg2 = MetaConfig([cfg1], session_id='metacfg2') cfg1 = await metacfg1.config.new(type='config', session_id="cfg1")
metacfg2 = await MetaConfig([cfg1], session_id='metacfg2')
# #
assert cfg1.option('od1.i1').value.get() == None assert await cfg1.option('od1.i1').value.get() == None
assert cfg1.option('od1.i2').value.get() == 1 assert await cfg1.option('od1.i2').value.get() == 1
assert cfg1.option('od1.i3').value.get() == None assert await cfg1.option('od1.i3').value.get() == None
# #
assert metacfg1.option('od1.i1').value.get() == None assert await metacfg1.option('od1.i1').value.get() == None
assert metacfg1.option('od1.i2').value.get() == 1 assert await metacfg1.option('od1.i2').value.get() == 1
assert metacfg1.option('od1.i3').value.get() == None assert await metacfg1.option('od1.i3').value.get() == None
# #
assert metacfg2.option('od1.i1').value.get() == None assert await metacfg2.option('od1.i1').value.get() == None
assert metacfg2.option('od1.i2').value.get() == 1 assert await metacfg2.option('od1.i2').value.get() == 1
assert metacfg2.option('od1.i3').value.get() == None assert await metacfg2.option('od1.i3').value.get() == None
# #
metacfg1.option('od1.i3').value.set(3) await metacfg1.option('od1.i3').value.set(3)
assert metacfg1.option('od1.i3').value.get() == 3 assert await metacfg1.option('od1.i3').value.get() == 3
assert cfg1.option('od1.i3').value.get() == 3 assert await cfg1.option('od1.i3').value.get() == 3
assert metacfg2.option('od1.i2').value.get() == 1 assert await metacfg2.option('od1.i2').value.get() == 1
# #
metacfg2.option('od1.i2').value.set(4) await metacfg2.option('od1.i2').value.set(4)
assert metacfg2.option('od1.i2').value.get() == 4 assert await metacfg2.option('od1.i2').value.get() == 4
assert metacfg1.option('od1.i2').value.get() == 1 assert await metacfg1.option('od1.i2').value.get() == 1
assert cfg1.option('od1.i2').value.get() == 4 assert await cfg1.option('od1.i2').value.get() == 4

View file

@ -4,7 +4,8 @@ and to compare them
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from py.test import raises import pytest
import warnings
from tiramisu.error import APIError, ConfigError from tiramisu.error import APIError, ConfigError
from tiramisu import IntOption, SymLinkOption, OptionDescription, Config, Calculation, groups, list_sessions from tiramisu import IntOption, SymLinkOption, OptionDescription, Config, Calculation, groups, list_sessions
@ -16,6 +17,8 @@ except:
groups.family = groups.GroupType('family') groups.family = groups.GroupType('family')
def teardown_function(function): def teardown_function(function):
# some tests emit a warnings because of doesn't create a Config
with warnings.catch_warnings(record=True) as w:
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
@ -23,140 +26,159 @@ def a_func():
return None return None
def test_option_valid_name(): @pytest.mark.asyncio
async def test_option_valid_name():
IntOption('test', '') IntOption('test', '')
raises(ValueError, 'IntOption(1, "")') with pytest.raises(ValueError):
# raises(ValueError, 'IntOption("1test", "")') IntOption(1, "")
i = IntOption("test1", "") i = IntOption("test1", "")
# raises(ValueError, 'IntOption("_test", "")') with pytest.raises(ValueError):
# raises(ValueError, 'IntOption(" ", "")') SymLinkOption(1, i)
raises(ValueError, 'SymLinkOption(1, i)')
i = SymLinkOption("test1", i) i = SymLinkOption("test1", i)
#
#
#def test_option_with_callback_legacy():
# # no default value with callback
# raises(ValueError, "IntOption('test', '', default=1, callback=a_func)")
def test_option_get_information(): @pytest.mark.asyncio
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)
raises(ValueError, "i.impl_get_information('noinfo')") with pytest.raises(ValueError):
i.impl_get_information('noinfo')
i.impl_set_information('info', string) i.impl_set_information('info', string)
assert i.impl_get_information('info') == string assert i.impl_get_information('info') == string
raises(ValueError, "i.impl_get_information('noinfo')") with pytest.raises(ValueError):
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
def test_option_get_information_config(): @pytest.mark.asyncio
async def test_option_get_information_config():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
string
i = IntOption('test', description) i = IntOption('test', description)
od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [i])
Config(od) await Config(od)
raises(ValueError, "i.impl_get_information('noinfo')") with pytest.raises(ValueError):
raises(AttributeError, "i.impl_set_information('info', string)") i.impl_get_information('noinfo')
# assert i.impl_get_information('info') == string with pytest.raises(AttributeError):
raises(ValueError, "i.impl_get_information('noinfo')") i.impl_set_information('info', string)
with pytest.raises(ValueError):
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
def test_option_get_information_default(): @pytest.mark.asyncio
async def test_option_get_information_default():
description = "it's ok" description = "it's ok"
string = 'some informations' string = 'some informations'
string
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])
cfg = Config(od) cfg = await Config(od)
# #
assert cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault' assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault'
# #
cfg.option('test').information.set('noinfo', 'notdefault') await cfg.option('test').information.set('noinfo', 'notdefault')
assert cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault' assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault'
def test_option_get_information_config2(): @pytest.mark.asyncio
async 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])
Config(od) await Config(od)
raises(ValueError, "i.impl_get_information('noinfo')") with pytest.raises(ValueError):
raises(AttributeError, "i.impl_set_information('info', 'hello')") i.impl_get_information('noinfo')
with pytest.raises(AttributeError):
i.impl_set_information('info', 'hello')
assert i.impl_get_information('info') == string assert i.impl_get_information('info') == string
raises(ValueError, "i.impl_get_information('noinfo')") with pytest.raises(ValueError):
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
def test_optiondescription_get_information(): @pytest.mark.asyncio
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, [])
o.impl_set_information('info', string) o.impl_set_information('info', string)
assert o.impl_get_information('info') == string assert o.impl_get_information('info') == string
raises(ValueError, "o.impl_get_information('noinfo')") with pytest.raises(ValueError):
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
def test_option_isoptiondescription(): @pytest.mark.asyncio
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])
cfg = Config(od) cfg = await Config(od)
assert cfg.option('od').option.isoptiondescription() assert await cfg.option('od').option.isoptiondescription()
assert not cfg.option('od.test').option.isoptiondescription() assert not await cfg.option('od.test').option.isoptiondescription()
def test_option_double(): @pytest.mark.asyncio
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])
cfg = Config(od) cfg = await Config(od)
assert cfg.option('od2.od1.test').value.get() is None assert await cfg.option('od2.od1.test').value.get() is None
assert cfg.option('od2').option('od1').option('test').value.get() is None assert await cfg.option('od2').option('od1').option('test').value.get() is None
def test_option_multi(): @pytest.mark.asyncio
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)
#add default_multi to not multi's option #add default_multi to not multi's option
raises(ValueError, "IntOption('test', '', default_multi=1)") with pytest.raises(ValueError):
IntOption('test', '', default_multi=1)
#unvalid default_multi #unvalid default_multi
raises(ValueError, "IntOption('test', '', multi=True, default_multi='yes')") with pytest.raises(ValueError):
IntOption('test', '', multi=True, default_multi='yes')
#def test_option_multi_legacy(): #@pytest.mark.asyncio
#async def test_option_multi_legacy():
# #not default_multi with callback # #not default_multi with callback
# #raises(ValueError, "IntOption('test', '', multi=True, default_multi=1, callback=a_func)") # #with pytest.raises(ValueError):
# IntOption('test', '', multi=True, default_multi=1, callback=a_func)")
def test_unknown_option(): @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])
api = Config(od2) cfg = await Config(od2)
# test is an option, not an optiondescription # test is an option, not an optiondescription
raises(TypeError, "api.option('od.test.unknown').value.get()") with pytest.raises(TypeError):
await cfg.option('od.test.unknown').value.get()
# unknown is an unknown option # unknown is an unknown option
raises(AttributeError, "api.option('unknown').value.get()") with pytest.raises(AttributeError):
await cfg.option('unknown').value.get()
# unknown is an unknown option # unknown is an unknown option
raises(AttributeError, "api.option('od.unknown').value.get()") with pytest.raises(AttributeError):
await cfg.option('od.unknown').value.get()
# unknown is an unknown optiondescription # unknown is an unknown optiondescription
raises(AttributeError, "api.option('od.unknown.suboption').value.get()") with pytest.raises(AttributeError):
await cfg.option('od.unknown.suboption').value.get()
def test_optiondescription_list(): @pytest.mark.asyncio
async def test_optiondescription_list():
groups.notfamily1 = groups.GroupType('notfamily1') groups.notfamily1 = groups.GroupType('notfamily1')
i = IntOption('test', '') i = IntOption('test', '')
i2 = IntOption('test', '') i2 = IntOption('test', '')
@ -166,28 +188,29 @@ 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])
api = Config(od4) cfg = await Config(od4)
assert len(list(api.option('od').list('option'))) == 0 assert len(list(await cfg.option('od').list('option'))) == 0
assert len(list(api.option('od').list('optiondescription'))) == 2 assert len(list(await cfg.option('od').list('optiondescription'))) == 2
assert len(list(api.option('od').list('optiondescription', group_type=groups.family))) == 1 assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.family))) == 1
assert len(list(api.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1 assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1
assert len(list(api.option('od.od').list('option'))) == 1 assert len(list(await cfg.option('od.od').list('option'))) == 1
assert len(list(api.option('od.od2').list('option'))) == 1 assert len(list(await cfg.option('od.od2').list('option'))) == 1
try: try:
list(api.option('od').list('unknown')) list(await cfg.option('od').list('unknown'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
try: try:
list(api.option('od').list('option', group_type='toto')) list(await cfg.option('od').list('option', group_type='toto'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
def test_optiondescription_group(): @pytest.mark.asyncio
async def test_optiondescription_group():
groups.notfamily = groups.GroupType('notfamily') groups.notfamily = groups.GroupType('notfamily')
i = IntOption('test', '') i = IntOption('test', '')
i2 = IntOption('test', '') i2 = IntOption('test', '')
@ -196,26 +219,27 @@ 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])
api = Config(od2) cfg = await Config(od2)
assert len(list(api.option.list('option'))) == 0 assert len(list(await cfg.option.list('option'))) == 0
assert len(list(api.option.list('optiondescription'))) == 2 assert len(list(await cfg.option.list('optiondescription'))) == 2
assert len(list(api.option.list('optiondescription', group_type=groups.family))) == 1 assert len(list(await cfg.option.list('optiondescription', group_type=groups.family))) == 1
assert len(list(api.option.list('optiondescription', group_type=groups.notfamily))) == 1 assert len(list(await cfg.option.list('optiondescription', group_type=groups.notfamily))) == 1
try: try:
list(api.option.list('unknown')) list(await cfg.option.list('unknown'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
try: try:
list(api.option.list('option', group_type='toto')) list(await cfg.option.list('option', group_type='toto'))
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
def test_optiondescription_group_redefined(): @pytest.mark.asyncio
async def test_optiondescription_group_redefined():
try: try:
groups.notfamily = groups.GroupType('notfamily') groups.notfamily = groups.GroupType('notfamily')
except: except:
@ -223,43 +247,55 @@ def test_optiondescription_group_redefined():
i = IntOption('test', '') i = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
od1.impl_set_group_type(groups.family) od1.impl_set_group_type(groups.family)
raises(ValueError, "od1.impl_set_group_type(groups.notfamily)") with pytest.raises(ValueError):
od1.impl_set_group_type(groups.notfamily)
def test_optiondescription_group_leadership(): @pytest.mark.asyncio
async def test_optiondescription_group_leadership():
i = IntOption('test', '') i = IntOption('test', '')
od1 = OptionDescription('od', '', [i]) od1 = OptionDescription('od', '', [i])
raises(ConfigError, "od1.impl_set_group_type(groups.leadership)") with pytest.raises(ConfigError):
od1.impl_set_group_type(groups.leadership)
def test_asign_optiondescription(): @pytest.mark.asyncio
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])
api = Config(od2) cfg = await Config(od2)
raises(APIError, "api.option('od').value.set('test')") with pytest.raises(APIError):
raises(APIError, "api.option('od').value.reset()") await cfg.option('od').value.set('test')
with pytest.raises(APIError):
await cfg.option('od').value.reset()
def test_intoption(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [i1, i2])
cfg = Config(od) cfg = await Config(od)
raises(ValueError, "cfg.option('test1').value.set(2)") with pytest.raises(ValueError):
cfg.option('test1').value.set(3) await cfg.option('test1').value.set(2)
cfg.option('test1').value.set(4) await cfg.option('test1').value.set(3)
cfg.option('test2').value.set(2) await cfg.option('test1').value.set(4)
cfg.option('test2').value.set(3) await cfg.option('test2').value.set(2)
raises(ValueError, "cfg.option('test2').value.set(4)") await cfg.option('test2').value.set(3)
with pytest.raises(ValueError):
await cfg.option('test2').value.set(4)
def test_get_display_type(): @pytest.mark.asyncio
async def test_get_display_type():
i1 = IntOption('test1', 'description', min_number=3) i1 = IntOption('test1', 'description', min_number=3)
assert i1.get_display_type() == _('integer') assert i1.get_display_type() == _('integer')
def test_option_not_in_config(): @pytest.mark.asyncio
async def test_option_not_in_config():
i1 = IntOption('test1', 'description', min_number=3) i1 = IntOption('test1', 'description', min_number=3)
raises(AttributeError, "i1.impl_getpath()") with pytest.raises(AttributeError):
i1.impl_getpath()

File diff suppressed because it is too large Load diff

View file

@ -3,8 +3,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from py.test import raises 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, \
@ -45,7 +44,8 @@ def make_description():
#____________________________________________________________ #____________________________________________________________
# default values # default values
def test_default_is_none(config_type): @pytest.mark.asyncio
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
@ -54,210 +54,231 @@ 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]) group = OptionDescription('group', '', [dummy1, dummy2])
cfg = Config(group) cfg = await Config(group)
cfg = get_config(cfg, config_type) cfg = await 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 cfg.option('dummy1').value.get() is None assert await cfg.option('dummy1').value.get() is None
assert cfg.option('dummy2').value.get() is None assert await cfg.option('dummy2').value.get() is None
def test_set_defaut_value_from_option_object(): @pytest.mark.asyncio
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
def test_force_default_on_freeze(): @pytest.mark.asyncio
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]) group = OptionDescription('group', '', [dummy1, dummy2])
cfg_ori = Config(group) cfg_ori = await Config(group)
cfg_ori.property.read_write() await cfg_ori.property.read_write()
cfg = cfg_ori cfg = cfg_ori
# FIXME cfg = get_config(cfg_ori, config_type) # FIXME cfg = await get_config(cfg_ori, config_type)
owner = cfg.owner.get() owner = await cfg.owner.get()
cfg.option('dummy1').value.set(True) await cfg.option('dummy1').value.set(True)
cfg.option('dummy2').value.set(False) await cfg.option('dummy2').value.set(False)
assert cfg.option('dummy1').owner.get() == owner assert await cfg.option('dummy1').owner.get() == owner
assert cfg.option('dummy2').owner.get() == owner assert await cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
cfg_ori.option('dummy1').property.add('frozen') await cfg_ori.option('dummy1').property.add('frozen')
cfg_ori.option('dummy2').property.add('frozen') await cfg_ori.option('dummy2').property.add('frozen')
# cfg = get_config(cfg_ori, config_type) # cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy1').value.get() is False assert await cfg.option('dummy1').value.get() is False
assert cfg.option('dummy2').value.get() is False assert await cfg.option('dummy2').value.get() is False
assert cfg.option('dummy1').owner.isdefault() assert await cfg.option('dummy1').owner.isdefault()
assert cfg.option('dummy2').owner.get() == owner assert await cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
raises(PropertiesOptionError, "cfg_ori.option('dummy2').owner.set('frozen')") with pytest.raises(PropertiesOptionError):
# cfg = get_config(cfg_ori, config_type) await cfg_ori.option('dummy2').owner.set('frozen')
raises(PropertiesOptionError, "cfg.option('dummy1').value.reset()") # cfg = await get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError):
await cfg.option('dummy1').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
cfg_ori.option('dummy1').property.pop('frozen') await cfg_ori.option('dummy1').property.pop('frozen')
# cfg = get_config(cfg_ori, config_type) # cfg = await get_config(cfg_ori, config_type)
cfg.option('dummy1').value.reset() await cfg.option('dummy1').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
cfg.option('dummy1').property.add('frozen') await cfg.option('dummy1').property.add('frozen')
# cfg = get_config(cfg_ori, config_type) # cfg = await get_config(cfg_ori, config_type)
raises(PropertiesOptionError, "cfg.option('dummy2').owner.set('frozen')") with pytest.raises(PropertiesOptionError):
await cfg.option('dummy2').owner.set('frozen')
def test_force_default_on_freeze_multi(): @pytest.mark.asyncio
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]) group = OptionDescription('group', '', [dummy1, dummy2])
cfg_ori = Config(group) cfg_ori = await Config(group)
cfg_ori.property.read_write() await cfg_ori.property.read_write()
cfg = cfg_ori cfg = cfg_ori
# FIXME cfg = get_config(cfg_ori, config_type) # FIXME cfg = await get_config(cfg_ori, config_type)
cfg.option('dummy1').value.set([undefined, True]) await cfg.option('dummy1').value.set([undefined, True])
cfg.option('dummy2').value.set([undefined, False]) await cfg.option('dummy2').value.set([undefined, False])
owner = cfg.owner.get() owner = await cfg.owner.get()
assert cfg.option('dummy1').owner.get() == owner assert await cfg.option('dummy1').owner.get() == owner
assert cfg.option('dummy2').owner.get() == owner assert await cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
cfg_ori.option('dummy1').property.add('frozen') await cfg_ori.option('dummy1').property.add('frozen')
cfg_ori.option('dummy2').property.add('frozen') await cfg_ori.option('dummy2').property.add('frozen')
# cfg = get_config(cfg_ori, config_type) # cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy1').value.get() == [False] assert await cfg.option('dummy1').value.get() == [False]
assert cfg.option('dummy2').value.get() == [True, False] assert await cfg.option('dummy2').value.get() == [True, False]
assert cfg.option('dummy1').owner.isdefault() assert await cfg.option('dummy1').owner.isdefault()
assert cfg.option('dummy2').owner.get() == owner assert await cfg.option('dummy2').owner.get() == owner
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
raises(PropertiesOptionError, "cfg_ori.option('dummy2').owner.set('owner')") with pytest.raises(PropertiesOptionError):
# cfg = get_config(cfg_ori, config_type) await cfg_ori.option('dummy2').owner.set('owner')
raises(PropertiesOptionError, "cfg.option('dummy2').value.reset()") # cfg = await get_config(cfg_ori, config_type)
with pytest.raises(PropertiesOptionError):
await cfg.option('dummy2').value.reset()
# if config_type == 'tiramisu-api': # if config_type == 'tiramisu-api':
# cfg.send() # await cfg.send()
cfg_ori.option('dummy1').property.pop('frozen') await cfg_ori.option('dummy1').property.pop('frozen')
# cfg = get_config(cfg_ori, config_type) # cfg = await get_config(cfg_ori, config_type)
cfg.option('dummy1').value.reset() await cfg.option('dummy1').value.reset()
def test_force_default_on_freeze_leader(): @pytest.mark.asyncio
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]) descr = OptionDescription("root", "", [descr])
raises(ConfigError, "Config(descr)") with pytest.raises(ConfigError):
await Config(descr)
def test_force_metaconfig_on_freeze_leader(): @pytest.mark.asyncio
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]) descr = OptionDescription("root", "", [descr])
raises(ConfigError, "Config(descr)") with pytest.raises(ConfigError):
await Config(descr)
def test_force_default_on_freeze_leader_frozen(): @pytest.mark.asyncio
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]) descr = OptionDescription("root", "", [descr])
cfg = Config(descr) cfg = await Config(descr)
raises(LeadershipError, "cfg.option('dummy1.dummy1').property.pop('frozen')") with pytest.raises(LeadershipError):
await cfg.option('dummy1.dummy1').property.pop('frozen')
def test_force_metaconfig_on_freeze_leader_frozen(): @pytest.mark.asyncio
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]) descr = OptionDescription("root", "", [descr])
cfg = Config(descr) cfg = await Config(descr)
raises(LeadershipError, "cfg.option('dummy1.dummy1').property.pop('frozen')") with pytest.raises(LeadershipError):
await cfg.option('dummy1.dummy1').property.pop('frozen')
def test_force_default_on_freeze_follower(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription("root", "", [descr])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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)
cfg.option('dummy1.dummy1').value.set([True]) await cfg.option('dummy1.dummy1').value.set([True])
cfg.option('dummy1.dummy2', 0).value.set(False) await cfg.option('dummy1.dummy2', 0).value.set(False)
assert cfg.option('dummy1.dummy1').value.get() == [True] assert await cfg.option('dummy1.dummy1').value.get() == [True]
assert cfg.option('dummy1.dummy2', 0).value.get() == False assert await cfg.option('dummy1.dummy2', 0).value.get() == False
assert cfg.option('dummy1.dummy1').owner.get() == 'user' assert await cfg.option('dummy1.dummy1').owner.get() == 'user'
assert cfg.option('dummy1.dummy2', 0).owner.get() == 'user' assert await cfg.option('dummy1.dummy2', 0).owner.get() == 'user'
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('dummy1.dummy2').property.add('frozen') await cfg_ori.option('dummy1.dummy2').property.add('frozen')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy1.dummy1').value.get() == [True] assert await cfg.option('dummy1.dummy1').value.get() == [True]
assert cfg.option('dummy1.dummy2', 0).value.get() == None assert await cfg.option('dummy1.dummy2', 0).value.get() == None
assert cfg.option('dummy1.dummy1').owner.get() == 'user' assert await cfg.option('dummy1.dummy1').owner.get() == 'user'
assert cfg.option('dummy1.dummy2', 0).owner.isdefault() assert await cfg.option('dummy1.dummy2', 0).owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
raises(PropertiesOptionError, "cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower')") with pytest.raises(PropertiesOptionError):
cfg = get_config(cfg_ori, config_type) await cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower')
cfg = await get_config(cfg_ori, config_type)
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('dummy1.dummy2').property.pop('frozen') await cfg_ori.option('dummy1.dummy2').property.pop('frozen')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
cfg.option('dummy1.dummy1').value.set([True, True]) await cfg.option('dummy1.dummy1').value.set([True, True])
cfg.option('dummy1.dummy2', 1).value.set(False) await cfg.option('dummy1.dummy2', 1).value.set(False)
assert cfg.option('dummy1.dummy1').value.get() == [True, True] assert await cfg.option('dummy1.dummy1').value.get() == [True, True]
assert cfg.option('dummy1.dummy2', 0).value.get() == False assert await cfg.option('dummy1.dummy2', 0).value.get() == False
assert cfg.option('dummy1.dummy2', 1).value.get() == False assert await cfg.option('dummy1.dummy2', 1).value.get() == False
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('dummy1.dummy2').property.add('frozen') await cfg_ori.option('dummy1.dummy2').property.add('frozen')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy1.dummy1').value.get() == [True, True] assert await cfg.option('dummy1.dummy1').value.get() == [True, True]
assert cfg.option('dummy1.dummy2', 0).value.get() == None assert await cfg.option('dummy1.dummy2', 0).value.get() == None
assert cfg.option('dummy1.dummy2', 1).value.get() == None assert await cfg.option('dummy1.dummy2', 1).value.get() == None
# #
cfg.option('dummy1.dummy1').value.pop(1) await cfg.option('dummy1.dummy1').value.pop(1)
assert cfg.option('dummy1.dummy1').value.get() == [True] assert await cfg.option('dummy1.dummy1').value.get() == [True]
assert cfg.option('dummy1.dummy2', 0).value.get() == None assert await cfg.option('dummy1.dummy2', 0).value.get() == None
# #
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('dummy1.dummy2').property.pop('frozen') await cfg_ori.option('dummy1.dummy2').property.pop('frozen')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy1.dummy1').value.get() == [True] assert await cfg.option('dummy1.dummy1').value.get() == [True]
assert cfg.option('dummy1.dummy2', 0).value.get() == False assert await cfg.option('dummy1.dummy2', 0).value.get() == False
# #
cfg.option('dummy1.dummy1').value.set([True, True]) await cfg.option('dummy1.dummy1').value.set([True, True])
assert cfg.option('dummy1.dummy2', 0).value.get() == False assert await cfg.option('dummy1.dummy2', 0).value.get() == False
assert cfg.option('dummy1.dummy2', 1).value.get() == None assert await cfg.option('dummy1.dummy2', 1).value.get() == None
def test_overrides_changes_option_value(config_type): @pytest.mark.asyncio
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", "", [ descr = OptionDescription("test", "", [
BoolOption("b", "", default=False)]) BoolOption("b", "", default=False)])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('b').value.set(True) await cfg.option('b').value.set(True)
def test_choice_with_no_default(config_type): @pytest.mark.asyncio
async def test_choice_with_no_default(config_type):
descr = OptionDescription("test", "", [ descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"))]) ChoiceOption("backend", "", ("c", "cli"))])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('backend').value.get() is None assert await cfg.option('backend').value.get() is None
cfg.option('backend').value.set('c') await cfg.option('backend').value.set('c')
def test_choice_with_default(config_type): @pytest.mark.asyncio
async def test_choice_with_default(config_type):
descr = OptionDescription("test", "", [ descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"), default="cli")]) ChoiceOption("backend", "", ("c", "cli"), default="cli")])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('backend').value.get() == 'cli' assert await cfg.option('backend').value.get() == 'cli'

View file

@ -2,7 +2,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from py.test import raises 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, \
@ -41,181 +41,206 @@ def make_description():
return descr return descr
def test_default_owner(config_type): @pytest.mark.asyncio
async def test_default_owner(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
cfg.option('dummy').value.set(True) await cfg.option('dummy').value.set(True)
owner = cfg.owner.get() owner = await cfg.owner.get()
assert cfg.option('dummy').owner.get() == owner assert await cfg.option('dummy').owner.get() == owner
def test_hidden_owner(): @pytest.mark.asyncio
async def test_hidden_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',)) gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',))
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
#raises(PropertiesOptionError, "cfg.forcepermissive.option('dummy').owner.get()") #with pytest.raises(PropertiesOptionError):
#raises(PropertiesOptionError, "cfg.option('dummy').owner.isdefault()") # await cfg.forcepermissive.option('dummy').owner.get()
#raises(PropertiesOptionError, "cfg.forcepermissive.option('dummy').owner.isdefault()") #with pytest.raises(PropertiesOptionError):
cfg.permissive.add('hidden') # await cfg.option('dummy').owner.isdefault()
cfg.forcepermissive.option('dummy').value.get() #with pytest.raises(PropertiesOptionError):
cfg.forcepermissive.option('dummy').owner.isdefault() # await cfg.forcepermissive.option('dummy').owner.isdefault()
await cfg.permissive.add('hidden')
await cfg.forcepermissive.option('dummy').value.get()
await cfg.forcepermissive.option('dummy').owner.isdefault()
def test_addowner(config_type): @pytest.mark.asyncio
async def test_addowner(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
assert cfg.option('dummy').owner.isdefault() assert await cfg.option('dummy').owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.owner.set('gen_config') await cfg_ori.owner.set('gen_config')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
cfg.option('dummy').value.set(True) await cfg.option('dummy').value.set(True)
assert cfg.option('dummy').owner.get() == owners.gen_config assert await cfg.option('dummy').owner.get() == owners.gen_config
assert not cfg.option('dummy').owner.isdefault() assert not await cfg.option('dummy').owner.isdefault()
def test_addowner_multiple_time(): @pytest.mark.asyncio
async def test_addowner_multiple_time():
owners.addowner("testowner2")
with pytest.raises(ConstError):
owners.addowner("testowner2") owners.addowner("testowner2")
raises(ConstError, 'owners.addowner("testowner2")')
def test_delete_owner(): @pytest.mark.asyncio
async def test_delete_owner():
owners.addowner('deleted2') owners.addowner('deleted2')
raises(ConstError, 'del(owners.deleted2)') with pytest.raises(ConstError):
del(owners.deleted2)
def test_owner_is_not_a_string(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == owners.default assert await cfg.option('dummy').owner.get() == owners.default
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu': if config_type == 'tiramisu':
assert isinstance(cfg.option('dummy').owner.get(), owners.Owner) assert isinstance(await cfg.option('dummy').owner.get(), owners.Owner)
cfg.option('dummy').value.set(True) await cfg.option('dummy').value.set(True)
assert cfg.option('dummy').owner.get() == 'user' assert await cfg.option('dummy').owner.get() == 'user'
def test_setowner_without_valid_owner(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
def test_setowner_for_value(config_type): @pytest.mark.asyncio
async def test_setowner_for_value(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
raises(ConfigError, "cfg_ori.option('dummy').owner.set('new2')") with pytest.raises(ConfigError):
cfg = get_config(cfg_ori, config_type) await cfg_ori.option('dummy').owner.set('new2')
cfg.option('dummy').value.set(False) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').owner.get() == owners.user await cfg.option('dummy').value.set(False)
assert await cfg.option('dummy').owner.get() == owners.user
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('dummy').owner.set('new2') await cfg_ori.option('dummy').owner.set('new2')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').owner.get() == owners.new2 assert await cfg.option('dummy').owner.get() == owners.new2
def test_setowner_forbidden(config_type): @pytest.mark.asyncio
async def test_setowner_forbidden(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
raises(ValueError, "cfg_ori.owner.set('default')") with pytest.raises(ValueError):
cfg = get_config(cfg_ori, config_type) await cfg_ori.owner.set('default')
cfg.option('dummy').value.set(False) cfg = await get_config(cfg_ori, config_type)
await cfg.option('dummy').value.set(False)
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
raises(ValueError, "cfg_ori.option('dummy').owner.set('default')") with pytest.raises(ValueError):
cfg = get_config(cfg_ori, config_type) await cfg_ori.option('dummy').owner.set('default')
cfg = await get_config(cfg_ori, config_type)
def test_setowner_read_only(config_type): @pytest.mark.asyncio
async def test_setowner_read_only(config_type):
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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)
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('dummy').owner.get() == 'default' assert await cfg.option('dummy').owner.get() == 'default'
cfg.option('dummy').value.set(False) await cfg.option('dummy').value.set(False)
assert cfg.option('dummy').owner.get() == owners.user assert await cfg.option('dummy').owner.get() == owners.user
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.property.read_only() await cfg_ori.property.read_only()
raises(PropertiesOptionError, with pytest.raises(PropertiesOptionError):
"cfg_ori.option('dummy').owner.set('readonly2')") await cfg_ori.option('dummy').owner.set('readonly2')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('dummy').owner.get() == owners.user assert await cfg.option('dummy').owner.get() == owners.user
def test_setowner_optiondescription(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [descr1])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(APIError, "cfg.option('tiramisu').owner.get()") with pytest.raises(APIError):
raises(APIError, "cfg.option('tiramisu').owner.set('user')") await cfg.option('tiramisu').owner.get()
with pytest.raises(APIError):
await cfg.option('tiramisu').owner.set('user')
def test_setowner_symlinkoption(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [descr1])
cfg_ori = Config(descr) cfg_ori = await Config(descr)
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('tiramisu.symdummy').owner.isdefault() assert await cfg.option('tiramisu.symdummy').owner.isdefault()
cfg.option('tiramisu.dummy').value.set(True) await cfg.option('tiramisu.dummy').value.set(True)
assert not cfg.option('tiramisu.symdummy').owner.isdefault() assert not await cfg.option('tiramisu.symdummy').owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
raises(ConfigError, "cfg_ori.option('tiramisu.symdummy').owner.set('user')") with pytest.raises(ConfigError):
await cfg_ori.option('tiramisu.symdummy').owner.set('user')
def test_owner_leadership(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [descr])
cfg_ori = Config(od) cfg_ori = await Config(od)
raises(ConfigError, "cfg_ori.option('int.str', 0).owner.set('user')") with pytest.raises(ConfigError):
cfg = get_config(cfg_ori, config_type) await cfg_ori.option('int.str', 0).owner.set('user')
cfg = await get_config(cfg_ori, config_type)
cfg.option('int.int').value.set([0, 1]) await cfg.option('int.int').value.set([0, 1])
cfg.option('int.str', 0).value.set('yes') await cfg.option('int.str', 0).value.set('yes')
assert not cfg.option('int.str', 0).owner.isdefault() assert not await cfg.option('int.str', 0).owner.isdefault()
assert cfg.option('int.str', 1).owner.isdefault() assert await cfg.option('int.str', 1).owner.isdefault()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('int.str', 0).owner.set('user') await cfg_ori.option('int.str', 0).owner.set('user')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('int.str', 0).owner.get() == owners.user assert await cfg.option('int.str', 0).owner.get() == owners.user
assert cfg.option('int.str', 1).owner.isdefault() assert await cfg.option('int.str', 1).owner.isdefault()
assert cfg.option('int.str', 0).value.get() == 'yes' assert await cfg.option('int.str', 0).value.get() == 'yes'
assert cfg.option('int.str', 1).value.get() == None assert await cfg.option('int.str', 1).value.get() == None

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from py.test import raises import pytest
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
PasswordOption, StrOption, DateOption, OptionDescription, Config, \ PasswordOption, StrOption, DateOption, OptionDescription, Config, \
@ -53,41 +53,47 @@ def make_description():
# ____________________________________________________________ # ____________________________________________________________
def test_is_hidden(config_type): @pytest.mark.asyncio
async def test_is_hidden(config_type):
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
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
raises(PropertiesOptionError, "cfg.option('gc.dummy').value.get() == False") with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() == False
# getattr # getattr
raises(PropertiesOptionError, "cfg.option('gc.dummy').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get()
def test_group_is_hidden(config_type): @pytest.mark.asyncio
async def test_group_is_hidden(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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)
raises(PropertiesOptionError, "cfg.option('gc.dummy').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
assert 'hidden' in cfg_ori.forcepermissive.option('gc').property.get() assert 'hidden' in await cfg_ori.forcepermissive.option('gc').property.get()
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
raises(PropertiesOptionError, "cfg.option('gc.float').value.get()") with pytest.raises(PropertiesOptionError):
await 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':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('gc').property.pop('hidden') await cfg_ori.forcepermissive.option('gc').property.pop('hidden')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert not 'hidden' in cfg.option('gc').property.get() assert not 'hidden' in await cfg.option('gc').property.get()
assert cfg.option('gc.float').value.get() == 2.3 assert await cfg.option('gc.float').value.get() == 2.3
#dummy est en hide #dummy est en hide
prop = [] prop = []
try: try:
cfg.option('gc.dummy').value.set(False) await 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':
@ -96,20 +102,22 @@ def test_group_is_hidden(config_type):
assert 'hidden' in prop assert 'hidden' in prop
def test_group_is_hidden_multi(config_type): @pytest.mark.asyncio
async def test_group_is_hidden_multi(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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)
raises(PropertiesOptionError, "cfg.option('objspace').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('objspace').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
assert 'hidden' in cfg_ori.forcepermissive.option('objspace').property.get() assert 'hidden' in await cfg_ori.forcepermissive.option('objspace').property.get()
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
prop = [] prop = []
try: try:
cfg.option('objspace').value.set(['std']) await 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':
@ -117,58 +125,71 @@ 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':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('objspace').property.pop('hidden') await cfg_ori.forcepermissive.option('objspace').property.pop('hidden')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert not 'hidden' in cfg.option('objspace').property.get() assert not 'hidden' in await cfg.option('objspace').property.get()
cfg.option('objspace').value.set(['std', 'thunk']) await cfg.option('objspace').value.set(['std', 'thunk'])
def test_global_show(config_type): @pytest.mark.asyncio
async def test_global_show(config_type):
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
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)
raises(PropertiesOptionError, "cfg.option('gc.dummy').value.get() == False") with pytest.raises(PropertiesOptionError):
await cfg.option('gc.dummy').value.get() == False
def test_with_many_subgroups(config_type): @pytest.mark.asyncio
async def test_with_many_subgroups(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
#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 = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert not 'hidden' in cfg.option('gc.subgroup.booltwo').property.get() assert not 'hidden' in await cfg.option('gc.subgroup.booltwo').property.get()
assert cfg.option('gc.subgroup.booltwo').value.get() is False assert await cfg.option('gc.subgroup.booltwo').value.get() is False
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.option('gc.subgroup.booltwo').property.add('hidden') await cfg_ori.option('gc.subgroup.booltwo').property.add('hidden')
def test_password_option(config_type): @pytest.mark.asyncio
async def test_password_option(config_type):
o = PasswordOption('o', '') o = PasswordOption('o', '')
d = OptionDescription('d', '', [o]) d = OptionDescription('d', '', [o])
cfg = Config(d) cfg = await Config(d)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('o').value.set('a_valid_password') await cfg.option('o').value.set('a_valid_password')
raises(ValueError, "cfg.option('o').value.set(1)") with pytest.raises(ValueError):
await cfg.option('o').value.set(1)
def test_date_option(config_type): @pytest.mark.asyncio
async def test_date_option(config_type):
o = DateOption('o', '') o = DateOption('o', '')
d = OptionDescription('d', '', [o]) d = OptionDescription('d', '', [o])
cfg = Config(d) cfg = await Config(d)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
cfg.option('o').value.set('2017-02-04') await cfg.option('o').value.set('2017-02-04')
cfg.option('o').value.set('2017-2-4') await cfg.option('o').value.set('2017-2-4')
raises(ValueError, "cfg.option('o').value.set(1)") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('o').value.set('2017-13-20')") await cfg.option('o').value.set(1)
raises(ValueError, "cfg.option('o').value.set('2017-11-31')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('o').value.set('2017-12-32')") await cfg.option('o').value.set('2017-13-20')
raises(ValueError, "cfg.option('o').value.set('2017-2-29')") with pytest.raises(ValueError):
raises(ValueError, "cfg.option('o').value.set('2-2-2017')") await cfg.option('o').value.set('2017-11-31')
raises(ValueError, "cfg.option('o').value.set('2017/2/2')") with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-12-32')
with pytest.raises(ValueError):
await cfg.option('o').value.set('2017-2-29')
with pytest.raises(ValueError):
await cfg.option('o').value.set('2-2-2017')
with pytest.raises(ValueError):
await cfg.option('o').value.set('2017/2/2')

View file

@ -8,10 +8,6 @@ from tiramisu.option import UsernameOption
from tiramisu.storage import list_sessions from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_username(): def test_username():
UsernameOption('a', '', 'string') UsernameOption('a', '', 'string')
UsernameOption('a', '', '_string') UsernameOption('a', '', '_string')

File diff suppressed because it is too large Load diff

View file

@ -3,8 +3,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from py.test import raises 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 tiramisu.storage import list_sessions
@ -37,29 +36,32 @@ def make_description():
return descr return descr
def test_root_config_answers_ok(config_type): @pytest.mark.asyncio
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]) descr = OptionDescription('tiramisu', '', [gcdummy, boolop])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
#settings = cfg.cfgimpl_get_settings() #settings = await cfg.cfgimpl_get_settings()
#settings.append('hidden') #settings.append('hidden')
assert cfg.option('dummy').value.get() is False assert await cfg.option('dummy').value.get() is False
assert cfg.option('boolop').value.get() is True assert await cfg.option('boolop').value.get() is True
#def test_optname_shall_not_start_with_numbers(): #@pytest.mark.asyncio
# async def test_optname_shall_not_start_with_numbers():
# raises(ValueError, "gcdummy = BoolOption('123dummy', 'dummy', default=False)") # raises(ValueError, "gcdummy = BoolOption('123dummy', 'dummy', default=False)")
# raises(ValueError, "descr = OptionDescription('123tiramisu', '', [])") # raises(ValueError, "descr = OptionDescription('123tiramisu', '', [])")
# #
# #
def test_option_has_an_api_name(config_type): @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]) descr = OptionDescription('tiramisu', '', [b])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('impl_has_dependency').value.get() is True assert await cfg.option('impl_has_dependency').value.get() is True
assert b.impl_has_dependency() is False assert b.impl_has_dependency() is False

View file

@ -3,8 +3,8 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from .config import config_type, get_config from .config import config_type, get_config
from py.test import raises
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 tiramisu.storage import list_sessions, delete_session
@ -20,390 +20,413 @@ def make_description():
return OptionDescription('od1', '', [u1, u2]) return OptionDescription('od1', '', [u1, u2])
def test_permissive(config_type): @pytest.mark.asyncio
async def test_permissive(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.unrestraint.permissive.add('disabled') await cfg_ori.unrestraint.permissive.add('disabled')
cfg_ori.unrestraint.permissive.pop('hidden') await cfg_ori.unrestraint.permissive.pop('hidden')
assert cfg_ori.unrestraint.permissive.get() == frozenset(['disabled']) assert await cfg_ori.unrestraint.permissive.get() == frozenset(['disabled'])
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.property.add('permissive') await cfg_ori.property.add('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
cfg.option('u1').value.get() await cfg.option('u1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.property.pop('permissive') await cfg_ori.property.pop('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
def test_permissive_add(config_type): @pytest.mark.asyncio
async def test_permissive_add(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.unrestraint.permissive.add('disabled') await cfg_ori.unrestraint.permissive.add('disabled')
assert cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) assert await cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.property.add('permissive') await cfg_ori.property.add('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
cfg.option('u1').value.get() await cfg.option('u1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.property.pop('permissive') await cfg_ori.property.pop('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'}
def test_permissive_pop(): @pytest.mark.asyncio
async def test_permissive_pop():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
cfg.property.read_write() await cfg.property.read_write()
props = frozenset() props = frozenset()
try: try:
cfg.forcepermissive.option('u1').value.get() await cfg.forcepermissive.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'}
cfg.unrestraint.permissive.add('disabled') await cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) assert await cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
cfg.forcepermissive.option('u1').value.get() await cfg.forcepermissive.option('u1').value.get()
cfg.unrestraint.permissive.pop('disabled') await cfg.unrestraint.permissive.pop('disabled')
props = frozenset() props = frozenset()
try: try:
cfg.forcepermissive.option('u1').value.get() await cfg.forcepermissive.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'}
def test_permissive_reset(): @pytest.mark.asyncio
async def test_permissive_reset():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
assert cfg.unrestraint.permissive.get() == frozenset(['hidden']) assert await cfg.unrestraint.permissive.get() == frozenset(['hidden'])
# #
cfg.unrestraint.permissive.add('disabled') await cfg.unrestraint.permissive.add('disabled')
cfg.unrestraint.permissive.pop('hidden') await cfg.unrestraint.permissive.pop('hidden')
assert cfg.unrestraint.permissive.get() == frozenset(['disabled']) assert await cfg.unrestraint.permissive.get() == frozenset(['disabled'])
# #
cfg.unrestraint.permissive.reset() await cfg.unrestraint.permissive.reset()
assert cfg.unrestraint.permissive.get() == frozenset() assert await cfg.unrestraint.permissive.get() == frozenset()
def test_permissive_mandatory(): @pytest.mark.asyncio
async def test_permissive_mandatory():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'])
cfg.unrestraint.permissive.add('mandatory') await cfg.unrestraint.permissive.add('mandatory')
cfg.unrestraint.permissive.add('disabled') await cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled']) assert await cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled'])
cfg.property.add('permissive') await cfg.property.add('permissive')
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.property.pop('permissive') await cfg.property.pop('permissive')
try: try:
cfg.option('u1').value.get() await 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'])
def test_permissive_frozen(): @pytest.mark.asyncio
async def test_permissive_frozen():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
cfg.unrestraint.permissive.pop('hidden') await cfg.unrestraint.permissive.pop('hidden')
cfg.unrestraint.permissive.add('frozen') await cfg.unrestraint.permissive.add('frozen')
cfg.unrestraint.permissive.add('disabled') await cfg.unrestraint.permissive.add('disabled')
assert cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled']) assert await cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled'])
assert cfg.permissive.get() == frozenset(['frozen', 'disabled']) assert await cfg.permissive.get() == frozenset(['frozen', 'disabled'])
try: try:
cfg.option('u1').value.set(1) await cfg.option('u1').value.set(1)
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset(['disabled']) assert frozenset(props) == frozenset(['disabled'])
cfg.property.add('permissive') await cfg.property.add('permissive')
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.pop('permissive') await cfg.property.pop('permissive')
try: try:
cfg.option('u1').value.set(1) await cfg.option('u1').value.set(1)
except PropertiesOptionError as err: except PropertiesOptionError as err:
props = err.proptype props = err.proptype
assert frozenset(props) == frozenset(['disabled']) assert frozenset(props) == frozenset(['disabled'])
def test_invalid_permissive(): @pytest.mark.asyncio
async def test_invalid_permissive():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
# FIXME raises(TypeError, "cfg.unrestraint.permissive.set(['frozen', 'disabled'])") # FIXME with pytest.raises(TypeError):
# await cfg.unrestraint.permissive.set(['frozen', 'disabled'])")
def test_forbidden_permissive(): @pytest.mark.asyncio
async def test_forbidden_permissive():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
raises(ConfigError, "cfg.permissive.add('force_default_on_freeze')") with pytest.raises(ConfigError):
raises(ConfigError, "cfg.permissive.add('force_metaconfig_on_freeze')") await cfg.permissive.add('force_default_on_freeze')
with pytest.raises(ConfigError):
await cfg.permissive.add('force_metaconfig_on_freeze')
def test_permissive_option(config_type): @pytest.mark.asyncio
async def test_permissive_option(config_type):
descr = make_description() descr = make_description()
cfg_ori = Config(descr) cfg_ori = await Config(descr)
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:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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':
cfg.send() await cfg.send()
cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) await cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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':
cfg.send() await cfg.send()
cfg_ori.property.add('permissive') await cfg_ori.property.add('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
cfg.option('u1').value.get() await cfg.option('u1').value.get()
props = frozenset() props = frozenset()
try: try:
cfg.option('u2').value.get() await 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':
cfg.send() await cfg.send()
cfg_ori.property.pop('permissive') await cfg_ori.property.pop('permissive')
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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'}
def test_permissive_option_cache(): @pytest.mark.asyncio
async def test_permissive_option_cache():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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'}
cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) await cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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'}
cfg.property.add('permissive') await cfg.property.add('permissive')
cfg.option('u1').value.get() await cfg.option('u1').value.get()
props = frozenset() props = frozenset()
try: try:
cfg.option('u2').value.get() await 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'}
cfg.property.pop('permissive') await cfg.property.pop('permissive')
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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:
cfg.option('u2').value.get() await 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'}
def test_permissive_option_mandatory(): @pytest.mark.asyncio
async def test_permissive_option_mandatory():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_only() await cfg.property.read_only()
props = frozenset() props = frozenset()
try: try:
cfg.option('u1').value.get() await 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'])
cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled'])) await cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled']))
assert cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled']) assert await cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled'])
cfg.property.add('permissive') await cfg.property.add('permissive')
cfg.option('u1').value.get() await cfg.option('u1').value.get()
cfg.property.pop('permissive') await cfg.property.pop('permissive')
try: try:
cfg.option('u1').value.get() await 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'])
def test_permissive_option_frozen(): @pytest.mark.asyncio
async def test_permissive_option_frozen():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
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.pop('permissive') await cfg.property.pop('permissive')
assert cfg.option('u1').value.get() == 1 assert await cfg.option('u1').value.get() == 1
def test_invalid_option_permissive(): @pytest.mark.asyncio
async def test_invalid_option_permissive():
descr = make_description() descr = make_description()
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
raises(TypeError, "cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled'])") with pytest.raises(TypeError):
await cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled'])
def test_remove_option_permissive(config_type): @pytest.mark.asyncio
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])
rootod = OptionDescription('rootod', '', [od1]) rootod = OptionDescription('rootod', '', [od1])
cfg_ori = Config(rootod) cfg_ori = await Config(rootod)
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)
raises(PropertiesOptionError, "cfg.option('od1.var1').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('od1.var1').value.get() == 'value' assert await cfg.option('od1.var1').value.get() == 'value'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset()) await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset())
assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset()
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
raises(PropertiesOptionError, "cfg.option('od1.var1').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get()
def test_reset_option_permissive(config_type): @pytest.mark.asyncio
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])
rootod = OptionDescription('rootod', '', [od1]) rootod = OptionDescription('rootod', '', [od1])
cfg_ori = Config(rootod) cfg_ori = await Config(rootod)
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)
raises(PropertiesOptionError, "cfg.option('od1.var1').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get()
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
assert cfg.option('od1.var1').value.get() == 'value' assert await cfg.option('od1.var1').value.get() == 'value'
if config_type == 'tiramisu-api': if config_type == 'tiramisu-api':
cfg.send() await cfg.send()
cfg_ori.forcepermissive.option('od1.var1').permissive.reset() await cfg_ori.forcepermissive.option('od1.var1').permissive.reset()
assert cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset()
cfg = get_config(cfg_ori, config_type) cfg = await get_config(cfg_ori, config_type)
raises(PropertiesOptionError, "cfg.option('od1.var1').value.get()") with pytest.raises(PropertiesOptionError):
await cfg.option('od1.var1').value.get()

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,9 @@
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
import pytest
from py.test import raises from py.test import raises
import warnings
try: try:
from tiramisu.setting import OptionBag, ConfigBag from tiramisu.setting import OptionBag, ConfigBag
@ -19,6 +21,7 @@ from tiramisu.storage import list_sessions, delete_session
def teardown_function(function): def teardown_function(function):
with warnings.catch_warnings(record=True) as w:
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
@ -72,7 +75,8 @@ def test_slots_option():
del c del c
def test_slots_option_readonly(): @pytest.mark.asyncio
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', '')
@ -103,7 +107,7 @@ def test_slots_option_readonly():
o._name = 'o' o._name = 'o'
p._name = 'p' p._name = 'p'
q._name = 'q' q._name = 'q'
Config(m) await Config(m)
raises(AttributeError, "a._requires = 'a'") raises(AttributeError, "a._requires = 'a'")
raises(AttributeError, "b._requires = 'b'") raises(AttributeError, "b._requires = 'b'")
raises(AttributeError, "c._requires = 'c'") raises(AttributeError, "c._requires = 'c'")
@ -130,36 +134,39 @@ def test_slots_option_readonly():
# assert slots == set(OptionDescription.__slots__) # assert slots == set(OptionDescription.__slots__)
def test_slots_config(): @pytest.mark.asyncio
async def test_slots_config():
od1 = OptionDescription('a', '', []) od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1]) od2 = OptionDescription('a', '', [od1])
c = Config(od2) c = await Config(od2)
raises(AttributeError, "c._config_bag.context.x = 1") raises(AttributeError, "c._config_bag.context.x = 1")
raises(AttributeError, "c._config_bag.context.cfgimpl_x = 1") raises(AttributeError, "c._config_bag.context.cfgimpl_x = 1")
option_bag = OptionBag() option_bag = OptionBag()
option_bag.set_option(od2, option_bag.set_option(od2,
'a', 'a',
None, None,
ConfigBag(c._config_bag.context)) ConfigBag(c._config_bag.context, None, None))
sc = c._config_bag.context.get_subconfig(option_bag) sc = await c._config_bag.context.get_subconfig(option_bag)
assert isinstance(sc, SubConfig) assert isinstance(sc, SubConfig)
raises(AttributeError, "sc.x = 1") raises(AttributeError, "sc.x = 1")
raises(AttributeError, "sc.cfgimpl_x = 1") raises(AttributeError, "sc.cfgimpl_x = 1")
def test_slots_setting(): @pytest.mark.asyncio
async def test_slots_setting():
od1 = OptionDescription('a', '', []) od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1]) od2 = OptionDescription('a', '', [od1])
c = Config(od2) c = await Config(od2)
s = c._config_bag.context.cfgimpl_get_settings() s = c._config_bag.context.cfgimpl_get_settings()
s s
raises(AttributeError, "s.x = 1") raises(AttributeError, "s.x = 1")
def test_slots_value(): @pytest.mark.asyncio
async def test_slots_value():
od1 = OptionDescription('a', '', []) od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1]) od2 = OptionDescription('a', '', [od1])
c = Config(od2) c = await Config(od2)
v = c._config_bag.context.cfgimpl_get_values() v = c._config_bag.context.cfgimpl_get_values()
v v
raises(AttributeError, "v.x = 1") raises(AttributeError, "v.x = 1")

View file

@ -5,11 +5,13 @@ from tiramisu import BoolOption, StrOption, SymLinkOption, OptionDescription, Dy
Calculation, Params, ParamOption, ParamValue, calc_value, Config Calculation, Params, ParamOption, ParamValue, calc_value, Config
from pickle import dumps from pickle import dumps
from py.test import raises from py.test import raises
import sys import pytest
import sys, warnings
from tiramisu.storage import list_sessions from tiramisu.storage import list_sessions
def teardown_function(function): def teardown_function(function):
with warnings.catch_warnings(record=True) as w:
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
@ -225,14 +227,16 @@ def test_diff_opt():
raises(NotImplementedError, "dumps(o1)") raises(NotImplementedError, "dumps(o1)")
def test_diff_information_config(): @pytest.mark.asyncio
async def test_diff_information_config():
b = BoolOption('b', '') b = BoolOption('b', '')
b.impl_set_information('info', 'oh') b.impl_set_information('info', 'oh')
b.impl_set_information('info1', 'oh') b.impl_set_information('info1', 'oh')
b.impl_set_information('info2', 'oh') b.impl_set_information('info2', 'oh')
o = OptionDescription('o', '', [b]) o = OptionDescription('o', '', [b])
o1 = OptionDescription('o1', '', [o]) o1 = OptionDescription('o1', '', [o])
c = Config(o1)._config_bag.context d = await Config(o1)
c = d._config_bag.context
raises(NotImplementedError, "dumps(c)") raises(NotImplementedError, "dumps(c)")

View file

@ -3,6 +3,7 @@ from .autopath import do_autopath
do_autopath() do_autopath()
from py.test import raises from py.test import raises
import pytest
from tiramisu.error import ConfigError from tiramisu.error import ConfigError
from tiramisu import Config, BoolOption, OptionDescription, Leadership, \ from tiramisu import Config, BoolOption, OptionDescription, Leadership, \
@ -14,339 +15,359 @@ def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_non_persistent(): @pytest.mark.asyncio
async def test_non_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
Config(o, session_id='test_non_persistent') await Config(o, session_id='test_non_persistent')
def test_list(): @pytest.mark.asyncio
async def test_list():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
c = Config(o, session_id='test_non_persistent') cfg = await Config(o, session_id='test_non_persistent')
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert 'test_non_persistent' in list_sessions() assert 'test_non_persistent' in list_sessions()
del(c) del(cfg)
assert 'test_non_persistent' not in list_sessions() assert 'test_non_persistent' not in list_sessions()
def test_delete_not_persistent(): @pytest.mark.asyncio
async def test_delete_not_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if not default_storage.is_persistent(): if not default_storage.is_persistent():
c = Config(o, session_id='not_test_persistent') cfg = await Config(o, session_id='not_test_persistent')
assert 'not_test_persistent' in list_sessions() assert 'not_test_persistent' in list_sessions()
del c del cfg
assert 'not_test_persistent' not in list_sessions() assert 'not_test_persistent' not in list_sessions()
# #
c = Config(o, session_id='not_test_persistent') cfg = await Config(o, session_id='not_test_persistent')
raises(ValueError, "delete_session('not_test_persistent')") raises(ValueError, "delete_session('not_test_persistent')")
def test_create_persistent(): @pytest.mark.asyncio
async def test_create_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
Config(o, session_id='test_persistent', persistent=True) await Config(o, session_id='test_persistent', persistent=True)
delete_session('test_persistent') delete_session('test_persistent')
def test_create_delete_not_persistent(): @pytest.mark.asyncio
async def test_create_delete_not_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if not default_storage.is_persistent(): if not default_storage.is_persistent():
raises(ValueError, "delete_session('test_persistent')") raises(ValueError, "delete_session('test_persistent')")
def test_list_sessions_persistent(): @pytest.mark.asyncio
async def test_list_sessions_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert 'test_persistent' in list_sessions() assert 'test_persistent' in list_sessions()
delete_session('test_persistent') delete_session('test_persistent')
def test_delete_session_persistent(): @pytest.mark.asyncio
async def test_delete_session_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
Config(o, session_id='test_persistent', persistent=True) await Config(o, session_id='test_persistent', persistent=True)
assert 'test_persistent' in list_sessions() assert 'test_persistent' in list_sessions()
delete_session('test_persistent') delete_session('test_persistent')
assert 'test_persistent' not in list_sessions() assert 'test_persistent' not in list_sessions()
def test_create_persistent_retrieve(): @pytest.mark.asyncio
async def test_create_persistent_retrieve():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert c.option('b').value.get() is True assert await cfg.option('b').value.get() is True
del c del cfg
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is True assert await cfg.option('b').value.get() is True
assert 'test_persistent' in list_sessions() assert 'test_persistent' in list_sessions()
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
def test_two_persistent(): @pytest.mark.asyncio
async def test_two_persistent():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c2 = Config(o, session_id='test_persistent', persistent=True) cfg2 = await Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache') await cfg2.property.pop('cache')
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
assert c2.option('b').value.get() is None assert await cfg2.option('b').value.get() is None
# #
c.option('b').value.set(False) await cfg.option('b').value.set(False)
assert c.option('b').value.get() is False assert await cfg.option('b').value.get() is False
assert c2.option('b').value.get() is False assert await cfg2.option('b').value.get() is False
# #
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert c.option('b').value.get() is True assert await cfg.option('b').value.get() is True
assert c2.option('b').value.get() is True assert await cfg2.option('b').value.get() is True
delete_session('test_persistent') delete_session('test_persistent')
def test_create_persistent_retrieve_owner(): @pytest.mark.asyncio
async def test_create_persistent_retrieve_owner():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').owner.isdefault() assert await cfg.option('b').owner.isdefault()
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert c.option('b').value.get() assert await cfg.option('b').value.get()
assert c.option('b').owner.get() == 'user' assert await cfg.option('b').owner.get() == 'user'
##owners.addowner('persistentowner') ##owners.addowner('persistentowner')
c.option('b').owner.set('persistentowner') await cfg.option('b').owner.set('persistentowner')
assert c.option('b').owner.get() == 'persistentowner' assert await cfg.option('b').owner.get() == 'persistentowner'
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.option('b').owner.set('persistentowner') await cfg.option('b').owner.set('persistentowner')
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
assert c.option('b').owner.isdefault() assert await cfg.option('b').owner.isdefault()
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
def test_create_persistent_retrieve_owner_leadership(): @pytest.mark.asyncio
async def test_create_persistent_retrieve_owner_leadership():
a = BoolOption('a', '', multi=True) a = BoolOption('a', '', multi=True)
b = BoolOption('b', '', multi=True) b = BoolOption('b', '', multi=True)
o = Leadership('a', '', [a, b]) o = Leadership('a', '', [a, b])
o1 = OptionDescription('a', '', [o]) o1 = OptionDescription('a', '', [o])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o1, session_id='test_persistent', persistent=True) cfg = await Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').owner.isdefault() assert await cfg.option('a.a').owner.isdefault()
c.option('a.a').value.set([True, False]) await cfg.option('a.a').value.set([True, False])
c.option('a.b', 1).value.set(True) await cfg.option('a.b', 1).value.set(True)
assert c.option('a.a').owner.get() == 'user' assert await cfg.option('a.a').owner.get() == 'user'
assert c.option('a.b', 0).owner.isdefault() assert await cfg.option('a.b', 0).owner.isdefault()
assert c.option('a.b', 1).owner.get() == 'user' assert await cfg.option('a.b', 1).owner.get() == 'user'
#owners.addowner('persistentowner2') #owners.addowner('persistentowner2')
c.option('a.b', 1).owner.set('persistentowner2') await cfg.option('a.b', 1).owner.set('persistentowner2')
c.option('a.b', 0).value.set(True) await cfg.option('a.b', 0).value.set(True)
assert c.option('a.b', 0).owner.get() == 'user' assert await cfg.option('a.b', 0).owner.get() == 'user'
assert c.option('a.b', 1).owner.get() == 'persistentowner2' assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2'
assert c.option('a.a').value.get() == [True, False] assert await cfg.option('a.a').value.get() == [True, False]
del c del cfg
# #
c = Config(o1, session_id='test_persistent', persistent=True) cfg = await Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').value.get() == [True, False] assert await cfg.option('a.a').value.get() == [True, False]
assert c.option('a.b', 0).owner.get() == 'user' assert await cfg.option('a.b', 0).owner.get() == 'user'
assert c.option('a.b', 1).owner.get() == 'persistentowner2' assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2'
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
# #
c = Config(o1, session_id='test_persistent', persistent=True) cfg = await Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').value.get() == [] assert await cfg.option('a.a').value.get() == []
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
def test_two_persistent_owner(): @pytest.mark.asyncio
async def test_two_persistent_owner():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache') await cfg.property.pop('cache')
c2 = Config(o, session_id='test_persistent', persistent=True) cfg2 = await Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache') await cfg2.property.pop('cache')
assert c.option('b').owner.isdefault() assert await cfg.option('b').owner.isdefault()
assert c2.option('b').owner.isdefault() assert await cfg2.option('b').owner.isdefault()
c.option('b').value.set(False) await cfg.option('b').value.set(False)
assert c.option('b').owner.get() == 'user' assert await cfg.option('b').owner.get() == 'user'
assert c2.option('b').owner.get() == 'user' assert await cfg2.option('b').owner.get() == 'user'
c.option('b').owner.set('persistent') await cfg.option('b').owner.set('persistent')
assert c.option('b').owner.get() == 'persistent' assert await cfg.option('b').owner.get() == 'persistent'
assert c2.option('b').owner.get() == 'persistent' assert await cfg2.option('b').owner.get() == 'persistent'
delete_session('test_persistent') delete_session('test_persistent')
def test_create_persistent_retrieve_information(): @pytest.mark.asyncio
async def test_create_persistent_retrieve_information():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.information.set('info', 'string') await cfg.information.set('info', 'string')
assert c.information.get('info') == 'string' assert await cfg.information.get('info') == 'string'
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.information.get('info') == 'string' assert await cfg.information.get('info') == 'string'
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.information.get('info', None) is None assert await cfg.information.get('info', None) is None
delete_session(c.config.name()) delete_session(await cfg.config.name())
del c del cfg
def test_two_persistent_information(): @pytest.mark.asyncio
async def test_two_persistent_information():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache') await cfg.property.pop('cache')
c.information.set('info', 'string') await cfg.information.set('info', 'string')
assert c.information.get('info') == 'string' assert await cfg.information.get('info') == 'string'
c2 = Config(o, session_id='test_persistent', persistent=True) cfg2 = await Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache') await cfg2.property.pop('cache')
assert c2.information.get('info') == 'string' assert await cfg2.information.get('info') == 'string'
delete_session('test_persistent') delete_session('test_persistent')
def test_two_different_persistents(): @pytest.mark.asyncio
async def test_two_different_persistents():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache') await cfg.property.pop('cache')
d = Config(o, session_id='test_persistent2', persistent=True) cfg2 = await Config(o, session_id='test_persistent2', persistent=True)
d.property.pop('cache') await cfg2.property.pop('cache')
c.option('b').property.add('test') await cfg.option('b').property.add('test')
assert c.option('b').property.get() == {'test'} assert await cfg.option('b').property.get() == {'test'}
assert d.option('b').property.get() == set() assert await cfg2.option('b').property.get() == set()
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
assert d.option('b').value.get() is None assert await cfg2.option('b').value.get() is None
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert c.option('b').value.get() == True assert await cfg.option('b').value.get() == True
assert d.option('b').value.get() is None assert await cfg2.option('b').value.get() is None
delete_session('test_persistent') delete_session('test_persistent')
delete_session('test_persistent2') delete_session('test_persistent2')
def test_two_different_information(): @pytest.mark.asyncio
async def test_two_different_information():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.information.set('a', 'a') await cfg.information.set('a', 'a')
d = Config(o, session_id='test_persistent2', persistent=True) cfg2 = await Config(o, session_id='test_persistent2', persistent=True)
d.information.set('a', 'b') await cfg2.information.set('a', 'b')
assert c.information.get('a') == 'a' assert await cfg.information.get('a') == 'a'
assert d.information.get('a') == 'b' assert await cfg2.information.get('a') == 'b'
delete_session('test_persistent') delete_session('test_persistent')
delete_session('test_persistent2') delete_session('test_persistent2')
def test_exportation_importation(): @pytest.mark.asyncio
async def test_exportation_importation():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
d = Config(o, session_id='test_persistent2', persistent=True) cfg2 = await Config(o, session_id='test_persistent2', persistent=True)
e = Config(o, session_id='test_persistent3', persistent=True) cfg3 = await Config(o, session_id='test_persistent3', persistent=True)
c.owner.set('export') await cfg.owner.set('export')
assert c.option('b').value.get() is None assert await cfg.option('b').value.get() is None
c.option('b').value.set(True) await cfg.option('b').value.set(True)
assert c.option('b').value.get() is True assert await cfg.option('b').value.get() is True
assert c.owner.get() == 'export' assert await cfg.owner.get() == 'export'
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert c.owner.get() == 'export' assert await cfg.owner.get() == 'export'
assert c.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg.value.exportation() == [['b'], [None], [True], ['export']]
d.value.importation(c.value.exportation()) await cfg2.value.importation(await cfg.value.exportation())
assert c.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg.value.exportation() == [['b'], [None], [True], ['export']]
assert c.owner.get() == 'export' assert await cfg.owner.get() == 'export'
assert d.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']]
assert d.owner.get() == 'user' assert await cfg2.owner.get() == 'user'
del d del cfg2
# #
d = Config(o, session_id='test_persistent2', persistent=True) cfg2 = await Config(o, session_id='test_persistent2', persistent=True)
assert d.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']]
assert d.owner.get() == 'user' assert await cfg2.owner.get() == 'user'
# #
e.value.importation(c.value.exportation(with_default_owner=True)) await cfg3.value.importation(await cfg.value.exportation(with_default_owner=True))
assert e.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']]
assert e.owner.get() == 'export' assert await cfg3.owner.get() == 'export'
del e del cfg3
# #
e = Config(o, session_id='test_persistent3', persistent=True) cfg3 = await Config(o, session_id='test_persistent3', persistent=True)
assert e.value.exportation() == [['b'], [None], [True], ['export']] assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']]
assert e.owner.get() == 'export' assert await cfg3.owner.get() == 'export'
# #
delete_session('test_persistent') delete_session('test_persistent')
delete_session('test_persistent2') delete_session('test_persistent2')
delete_session('test_persistent3') delete_session('test_persistent3')
def test_create_persistent_context_property(): @pytest.mark.asyncio
async def test_create_persistent_context_property():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.property.add('persistent') await cfg.property.add('persistent')
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert 'persistent' in c.property.get() assert 'persistent' in await cfg.property.get()
del c del cfg
delete_session('test_persistent') delete_session('test_persistent')
def test_create_persistent_context_property_metaconfig(): @pytest.mark.asyncio
async def test_create_persistent_context_property_metaconfig():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.property.add('persistent') await cfg.property.add('persistent')
del c del cfg
# #
m = MetaConfig([], optiondescription=o) meta = await MetaConfig([], optiondescription=o)
c = m.config.new(session_id='test_persistent', persistent=True) cfg = await meta.config.new(session_id='test_persistent', persistent=True)
assert 'persistent' in c.property.get() assert 'persistent' in await cfg.property.get()
del c del cfg
delete_session('test_persistent') delete_session('test_persistent')
def test_create_persistent_property(): @pytest.mark.asyncio
async def test_create_persistent_property():
b = BoolOption('b', '') b = BoolOption('b', '')
o = OptionDescription('od', '', [b]) o = OptionDescription('od', '', [b])
if default_storage.is_persistent(): if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
c.option('b').property.add('persistent') await cfg.option('b').property.add('persistent')
del c del cfg
# #
c = Config(o, session_id='test_persistent', persistent=True) cfg = await Config(o, session_id='test_persistent', persistent=True)
assert 'persistent' in c.option('b').property.get() assert 'persistent' in await cfg.option('b').property.get()
del c del cfg
delete_session('test_persistent') delete_session('test_persistent')

View file

@ -2,6 +2,8 @@
from .autopath import do_autopath from .autopath import do_autopath
do_autopath() do_autopath()
from py.test import raises from py.test import raises
import pytest
import warnings
from tiramisu.api import TIRAMISU_VERSION from tiramisu.api import TIRAMISU_VERSION
@ -13,6 +15,7 @@ from tiramisu.storage import list_sessions
def teardown_function(function): def teardown_function(function):
with warnings.catch_warnings(record=True) as w:
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
@ -31,11 +34,13 @@ def return_list2(value=None):
return [['val', 'val']] return [['val', 'val']]
def test_unknown_multi(): @pytest.mark.asyncio
async def test_unknown_multi():
raises(ValueError, "StrOption('multi', '', multi='unknown')") raises(ValueError, "StrOption('multi', '', multi='unknown')")
def test_submulti(): @pytest.mark.asyncio
async def test_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2: if TIRAMISU_VERSION == 2:
default_multi = 'yes' default_multi = 'yes'
@ -44,22 +49,24 @@ def test_submulti():
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od) cfg = await Config(od)
assert api.option('multi').option.ismulti() assert await cfg.option('multi').option.ismulti()
assert api.option('multi').option.issubmulti() assert await cfg.option('multi').option.issubmulti()
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == [] assert await cfg.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
assert api.option('multi3').value.get() == [['yes']] assert await cfg.option('multi3').value.get() == [['yes']]
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
def test_submulti_default_multi_not_list(): @pytest.mark.asyncio
async def test_submulti_default_multi_not_list():
raises(ValueError, "StrOption('multi2', '', default_multi='yes', multi=submulti)") raises(ValueError, "StrOption('multi2', '', default_multi='yes', multi=submulti)")
def test_append_submulti(): @pytest.mark.asyncio
async def test_append_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2: if TIRAMISU_VERSION == 2:
default_multi = 'yes' default_multi = 'yes'
@ -68,34 +75,35 @@ def test_append_submulti():
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od) cfg = await Config(od)
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').value.get() == [] assert await cfg.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
api.option('multi').value.set([undefined]) await cfg.option('multi').value.set([undefined])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [[]] assert await cfg.option('multi').value.get() == [[]]
api.option('multi').value.set([undefined, ['no']]) await cfg.option('multi').value.set([undefined, ['no']])
assert api.option('multi').value.get() == [[], ['no']] assert await cfg.option('multi').value.get() == [[], ['no']]
# #
assert api.option('multi2').value.get() == [] assert await cfg.option('multi2').value.get() == []
assert api.option('multi2').owner.get() == owners.default assert await cfg.option('multi2').owner.get() == owners.default
api.option('multi2').value.set([undefined]) await cfg.option('multi2').value.set([undefined])
assert api.option('multi2').owner.get() == owner assert await cfg.option('multi2').owner.get() == owner
assert api.option('multi2').value.get() == [['yes']] assert await cfg.option('multi2').value.get() == [['yes']]
api.option('multi2').value.set([undefined, ['no']]) await cfg.option('multi2').value.set([undefined, ['no']])
assert api.option('multi2').value.get() == [['yes'], ['no']] assert await cfg.option('multi2').value.get() == [['yes'], ['no']]
# #
assert api.option('multi3').value.get() == [['yes']] assert await cfg.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([undefined, undefined]) await cfg.option('multi3').value.set([undefined, undefined])
assert api.option('multi3').owner.get() == owner assert await cfg.option('multi3').owner.get() == owner
assert api.option('multi3').value.get() == [['yes'], []] assert await cfg.option('multi3').value.get() == [['yes'], []]
api.option('multi3').value.set([undefined, undefined, ['no']]) await cfg.option('multi3').value.set([undefined, undefined, ['no']])
assert api.option('multi3').value.get() == [['yes'], [], ['no']] assert await cfg.option('multi3').value.get() == [['yes'], [], ['no']]
def test_append_unvalide_submulti(): @pytest.mark.asyncio
async def test_append_unvalide_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2: if TIRAMISU_VERSION == 2:
default_multi = 'yes' default_multi = 'yes'
@ -104,26 +112,30 @@ def test_append_unvalide_submulti():
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od) cfg = await Config(od)
assert api.option('multi').value.get() == [] assert await cfg.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
raises(ValueError, "api.option('multi').value.set([[1]])") with pytest.raises(ValueError):
assert api.option('multi').value.get() == [] await cfg.option('multi').value.set([[1]])
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').value.get() == []
assert await cfg.option('multi').owner.get() == owners.default
# #
assert api.option('multi2').value.get() == [] assert await cfg.option('multi2').value.get() == []
raises(ValueError, "api.option('multi2').value.set(['no'])") with pytest.raises(ValueError):
assert api.option('multi').owner.get() == owners.default await cfg.option('multi2').value.set(['no'])
assert api.option('multi2').value.get() == [] assert await cfg.option('multi').owner.get() == owners.default
assert await cfg.option('multi2').value.get() == []
# #
assert api.option('multi3').value.get() == [['yes']] assert await cfg.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').owner.get() == owners.default
raises(ValueError, "api.option('multi3').value.set([[1]])") with pytest.raises(ValueError):
assert api.option('multi3').value.get() == [['yes']] await cfg.option('multi3').value.set([[1]])
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').value.get() == [['yes']]
assert await cfg.option('multi3').owner.get() == owners.default
def test_pop_submulti(): @pytest.mark.asyncio
async def test_pop_submulti():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2: if TIRAMISU_VERSION == 2:
default_multi = 'yes' default_multi = 'yes'
@ -132,304 +144,330 @@ def test_pop_submulti():
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3]) od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od) cfg = await Config(od)
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').value.get() == [] assert await cfg.option('multi').value.get() == []
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').owner.get() == owners.default
api.option('multi').value.set([['no', 'yes'], ['peharps']]) await cfg.option('multi').value.set([['no', 'yes'], ['peharps']])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['no', 'yes'], ['peharps']] assert await cfg.option('multi').value.get() == [['no', 'yes'], ['peharps']]
# #
assert api.option('multi3').value.get() == [['yes']] assert await cfg.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([]) await cfg.option('multi3').value.set([])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi3').value.get() == [] assert await cfg.option('multi3').value.get() == []
api.option('multi3').value.reset() await cfg.option('multi3').value.reset()
assert api.option('multi3').owner.get() == owners.default assert await cfg.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([[]]) await cfg.option('multi3').value.set([[]])
assert api.option('multi3').owner.get() == owner assert await cfg.option('multi3').owner.get() == owner
assert api.option('multi3').value.get() == [[]] assert await cfg.option('multi3').value.get() == [[]]
def test_callback_submulti_str(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [multi])
api = Config(od) cfg = await Config(od)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == [['val']] assert await cfg.option('multi').value.get() == [['val']]
api.option('multi').value.set([['val'], undefined]) await cfg.option('multi').value.set([['val'], undefined])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['val'], ['val']] assert await cfg.option('multi').value.get() == [['val'], ['val']]
api.option('multi').value.reset() await cfg.option('multi').value.reset()
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
def test_callback_submulti_list(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [multi])
api = Config(od) cfg = await Config(od)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').value.get() == [['val', 'val']] assert await cfg.option('multi').value.get() == [['val', 'val']]
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
api.option('multi').value.set([['val', 'val'], undefined]) await cfg.option('multi').value.set([['val', 'val'], undefined])
#assert api.option('multi').owner.get() == owner #assert await cfg.option('multi').owner.get() == owner
#assert api.option('multi').value.get() == [['val', 'val'], ['val', 'val']] #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val']]
#api.option('multi').value.set([['val', 'val'], undefined, undefined]) #await cfg.option('multi').value.set([['val', 'val'], undefined, undefined])
#assert api.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']] #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']]
#api.option('multi').value.reset() #await cfg.option('multi').value.reset()
#assert api.option('multi').owner.get() == owners.default #assert await cfg.option('multi').owner.get() == owners.default
def test_callback_submulti_list_list(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [multi])
api = Config(od) cfg = await Config(od)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').value.get() == [['val', 'val']] assert await cfg.option('multi').value.get() == [['val', 'val']]
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
api.option('multi').value.set([['val', 'val'], undefined]) await cfg.option('multi').value.set([['val', 'val'], undefined])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['val', 'val'], []] assert await cfg.option('multi').value.get() == [['val', 'val'], []]
api.option('multi').value.reset() await cfg.option('multi').value.reset()
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
def test_groups_with_leader_submulti(): @pytest.mark.asyncio
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
def test_groups_with_leader_in_config_submulti(): @pytest.mark.asyncio
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]) od = OptionDescription('root', '', [interface1])
Config(od) await Config(od)
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
def test_values_with_leader_and_followers_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.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"])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
api.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'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
raises(ValueError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')") with pytest.raises(ValueError):
raises(ValueError, "api.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')
with pytest.raises(ValueError):
await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']])
def test_reset_values_with_leader_and_followers_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.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'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
# #
api.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'])
api.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'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner
api.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_and_followers_follower_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
raises(LeadershipError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])") with pytest.raises(LeadershipError):
api.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'])
api.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'])
api.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.set(['255.255.255.0'])
api.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', '255.255.255.0'])
api.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.reset()
api.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'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) assert await 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'])
def test_values_with_leader_and_leadership_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
api.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"])
api.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.set(["192.168.230.145", "192.168.230.145"])
api.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'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0']) await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0'] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0']
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
api.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_owner_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.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'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.reset() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
def test_values_with_leader_disabled_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
api.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'])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
api.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'])
api.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.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
api.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') await cfg.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.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.set(['192.168.230.145', '192.168.230.145'])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
#delete with value in disabled var #delete with value in disabled var
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled')
api.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'])
api.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.set(['192.168.230.145'])
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
def test_leader_is_submulti(): @pytest.mark.asyncio
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]) maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig) cfg = await Config(maconfig)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert interface1.impl_get_group_type() == groups.leadership assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
api.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"]])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]] assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]]) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
api.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["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"]]
raises(ValueError, "api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1'])") with pytest.raises(ValueError):
await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1'])
def test_callback_submulti(): @pytest.mark.asyncio
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]) od = OptionDescription('multi', '', [multi, multi2])
api = Config(od) cfg = await Config(od)
api.property.read_write() await cfg.property.read_write()
owner = api.owner.get() owner = await cfg.owner.get()
assert api.option('multi').owner.get() == owners.default assert await cfg.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == [] assert await cfg.option('multi').value.get() == []
assert api.option('multi2').value.get() == [] assert await cfg.option('multi2').value.get() == []
api.option('multi').value.set([['val']]) await cfg.option('multi').value.set([['val']])
assert api.option('multi').owner.get() == owner assert await cfg.option('multi').owner.get() == owner
assert api.option('multi2').owner.get() == owners.default assert await cfg.option('multi2').owner.get() == owners.default
assert api.option('multi').value.get() == [['val']] assert await cfg.option('multi').value.get() == [['val']]
assert api.option('multi2').value.get() == [['val']] assert await cfg.option('multi2').value.get() == [['val']]
def test_submulti_unique(): @pytest.mark.asyncio
async def test_submulti_unique():
i = IntOption('int', '', multi=submulti, properties=('unique',)) i = IntOption('int', '', multi=submulti, properties=('unique',))
o = OptionDescription('od', '', [i]) o = OptionDescription('od', '', [i])
api = Config(o) cfg = await Config(o)
assert api.option('int').value.get() == [] assert await cfg.option('int').value.get() == []
api.option('int').value.set([[0]]) await cfg.option('int').value.set([[0]])
assert api.option('int').value.get() == [[0]] assert await cfg.option('int').value.get() == [[0]]
raises(ValueError, "api.option('int').value.set([[0, 0]])") with pytest.raises(ValueError):
api.option('int').value.set([[0], [0]]) await cfg.option('int').value.set([[0, 0]])
raises(ValueError, "api.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]])") await cfg.option('int').value.set([[0], [0]])
api.option('int').value.set([[0, 4, 5, 6], [0]]) with pytest.raises(ValueError):
await 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]])
def test_multi_submulti_meta(): @pytest.mark.asyncio
async def test_multi_submulti_meta():
multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti)
od = OptionDescription('od', '', [multi]) od = OptionDescription('od', '', [multi])
conf1 = Config(od, session_id='conf1') cfg = await Config(od, session_id='cfg')
conf1.property.read_write() await cfg.property.read_write()
conf2 = Config(od, session_id='conf2') cfg2 = await Config(od, session_id='cfg2')
conf2.property.read_write() await cfg2.property.read_write()
meta = MetaConfig([conf1, conf2]) meta = await MetaConfig([cfg, cfg2])
meta.property.read_write() await meta.property.read_write()
meta.option('multi').value.set([['val']]) await meta.option('multi').value.set([['val']])
assert meta.option('multi').value.get() == [['val']] assert await meta.option('multi').value.get() == [['val']]
meta.config('conf1').option('multi').value.set([['val', None]]) newcfg = await meta.config('cfg')
assert conf1.option('multi').value.get() == [['val', None]] await newcfg.option('multi').value.set([['val', None]])
assert meta.config('conf1').option('multi').value.get() == [['val', None]] assert await cfg.option('multi').value.get() == [['val', None]]
assert meta.option('multi').value.get() == [['val']] newcfg = await meta.config('cfg')
assert await newcfg.option('multi').value.get() == [['val', None]]
assert await meta.option('multi').value.get() == [['val']]
def test_multi_submulti_meta_no_cache(): @pytest.mark.asyncio
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]) od = OptionDescription('od', '', [multi])
conf1 = Config(od, session_id='conf1') cfg = await Config(od, session_id='cfg')
conf1.property.read_write() await cfg.property.read_write()
conf2 = Config(od, session_id='conf2') cfg2 = await Config(od, session_id='cfg2')
conf1.property.read_write() await cfg.property.read_write()
meta = MetaConfig([conf1, conf2]) meta = await MetaConfig([cfg, cfg2])
meta.property.read_write() await meta.property.read_write()
meta.property.pop('cache') await meta.property.pop('cache')
meta.option('multi').value.set([['val']]) await meta.option('multi').value.set([['val']])
assert meta.option('multi').value.get() == [['val']] assert await meta.option('multi').value.get() == [['val']]
meta.config('conf1').option('multi').value.set([['val', None]]) newcfg = await meta.config('cfg')
assert conf1.option('multi').value.get() == [['val', None]] await newcfg.option('multi').value.set([['val', None]])
assert meta.config('conf1').option('multi').value.get() == [['val', None]] assert await cfg.option('multi').value.get() == [['val', None]]
assert meta.option('multi').value.get() == [['val']] newcfg = await meta.config('cfg')
assert await newcfg.option('multi').value.get() == [['val', None]]
assert await meta.option('multi').value.get() == [['val']]

View file

@ -1,5 +1,5 @@
# coding: utf-8 # coding: utf-8
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 from .config import config_type, get_config
@ -20,108 +20,121 @@ def return_value():
#____________________________________________________________ #____________________________________________________________
def test_symlink_option(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('s1.b').value.get() is False assert await cfg.option('s1.b').value.get() is False
cfg.option("s1.b").value.set(True) await cfg.option("s1.b").value.set(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) await cfg.option('s1.b').value.set(True)
assert cfg.option('s1.b').value.get() is True assert await cfg.option('s1.b').value.get() is True
assert cfg.option('c').value.get() is 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
def test_symlink_assign_option(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ConfigError, "cfg.option('c').value.set(True)") with pytest.raises(ConfigError):
await cfg.option('c').value.set(True)
def test_symlink_del_option(config_type): @pytest.mark.asyncio
async def test_symlink_del_option(config_type):
boolopt = BoolOption("b", "", default=False) boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt) linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ConfigError, "cfg.option('c').value.reset()") with pytest.raises(ConfigError):
await cfg.option('c').value.reset()
def test_symlink_addproperties(): @pytest.mark.asyncio
async 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]) descr = OptionDescription('opt', '', [boolopt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
raises(TypeError, "cfg.option('c').property.add('new')") with pytest.raises(TypeError):
await cfg.option('c').property.add('new')
try: try:
cfg.option('c').property.reset() await cfg.option('c').property.reset()
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
def test_symlink_getpermissive(): @pytest.mark.asyncio
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]) descr = OptionDescription('opt', '', [boolopt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
cfg.option('b').permissive.set(frozenset(['perm'])) await cfg.option('b').permissive.set(frozenset(['perm']))
cfg.option('c').permissive.get() == frozenset(['perm']) await cfg.option('c').permissive.get() == frozenset(['perm'])
def test_symlink_addpermissives(): @pytest.mark.asyncio
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]) descr = OptionDescription('opt', '', [boolopt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
raises(TypeError, "cfg.option('c').permissive.set(frozenset(['new']))") with pytest.raises(TypeError):
await cfg.option('c').permissive.set(frozenset(['new']))
try: try:
cfg.option('c').permissive.reset() await cfg.option('c').permissive.reset()
except AssertionError: except AssertionError:
pass pass
else: else:
raise Exception('must raise') raise Exception('must raise')
def test_symlink_getproperties(): @pytest.mark.asyncio
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]) descr = OptionDescription('opt', '', [boolopt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await 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
def test_symlink_getcallback(): @pytest.mark.asyncio
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]) descr = OptionDescription('opt', '', [boolopt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await 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
def test_symlink_requires(config_type): @pytest.mark.asyncio
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'),
@ -130,76 +143,81 @@ def test_symlink_requires(config_type):
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]) descr = OptionDescription('opt', '', [boolopt, stropt, linkopt])
cfg = Config(descr) cfg = await Config(descr)
cfg.property.read_write() await cfg.property.read_write()
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('b').value.get() is True assert await cfg.option('b').value.get() is True
assert cfg.option('s').value.get() is None assert await cfg.option('s').value.get() is None
assert cfg.option('c').value.get() is None assert await cfg.option('c').value.get() is None
cfg.option('b').value.set(False) await cfg.option('b').value.set(False)
# #
props = [] props = []
try: try:
cfg.option('s').value.get() await 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:
cfg.option('c').value.get() await 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'}
def test_symlink_multi(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('s1.b').value.get() == [False] assert await cfg.option('s1.b').value.get() == [False]
assert cfg.option('c').value.get() == [False] assert await cfg.option('c').value.get() == [False]
cfg.option('s1.b').value.set([True]) await cfg.option('s1.b').value.set([True])
assert cfg.option('s1.b').value.get() == [True] assert await cfg.option('s1.b').value.get() == [True]
assert cfg.option('c').value.get() == [True] assert await cfg.option('c').value.get() == [True]
cfg.option('s1.b').value.set([False]) await cfg.option('s1.b').value.set([False])
assert cfg.option('s1.b').value.get() == [False] assert await cfg.option('s1.b').value.get() == [False]
assert cfg.option('c').value.get() == [False] assert await cfg.option('c').value.get() == [False]
cfg.option('s1.b').value.set([False, True]) await cfg.option('s1.b').value.set([False, True])
assert cfg.option('s1.b').value.get() == [False, True] assert await cfg.option('s1.b').value.get() == [False, True]
assert cfg.option('c').value.get() == [False, True] assert await 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
def test_symlink_assign(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
raises(ConfigError, "cfg.option('c').value.set(True)") with pytest.raises(ConfigError):
await cfg.option('c').value.set(True)
def test_symlink_owner(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.option('s1.b').owner.isdefault() assert await cfg.option('s1.b').owner.isdefault()
assert cfg.option('c').owner.isdefault() assert await cfg.option('c').owner.isdefault()
cfg.option('s1.b').value.set(True) await cfg.option('s1.b').value.set(True)
assert not cfg.option('s1.b').owner.isdefault() assert not await cfg.option('s1.b').owner.isdefault()
assert not cfg.option('c').owner.isdefault() assert not await cfg.option('c').owner.isdefault()
def test_symlink_get_information(): @pytest.mark.asyncio
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')
@ -210,97 +228,106 @@ def test_symlink_get_information():
assert linkopt.impl_get_information('test') == 'test2' assert linkopt.impl_get_information('test') == 'test2'
def test_symlink_leader(): @pytest.mark.asyncio
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)
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])") with pytest.raises(ValueError):
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
def test_symlink_followers(): @pytest.mark.asyncio
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)
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])") with pytest.raises(ValueError):
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
def test_symlink_with_leader(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('root', '', [interface1, leader])
cfg = Config(od) cfg = await Config(od)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []} assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []}
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'leader': ['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']}
def test_symlink_with_follower(config_type): @pytest.mark.asyncio
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]) od = OptionDescription('root', '', [interface1, follower])
cfg = Config(od) cfg = await Config(od)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []} assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []}
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]} assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]}
# #
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
assert cfg.option('follower', 0).value.get() == None assert await cfg.option('follower', 0).value.get() == None
assert cfg.option('follower', 1).value.get() == None assert await cfg.option('follower', 1).value.get() == None
# #
cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3') await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3')
assert cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, 'val3'], 'follower': [None, '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.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3' assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3'
assert cfg.option('follower', 0).value.get() == None assert await cfg.option('follower', 0).value.get() == None
assert cfg.option('follower', 1).value.get() == 'val3' assert await cfg.option('follower', 1).value.get() == 'val3'
#____________________________________________________________ #____________________________________________________________
def test_symlink_dependency(): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
assert cfg.option('s1.b').option.has_dependency() is False assert await cfg.option('s1.b').option.has_dependency() is False
assert cfg.option('c').option.has_dependency() is True assert await cfg.option('c').option.has_dependency() is True
assert cfg.option('s1.b').option.has_dependency(False) is True assert await cfg.option('s1.b').option.has_dependency(False) is True
assert cfg.option('c').option.has_dependency(False) is False assert await cfg.option('c').option.has_dependency(False) is False
def test_symlink_makedict(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
assert cfg.value.dict() == {'c': False, 's1.b': False} assert await cfg.value.dict() == {'c': False, 's1.b': False}
cfg.option('s1.b').value.set(True) await cfg.option('s1.b').value.set(True)
assert cfg.value.dict() == {'c': True, 's1.b': True} assert await cfg.value.dict() == {'c': True, 's1.b': True}
def test_symlink_list(config_type): @pytest.mark.asyncio
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", "", descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])]) [linkopt, OptionDescription("s1", "", [boolopt])])
cfg = Config(descr) cfg = await Config(descr)
cfg = get_config(cfg, config_type) cfg = await get_config(cfg, config_type)
list_opt = [] list_opt = []
for opt in cfg.option.list(): for opt in await cfg.option.list():
list_opt.append(opt.option.path()) list_opt.append(await opt.option.path())
assert list_opt == ['c'] assert list_opt == ['c']
# #
list_opt = [] list_opt = []
for opt in cfg.option.list(recursive=True): for opt in await cfg.option.list(recursive=True):
list_opt.append(opt.option.path()) list_opt.append(await opt.option.path())
assert list_opt == ['c', 's1.b'] assert list_opt == ['c', 's1.b']

View file

@ -18,7 +18,7 @@ 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
from .autolib import Calculation, Params, ParamOption, ParamSelfOption, ParamValue, \ from .autolib import Calculation, Params, ParamOption, ParamSelfOption, ParamValue, \
ParamIndex, ParamContext, ParamSuffix ParamIndex, ParamSuffix
from .option import * from .option import *
from .error import APIError from .error import APIError
from .api import Config, MetaConfig, GroupConfig, MixConfig from .api import Config, MetaConfig, GroupConfig, MixConfig
@ -34,7 +34,6 @@ allfuncs = ['Calculation',
'ParamSelfOption', 'ParamSelfOption',
'ParamValue', 'ParamValue',
'ParamIndex', 'ParamIndex',
'ParamContext',
'ParamSuffix', 'ParamSuffix',
'MetaConfig', 'MetaConfig',
'MixConfig', 'MixConfig',

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,6 @@ 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 .storage import get_default_values_storages, get_default_settings_storages
# ____________________________________________________________ # ____________________________________________________________
@ -99,10 +98,6 @@ class ParamValue(Param):
self.value = value self.value = value
class ParamContext(Param):
__slots__ = tuple()
class ParamIndex(Param): class ParamIndex(Param):
__slots__ = tuple() __slots__ = tuple()
@ -137,12 +132,12 @@ class Calculation:
if warnings_only is True: if warnings_only is True:
self.warnings_only = warnings_only self.warnings_only = warnings_only
def execute(self, async def execute(self,
option_bag: OptionBag, option_bag: OptionBag,
leadership_must_have_index: bool=False, leadership_must_have_index: bool=False,
orig_value: Any=undefined, orig_value: Any=undefined,
allow_raises=False) -> Any: allow_raises=False) -> Any:
return carry_out_calculation(option_bag.option, return await 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,
@ -151,13 +146,13 @@ class Calculation:
orig_value=orig_value, orig_value=orig_value,
allow_raises=allow_raises) allow_raises=allow_raises)
def help(self, async def help(self,
option_bag: OptionBag, option_bag: OptionBag,
leadership_must_have_index: bool=False) -> str: leadership_must_have_index: bool=False) -> str:
if not self.help_function: if not self.help_function:
return self.execute(option_bag, return self.execute(option_bag,
leadership_must_have_index=leadership_must_have_index) leadership_must_have_index=leadership_must_have_index)
return carry_out_calculation(option_bag.option, return await 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,
@ -180,7 +175,7 @@ class Break(Exception):
pass pass
def manager_callback(callbk: Union[ParamOption, ParamValue], async def manager_callback(callbk: Union[ParamOption, ParamValue],
option, option,
index: Optional[int], index: Optional[int],
orig_value, orig_value,
@ -199,7 +194,7 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
return index return index
return None return None
def calc_self(callbk, option, index, value, config_bag): async def calc_self(callbk, 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(callbk, index, is_follower)
@ -207,13 +202,13 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
if config_bag is undefined: if config_bag is undefined:
return undefined return undefined
path = option.impl_getpath() path = option.impl_getpath()
option_bag = get_option_bag(config_bag, option, path, apply_index) option_bag = await get_option_bag(config_bag, option, path, apply_index)
option_bag.config_bag.unrestraint() option_bag.config_bag.unrestraint()
option_bag.config_bag.remove_validation() option_bag.config_bag.remove_validation()
# if we are in properties calculation, cannot calculated properties # if we are in properties calculation, cannot calculated properties
option_bag.properties = config_bag.context.cfgimpl_get_settings().getproperties(option_bag, option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag,
apply_requires=False) apply_requires=False)
new_value = get_value(callbk, option_bag, path) new_value = await get_value(callbk, option_bag, path)
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
@ -221,10 +216,10 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
value = value[apply_index] value = value[apply_index]
return value return value
def get_value(callbk, option_bag, path): async def get_value(callbk, option_bag, path):
try: try:
# get value # get value
value = config_bag.context.getattr(path, value = await config_bag.context.getattr(path,
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
@ -236,7 +231,10 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
raise ValueError(_('the option "{0}" is used in a calculation but is invalid ({1})').format(option_bag.option.impl_get_display_name(), err)) raise ValueError(_('the option "{0}" is used in a calculation but is invalid ({1})').format(option_bag.option.impl_get_display_name(), err))
return value return value
def get_option_bag(config_bag, opt, path, index_): async def get_option_bag(config_bag,
opt,
path,
index_):
# 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()
config_bag.properties = config_bag.true_properties - {'warnings'} config_bag.properties = config_bag.true_properties - {'warnings'}
@ -247,6 +245,7 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
path, path,
index_, index_,
config_bag) config_bag)
option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag)
return option_bag return option_bag
if isinstance(callbk, ParamValue): if isinstance(callbk, ParamValue):
@ -260,16 +259,10 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
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, ParamContext):
if config_bag is undefined:
return undefined
# Not an option, set full context
return config_bag.context.duplicate(force_values=get_default_values_storages(),
force_settings=get_default_settings_storages())
if isinstance(callbk, ParamSelfOption): if isinstance(callbk, ParamSelfOption):
if leadership_must_have_index and option.impl_get_leadership() and index is None: if leadership_must_have_index and option.impl_get_leadership() and index is None:
raise Break() raise Break()
value = calc_self(callbk, option, index, orig_value, config_bag) value = await calc_self(callbk, option, index, orig_value, config_bag)
if not callbk.todict: if not callbk.todict:
return value return value
return {'name': option.impl_get_display_name(), return {'name': option.impl_get_display_name(),
@ -299,8 +292,8 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
index_ = None index_ = None
with_index = False with_index = False
path = callbk_option.impl_getpath() path = callbk_option.impl_getpath()
option_bag = get_option_bag(config_bag, callbk_option, path, index_) option_bag = await get_option_bag(config_bag, callbk_option, path, index_)
value = get_value(callbk, option_bag, path) value = await get_value(callbk, option_bag, path)
if with_index: if with_index:
value = value[index] value = value[index]
if not callbk.todict: if not callbk.todict:
@ -309,7 +302,7 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
'value': value} 'value': value}
def carry_out_calculation(option, async def carry_out_calculation(option,
callback: Callable, callback: Callable,
callback_params: Optional[Params], callback_params: Optional[Params],
index: Optional[int], index: Optional[int],
@ -342,7 +335,7 @@ def carry_out_calculation(option,
if callback_params: if callback_params:
for key, callbk in chain(fake_items(callback_params.args), callback_params.kwargs.items()): for key, callbk in chain(fake_items(callback_params.args), callback_params.kwargs.items()):
try: try:
value = manager_callback(callbk, value = await manager_callback(callbk,
option, option,
index, index,
orig_value, orig_value,

File diff suppressed because it is too large Load diff

View file

@ -84,16 +84,12 @@ class PropertiesOptionError(AttributeError):
return self.msg return self.msg
if self._settings is None: if self._settings is None:
return 'error' return 'error'
properties = list(self._settings.calc_raises_properties(self._option_bag, #for property_ in self._settings.get_calculated_properties(self._option_bag):
apply_requires=False)) # prop = property_.help(self._option_bag)
for property_ in self._settings.get_calculated_properties(self._option_bag): # if prop is not None:
prop = property_.help(self._option_bag) # properties.append(prop)
if prop is not None:
properties.append(prop)
if not properties: properties = list(self.proptype)
# if proptype == ['mandatory']
properties = self.proptype
only_one = len(properties) == 1 only_one = len(properties) == 1
properties_msg = display_list(properties, add_quote=True) properties_msg = display_list(properties, add_quote=True)
if only_one: if only_one:

View file

@ -29,7 +29,7 @@ from ..i18n import _
from ..setting import undefined, Settings from ..setting import undefined, Settings
from ..value import Values from ..value import Values
from ..error import ConfigError, display_list from ..error import ConfigError, display_list
from ..autolib import Calculation, Params, ParamContext, ParamOption, ParamIndex from ..autolib import Calculation, Params, ParamOption, ParamIndex
STATIC_TUPLE = frozenset() STATIC_TUPLE = frozenset()
@ -55,7 +55,6 @@ class Base:
'_properties', '_properties',
'_has_dependency', '_has_dependency',
'_dependencies', '_dependencies',
'_has_calc_context',
'__weakref__' '__weakref__'
) )

View file

@ -50,15 +50,15 @@ class ChoiceOption(Option):
raise TypeError(_('values must be a tuple or a calculation for {0}' raise TypeError(_('values must be a tuple or a calculation for {0}'
).format(name)) ).format(name))
self._choice_values = values self._choice_values = values
super(ChoiceOption, self).__init__(name, super().__init__(name,
doc, doc,
*args, *args,
**kwargs) **kwargs)
def impl_get_values(self, async def impl_get_values(self,
option_bag): option_bag):
if isinstance(self._choice_values, Calculation): if isinstance(self._choice_values, Calculation):
values = self._choice_values.execute(option_bag) values = await 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(_('calculated values for {0} is not a list' raise ConfigError(_('calculated values for {0} is not a list'
'').format(self.impl_getname())) '').format(self.impl_getname()))
@ -70,10 +70,23 @@ class ChoiceOption(Option):
value: Any) -> None: value: Any) -> None:
pass pass
def validate_with_option(self, def sync_validate_with_option(self,
value: Any, value: Any,
option_bag: OptionBag) -> None: option_bag: OptionBag) -> None:
values = self.impl_get_values(option_bag) if isinstance(self._choice_values, Calculation):
return
values = self._choice_values
if values is not undefined and value not in values:
if len(values) == 1:
raise ValueError(_('only "{0}" is allowed'
'').format(values[0]))
raise ValueError(_('only {0} are allowed'
'').format(display_list(values, add_quote=True)))
async def validate_with_option(self,
value: Any,
option_bag: OptionBag) -> None:
values = await self.impl_get_values(option_bag)
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

@ -83,6 +83,10 @@ class DomainnameOption(StrOption):
if allow_ip: if allow_ip:
msg = _('could be a IP, otherwise {}').format(msg) msg = _('could be a IP, otherwise {}').format(msg)
msg_warning = _('could be a IP, otherwise {}').format(msg_warning) msg_warning = _('could be a IP, otherwise {}').format(msg_warning)
if not allow_cidr_network:
regexp = r'(?:{0}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){{3}}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))'.format(regexp)
else:
regexp = r'(?:{0}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){{3}}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/[0-9][0-9]))'.format(regexp)
regexp = r'^{0}$'.format(regexp) regexp = r'^{0}$'.format(regexp)
extra['_domain_re'] = re.compile(regexp) extra['_domain_re'] = re.compile(regexp)
extra['_domain_re_message'] = msg extra['_domain_re_message'] = msg

View file

@ -27,7 +27,7 @@ from .optiondescription import OptionDescription
from .baseoption import BaseOption from .baseoption import BaseOption
from ..setting import OptionBag, ConfigBag, groups, undefined from ..setting import OptionBag, ConfigBag, groups, undefined
from ..error import ConfigError from ..error import ConfigError
from ..autolib import carry_out_calculation, Calculation from ..autolib import Calculation
NAME_REGEXP = re.compile(r'^[a-zA-Z\d\-_]*$') NAME_REGEXP = re.compile(r'^[a-zA-Z\d\-_]*$')
@ -53,7 +53,7 @@ class DynOptionDescription(OptionDescription):
if __debug__ and child.impl_get_group_type() != groups.leadership: if __debug__ and child.impl_get_group_type() != groups.leadership:
raise ConfigError(_('cannot set optiondescription in a ' raise ConfigError(_('cannot set optiondescription in a '
'dynoptiondescription')) 'dynoptiondescription'))
for chld in child.get_children(config_bag=undefined): for chld in child._children[1]:
chld._setsubdyn(self) chld._setsubdyn(self)
if __debug__ and child.impl_is_symlinkoption(): if __debug__ and child.impl_is_symlinkoption():
raise ConfigError(_('cannot set symlinkoption in a ' raise ConfigError(_('cannot set symlinkoption in a '
@ -67,15 +67,14 @@ class DynOptionDescription(OptionDescription):
suffix): suffix):
return suffix return suffix
def get_suffixes(self, async def get_suffixes(self,
config_bag: ConfigBag) -> List[str]: config_bag: ConfigBag) -> List[str]:
option_bag = OptionBag() option_bag = OptionBag()
option_bag.set_option(self, option_bag.set_option(self,
self.impl_getpath(), self.impl_getpath(),
None, None,
config_bag) config_bag)
values = self._suffixes.execute(option_bag) values = await self._suffixes.execute(option_bag)
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 option "{}", is not a list ({})'

View file

@ -111,7 +111,7 @@ class Leadership(OptionDescription):
opt = opt.opt opt = opt.opt
return opt in self._children[1] return opt in self._children[1]
def reset(self, async def reset(self,
values: Values, values: Values,
option_bag: OptionBag, option_bag: OptionBag,
_commit: bool=True) -> None: _commit: bool=True) -> None:
@ -124,10 +124,11 @@ class Leadership(OptionDescription):
follower_path, follower_path,
None, None,
config_bag) config_bag)
values.reset(soption_bag, soption_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(soption_bag)
await values.reset(soption_bag,
_commit=_commit) _commit=_commit)
def follower_force_store_value(self, async def follower_force_store_value(self,
values, values,
value, value,
option_bag, option_bag,
@ -136,25 +137,26 @@ class Leadership(OptionDescription):
settings = option_bag.config_bag.context.cfgimpl_get_settings() settings = option_bag.config_bag.context.cfgimpl_get_settings()
if value: if value:
rgevalue = range(len(value)) rgevalue = range(len(value))
for follower in self.get_children(option_bag.config_bag): for follower in await self.get_children(option_bag.config_bag):
foption_bag = OptionBag() foption_bag = OptionBag()
foption_bag.set_option(follower, foption_bag.set_option(follower,
follower.impl_getpath(), follower.impl_getpath(),
None, None,
option_bag.config_bag) option_bag.config_bag)
if 'force_store_value' in settings.getproperties(foption_bag): if 'force_store_value' in await settings.getproperties(foption_bag):
for index in rgevalue: for index in rgevalue:
foption_bag = OptionBag() foption_bag = OptionBag()
foption_bag.set_option(follower, foption_bag.set_option(follower,
follower.impl_getpath(), follower.impl_getpath(),
index, index,
option_bag.config_bag) option_bag.config_bag)
values._setvalue(foption_bag, foption_bag.properties = await settings.getproperties(foption_bag)
values.getvalue(foption_bag), await values._setvalue(foption_bag,
await values.getvalue(foption_bag),
owner, owner,
commit=False) commit=False)
def pop(self, async def pop(self,
values: Values, values: Values,
index: int, index: int,
option_bag: OptionBag, option_bag: OptionBag,
@ -166,7 +168,7 @@ class Leadership(OptionDescription):
config_bag.remove_validation() config_bag.remove_validation()
for follower in followers: for follower in followers:
follower_path = follower.impl_getpath() follower_path = follower.impl_getpath()
followerlen = values._p_.get_max_length(follower_path) followerlen = await values._p_.get_max_length(follower_path)
soption_bag = OptionBag() soption_bag = OptionBag()
soption_bag.set_option(follower, soption_bag.set_option(follower,
follower_path, follower_path,
@ -174,15 +176,16 @@ class Leadership(OptionDescription):
config_bag) config_bag)
# do not check force_default_on_freeze or force_metaconfig_on_freeze # do not check force_default_on_freeze or force_metaconfig_on_freeze
soption_bag.properties = set() soption_bag.properties = set()
if not values.is_default_owner(soption_bag, is_default = await values.is_default_owner(soption_bag,
validate_meta=False) and followerlen > index: validate_meta=False)
values._p_.resetvalue_index(follower_path, if not is_default and followerlen > index:
await values._p_.resetvalue_index(follower_path,
index, index,
True) True)
if followerlen > index + 1: if followerlen > index + 1:
for idx in range(index + 1, followerlen): for idx in range(index + 1, followerlen):
if values._p_.hasvalue(follower_path, idx): if await values._p_.hasvalue(follower_path, idx):
values._p_.reduce_index(follower_path, await values._p_.reduce_index(follower_path,
idx) idx)
def reset_cache(self, def reset_cache(self,
@ -212,7 +215,8 @@ class Leadership(OptionDescription):
follower.reset_cache(spath, follower.reset_cache(spath,
config_bag, config_bag,
None) None)
resetted_opts.append(spath) # 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

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