first version of new api

This commit is contained in:
Emmanuel Garette 2017-10-22 09:48:08 +02:00
parent 8e91f94379
commit 22a4aa81dc
12 changed files with 1250 additions and 35 deletions

0
test/api/__init__.py Normal file
View File

14
test/api/autopath.py Normal file
View File

@ -0,0 +1,14 @@
"""automatically sets the PYTHONPATH before running the unit tests
This is supposed to be used in development mode (i.e. testing from a fresh
checkout)
"""
from os.path import dirname, abspath, join, normpath
import sys
def do_autopath():
HERE = dirname(abspath(__file__))
PATH = normpath(join(HERE, '..', '..', 'tiramisu'))
if PATH not in sys.path:
sys.path.insert(1, PATH)

820
test/api/test_owner.py Normal file
View File

@ -0,0 +1,820 @@
"""test API to get/set owner
"""
import pytest
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu import Config, StrOption, OptionDescription, MasterSlaves, DynOptionDescription, \
getapi
from tiramisu.error import PropertiesOptionError
ICON = u'\u2937'
OPTIONS_TYPE = {'str': {'type': str,
'option': StrOption}
}
PROPERTIES = ['hidden', 'disabled']
def return_list(val=None, suffix=None):
if val:
return val
else:
return ['val1', 'val2']
def display_info(func):
def wrapper(*args, **kwargs):
print(u'\n{} {}'.format(ICON, func.__name__))
return func(*args, **kwargs)
return wrapper
autocheck_registers = []
def autocheck(func):
autocheck_registers.append(func)
def wrapper(*args, **kwargs):
if kwargs.get('display', True):
print(u' {} {}'.format(ICON, func.__name__))
return func(*args, **kwargs)
return wrapper
@autocheck
def autocheck_owner_without_value(api, path, **kwargs):
"""check different value of owner when any value is set to this option
"""
try:
isslave = api.permissive.option.isslave(path)
except:
isslave = False
# check if owner is a string "default"
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert api.owner.get(path) == 'default'
else:
if not isslave:
raises(PropertiesOptionError, "api.owner.get(path)")
else:
raises(PropertiesOptionError, "api.owner.get(path, 0)")
if not kwargs.get('propertyerror', False):
if not isslave:
assert api.permissive.owner.get(path) == 'default'
else:
assert api.permissive.owner.get(path, 0) == 'default'
else:
if not isslave:
raises(PropertiesOptionError, "api.permissive.owner.get(path)")
else:
raises(PropertiesOptionError, "api.permissive.owner.get(path, 0)")
# check if default owner
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert api.owner.isdefault(path)
else:
raises(PropertiesOptionError, "api.owner.isdefault(path)")
if not kwargs.get('propertyerror', False):
assert api.permissive.owner.isdefault(path)
else:
raises(PropertiesOptionError, "api.permissive.owner.isdefault(path)")
@autocheck
def autocheck_value(api, path, **kwargs):
"""set and get values
"""
print('=============')
try:
print(api.permissive.owner.get(path))
except Exception as pouet:
try:
print(api.permissive.owner.get(path, 0))
except Exception as pouet:
print(pouet)
pass
# check if is a multi, a master or a slave
if not kwargs.get('propertyerror', False):
multi = api.permissive.option.ismulti(path)
ismaster = api.permissive.option.ismaster(path)
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.ismulti(path)")
multi = False
ismaster = False
isslave = False
# set default value (different if value is multi or not)
if not multi:
first_value = 'myvalue'
second_value = 'myvalue1'
else:
first_value = ['myvalue']
second_value = ['myvalue', 'myvalue1']
if multi and not isslave:
empty_value = []
else:
empty_value = None
# test default value (should be empty) without permissive
# cannot test for slave (we cannot get all values for a slave)
if not isslave:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert api.value.get(path) == empty_value
else:
raises(PropertiesOptionError, "api.value.get(path)")
# test default value (should be empty) with permissive
# cannot test for slave (we cannot get all values for a slave)
if not isslave:
if not kwargs.get('propertyerror', False):
assert api.permissive.value.get(path) == empty_value
else:
raises(PropertiesOptionError, "api.permissive.value.get(path)")
# set a value without permissive
# for master/slave should have an index and good length
# for master must append, not set
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if ismaster:
raises(IndexError, "api.value.set(path, 0, first_value[0])")
api.value.append(path, first_value[0])
elif isslave:
#FIXME
print(api.value.append(path, first_value[0]))
raises(PropertiesOptionError, "api.value.append(path, first_value[0])")
api.value.set(path, 0, first_value[0])
raise Exception('pouet')
else:
api.value.set(path, first_value)
else:
if ismaster:
raises(PropertiesOptionError, "api.value.append(path, first_value[0])")
elif isslave:
raises(PropertiesOptionError, "api.value.set(path, 0, first_value[0])")
else:
raises(PropertiesOptionError, "api.value.set(path, first_value)")
# get value after set value without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if isslave:
assert api.value.get(path, 0) == first_value[0]
else:
assert api.value.get(path) == first_value
elif kwargs.get('permissive', False):
if isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
assert api.permissive.value.get(path, 0) == empty_value
else:
raises(PropertiesOptionError, "api.value.get(path)")
assert api.permissive.value.get(path) == empty_value
else:
if isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
raises(PropertiesOptionError, "api.permissive.value.get(path, 0)")
else:
raises(PropertiesOptionError, "api.value.get(path)")
raises(PropertiesOptionError, "api.permissive.value.get(path)")
# set a value with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if ismaster:
raises(IndexError, "api.permissive.value.set(path, 1, second_value[1])")
api.permissive.value.append(path, second_value[1])
elif isslave:
#FIXME
raises(PropertiesOptionError, "api.permissive.value.append(path, second_value[1])")
api.value.set(path, 1, second_value[1])
raise Exception('ca entre ici')
else:
api.value.set(path, second_value)
elif kwargs.get('permissive', False):
if ismaster:
api.permissive.value.append(path, second_value[0])
api.permissive.value.append(path, second_value[1])
elif isslave:
api.permissive.value.set(path, 1, second_value[1])
else:
api.permissive.value.set(path, first_value)
else:
if ismaster:
raises(PropertiesOptionError, "api.permissive.value.append(path, first_value[0])")
elif isslave:
raises(PropertiesOptionError, "api.permissive.value.set(path, 0, first_value[0])")
else:
raises(PropertiesOptionError, "api.permissive.value.set(path, first_value)")
# get value after set value with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if isslave:
assert api.value.get(path, 0) == second_value[0]
assert api.value.get(path, 1) == second_value[1]
else:
assert api.value.get(path) == second_value
elif kwargs.get('permissive', False):
if ismaster:
raises(PropertiesOptionError, "api.value.get(path)")
assert api.permissive.value.get(path) == second_value
elif isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
raises(PropertiesOptionError, "api.value.get(path, 1)")
assert api.permissive.value.get(path, 1) == second_value[1]
else:
raises(PropertiesOptionError, "api.value.get(path)")
assert api.permissive.value.get(path) == first_value
else:
if isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
raises(PropertiesOptionError, "api.permissive.value.get(path, 0)")
else:
raises(PropertiesOptionError, "api.value.get(path)")
raises(PropertiesOptionError, "api.permissive.value.get(path)")
print('=============')
try:
print(api.permissive.owner.get(path))
except Exception as pouet:
try:
print(api.permissive.owner.get(path, 0))
except Exception as pouet:
print(pouet)
pass
@autocheck
def autocheck_reset_value(api, path, **kwargs):
# check if is a multi, a master or a slave
if not kwargs.get('propertyerror', False):
multi = api.permissive.option.ismulti(path)
ismaster = api.permissive.option.ismaster(path)
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.ismulti(path)")
multi = False
ismaster = False
isslave = False
# set default value (different if value is multi or not)
if not multi:
first_value = 'myvalue'
second_value = 'myvalue1'
else:
first_value = ['myvalue']
second_value = ['myvalue', 'myvalue1']
if multi and not isslave:
empty_value = []
else:
empty_value = None
# reset value without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
api.value.reset(path)
else:
api.value.reset(path, 0)
else:
if not isslave:
raises(PropertiesOptionError, "api.value.reset(path)")
else:
raises(PropertiesOptionError, "api.value.reset(path, 0)")
# get value after reset value without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if isslave:
assert api.value.get(path, 0) == empty_value
assert api.value.get(path, 1) == second_value[1]
else:
assert api.value.get(path) == empty_value
elif kwargs.get('permissive', False):
if isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
assert api.permissive.value.get(path, 0) == empty_value
assert api.permissive.value.get(path, 1) == second_value[1]
else:
raises(PropertiesOptionError, "api.value.get(path)")
assert api.permissive.value.get(path) == first_value
# reset value with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
api.permissive.value.reset(path)
else:
api.permissive.value.reset(path, 1)
elif kwargs.get('permissive', False):
if not isslave:
api.permissive.value.reset(path)
else:
api.permissive.value.reset(path, 1)
else:
if not isslave:
raises(PropertiesOptionError, "api.permissive.value.reset(path)")
else:
raises(PropertiesOptionError, "api.permissive.value.reset(path, 1)")
# get value after reset value with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if isslave:
assert api.value.get(path, 0) == empty_value
assert api.value.get(path, 1) == empty_value
else:
assert api.value.get(path) == empty_value
elif kwargs.get('permissive', False):
if isslave:
raises(PropertiesOptionError, "api.value.get(path, 0)")
raises(PropertiesOptionError, "api.value.get(path, 1)")
assert api.permissive.value.get(path, 0) == empty_value
assert api.permissive.value.get(path, 1) == empty_value
else:
raises(PropertiesOptionError, "api.value.get(path)")
assert api.permissive.value.get(path) == empty_value
@autocheck
def autocheck_value2(*args, **kwargs):
"""reset value
"""
autocheck_value(*args, **kwargs)
@autocheck
def autocheck_property(api, path, **kwargs):
"""get property from path
"""
# check if is a multi or a slave
if not kwargs.get('propertyerror', False):
multi = api.permissive.option.ismulti(path)
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.ismulti(path)")
raises(PropertiesOptionError, "api.permissive.option.isslave(path)")
multi = False
isslave = False
# define properties
properties = ['prop1', 'prop2']
if multi and not isslave:
default_props = ['empty']
properties.append('empty')
else:
default_props = []
extra_properties = kwargs.get('extra_properties')
if extra_properties:
properties.extend(extra_properties)
default_props.extend(extra_properties)
properties = tuple(properties)
# get properties without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert set(api.property.get(path)) == set(default_props)
else:
assert set(api.property.get(path, 0)) == set(default_props)
assert set(api.property.get(path, 1)) == set(default_props)
else:
raises(PropertiesOptionError, "api.property.get(path)")
# get properties with permissive
if not kwargs.get('propertyerror', False):
if not isslave:
assert set(api.permissive.property.get(path)) == set(default_props)
else:
assert set(api.permissive.property.get(path, 0)) == set(default_props)
assert set(api.permissive.property.get(path, 1)) == set(default_props)
else:
if not isslave:
raises(PropertiesOptionError, "api.permissive.property.get(path)")
else:
raises(PropertiesOptionError, "api.permissive.property.get(path, 0)")
# set properties without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
api.property.set(path, properties)
else:
raises(PropertiesOptionError, "api.property.set(path, properties)")
# check properties after set without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert set(api.property.get(path)) == set(properties)
assert set(api.permissive.property.get(path)) == set(properties)
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "api.property.get(path)")
if not isslave:
assert set(api.permissive.property.get(path)) == set(default_props)
else:
assert set(api.permissive.property.get(path, 0)) == set(default_props)
assert set(api.permissive.property.get(path, 1)) == set(default_props)
else:
if not isslave:
raises(PropertiesOptionError, "api.property.get(path)")
raises(PropertiesOptionError, "api.permissive.property.get(path)")
else:
raises(PropertiesOptionError, "api.property.get(path, 0)")
raises(PropertiesOptionError, "api.permissive.property.get(path, 0)")
# set properties with permissive
if not kwargs.get('propertyerror', False):
api.permissive.property.set(path, properties)
else:
raises(PropertiesOptionError, "api.permissive.property.set(path, properties)")
# check properties after set with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert set(api.property.get(path)) == set(properties)
assert set(api.permissive.property.get(path)) == set(properties)
else:
assert set(api.property.get(path, 0)) == set(properties)
assert set(api.permissive.property.get(path, 0)) == set(properties)
assert set(api.property.get(path, 1)) == set(properties)
assert set(api.permissive.property.get(path, 1)) == set(properties)
elif kwargs.get('permissive', False):
if not isslave:
raises(PropertiesOptionError, "api.property.get(path)")
assert set(api.permissive.property.get(path)) == set(properties)
else:
raises(PropertiesOptionError, "api.property.get(path, 0)")
assert set(api.permissive.property.get(path, 0)) == set(properties)
raises(PropertiesOptionError, "api.property.get(path, 1)")
assert set(api.permissive.property.get(path, 1)) == set(properties)
else:
if not isslave:
raises(PropertiesOptionError, "api.property.get(path)")
raises(PropertiesOptionError, "api.permissive.property.get(path)")
else:
raises(PropertiesOptionError, "api.property.get(path, 0)")
raises(PropertiesOptionError, "api.permissive.property.get(path, 0)")
@autocheck
def autocheck_reset_property(api, path, **kwargs):
"""check properties after set with permissive
"""
# check if is a multi or a slave
if not kwargs.get('propertyerror', False):
multi = api.permissive.option.ismulti(path)
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.ismulti(path)")
raises(PropertiesOptionError, "api.permissive.option.isslave(path)")
multi = False
isslave = False
# define properties
properties = ['prop1', 'prop2']
if multi and not isslave:
default_props = ['empty']
properties.append('empty')
else:
default_props = []
extra_properties = kwargs.get('extra_properties')
if extra_properties:
properties.extend(extra_properties)
default_props.extend(extra_properties)
properties = tuple(properties)
# check properties
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert set(api.property.get(path)) == set(properties)
assert set(api.permissive.property.get(path)) == set(properties)
elif kwargs.get('permissive', False):
if not isslave:
assert set(api.permissive.property.get(path)) == set(properties)
else:
assert set(api.permissive.property.get(path, 0)) == set(properties)
assert set(api.permissive.property.get(path, 1)) == set(properties)
# reset properties without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
api.property.reset(path)
else:
raises(PropertiesOptionError, "api.property.reset(path)")
# check properties
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert set(api.property.get(path)) == set(default_props)
assert set(api.permissive.property.get(path)) == set(default_props)
else:
assert set(api.property.get(path, 0)) == set(default_props)
assert set(api.permissive.property.get(path, 0)) == set(default_props)
assert set(api.property.get(path, 1)) == set(default_props)
assert set(api.permissive.property.get(path, 1)) == set(default_props)
elif kwargs.get('permissive', False):
if not isslave:
assert set(api.permissive.property.get(path)) == set(properties)
else:
assert set(api.permissive.property.get(path, 0)) == set(properties)
assert set(api.permissive.property.get(path, 1)) == set(properties)
# reset properties with permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
api.permissive.property.set(path, properties)
api.permissive.property.reset(path)
elif kwargs.get('permissive', False):
api.permissive.property.reset(path)
# check properties
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert set(api.property.get(path)) == set(default_props)
assert set(api.permissive.property.get(path)) == set(default_props)
else:
assert set(api.property.get(path, 0)) == set(default_props)
assert set(api.permissive.property.get(path, 0)) == set(default_props)
assert set(api.property.get(path, 1)) == set(default_props)
assert set(api.permissive.property.get(path, 1)) == set(default_props)
elif kwargs.get('permissive', False):
if not isslave:
assert set(api.permissive.property.get(path)) == set(default_props)
else:
assert set(api.permissive.property.get(path, 0)) == set(default_props)
assert set(api.permissive.property.get(path, 1)) == set(default_props)
@autocheck
def autocheck_property2(*args, **kwargs):
return autocheck_property(*args, display=False, **kwargs)
@autocheck
def autocheck_owner_with_value(api, path, **kwargs):
"""value is now changed, check owner in this case
"""
# check if is a isslave
if not kwargs.get('propertyerror', False):
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.isslave(path)")
isslave = False
# get owner without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert api.owner.get(path) == 'user'
else:
assert api.owner.get(path, 0) == 'user'
assert api.owner.get(path, 1) == 'user'
else:
if not isslave:
raises(PropertiesOptionError, "api.owner.get(path)")
else:
raises(PropertiesOptionError, "api.owner.get(path, 0)")
raises(PropertiesOptionError, "api.owner.get(path, 1)")
# get owner with permissive
if not kwargs.get('propertyerror', False):
if not isslave:
assert api.permissive.owner.get(path) == 'user'
else:
print('--------')
print(api.permissive.owner.get(path, 0))
print(api.permissive.value.get(path, 0))
assert api.permissive.owner.get(path, 0) == 'default'
assert api.permissive.owner.get(path, 1) == 'user'
else:
if not isslave:
raises(PropertiesOptionError, "api.permissive.owner.get(path)")
else:
raises(PropertiesOptionError, "api.permissive.owner.get(path, 0)")
# test if is default owner without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert api.owner.isdefault(path) is False
else:
raises(PropertiesOptionError, "api.owner.isdefault(path)")
# test if is default owner with permissive
if not kwargs.get('propertyerror', False):
assert api.permissive.owner.isdefault(path) is False
else:
raises(PropertiesOptionError, "api.permissive.owner.isdefault(path)")
@autocheck
def autocheck_set_owner(api, path, **kwargs):
# test set owner without permissive
if not kwargs.get('propertyerror', False):
isslave = api.permissive.option.isslave(path)
else:
raises(PropertiesOptionError, "api.permissive.option.isslave(path)")
isslave = False
# set owner without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
api.owner.set(path, 'new_user')
else:
api.owner.set(path, 1, 'new_user')
else:
if not isslave:
raises(PropertiesOptionError, "api.owner.set(path, 'new_user')")
else:
raises(PropertiesOptionError, "api.owner.set(path, 1, 'new_user')")
# check owner set without permissive
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isslave:
assert api.owner.get(path) == 'new_user'
assert api.permissive.owner.get(path) == 'new_user'
else:
assert api.owner.get(path, 1) == 'new_user'
assert api.permissive.owner.get(path, 1) == 'new_user'
elif not kwargs.get('propertyerror', False):
if not isslave:
assert api.permissive.owner.get(path) == 'user'
else:
assert api.permissive.owner.get(path, 1) == 'user'
# set owner with permissive
if not kwargs.get('propertyerror', False):
if not isslave:
api.permissive.owner.set(path, 'new_user1')
else:
api.permissive.owner.set(path, 1, 'new_user1')
else:
if not isslave:
raises(PropertiesOptionError, "api.permissive.owner.set(path, 'new_user1')")
else:
raises(PropertiesOptionError, "api.permissive.owner.set(path, 1, 'new_user1')")
# get owner set with permissive
if not kwargs.get('propertyerror', False):
if not isslave:
assert api.permissive.owner.get(path) == 'new_user1'
else:
assert api.permissive.owner.get(path, 0) == 'default'
assert api.permissive.owner.get(path, 1) == 'new_user1'
def check_all(api, path, multi, **kwargs):
text = u' {} launch tests for {}'.format(ICON, path)
if multi:
text += u' as a multi'
print(text)
for func in autocheck_registers:
print(u' {} {}'.format(ICON, func.__name__))
func(api, path, **kwargs)
def make_api(options, multi):
def make_option(path):
option_infos = path.split('_')
option_type = 'str'
option_properties = []
for option_info in option_infos[1:]:
if option_info in OPTIONS_TYPE:
option_type = option_info
elif option_info in PROPERTIES:
option_properties.append(option_info)
else:
raise Exception('unknown {} in {}'.format(option_info, path))
args = [option_infos[0], "{}'s option".format(option_infos[0])]
kwargs = {}
if option_properties != []:
kwargs['properties'] = tuple(option_properties)
if multi:
kwargs['multi'] = True
tiramisu_option = OPTIONS_TYPE[option_type]['option']
return tiramisu_option(*args, **kwargs)
def make_optiondescriptions(path, collected):
infos = path.split('_')
name = infos[0]
properties = []
kwargs = {}
optiondescription = OptionDescription
for info in infos[1:]:
if info in PROPERTIES:
properties.append(info)
elif info == 'master':
if not multi:
return
optiondescription = MasterSlaves
elif info == 'dyn':
optiondescription = DynOptionDescription
kwargs['callback'] = return_list
else:
raise Exception('unknown {} in {}'.format(info, path))
options = []
if 'options' in collected:
options.extend(collected['options'])
for key, values in collected.items():
if key == 'options':
continue
option = make_optiondescriptions(key, values)
if option is None:
return
options.append(option)
if properties != []:
kwargs['properties'] = tuple(properties)
return optiondescription(name, "{}'s optiondescription".format(name), options, **kwargs)
collect_options = {}
for option in options:
if option is None:
continue
local_collect_options = collect_options
for optiondescription in option.split('.')[:-1]:
local_collect_options.setdefault(optiondescription, {})
local_collect_options = local_collect_options[optiondescription]
path = '.'.join(option.split('.')[:-1])
option_name = option.split('.')[-1]
local_collect_options.setdefault("options", []).append(make_option(option_name))
rootod = make_optiondescriptions('root', collect_options)
if rootod is None:
return
cfg = Config(rootod)
return getapi(cfg)
DICT_PATHS = [
#test a config without optiondescription
{'first': 'first',
'second': 'second_disabled',
'third': 'third_hidden'},
#test a config with an optiondescription
{'subod.first': 'subod.first',
'subod.second': 'subod.second_disabled',
'subod.third': 'subod.third_hidden'},
#test a config with two optiondescription
{'subod.subsubod.first': 'subod.subsubod.first',
'subod.subsubod.second': 'subod.subsubod.second_disabled',
'subod.subsubod.third': 'subod.subsubod.third_hidden'},
#test a config with mix of different optiondescription
{'first': 'first',
'subod.second': 'subod.second_disabled',
'subod.subsubod.third': 'subod.subsubod.third_hidden'},
#test a config with masterslaves
{'first.first': 'first_master.first',
'first.second': 'first_master.second_disabled',
'first.third': 'first_master.third_hidden'},
##test a config with dynoption
{'subodval1.firstval1': 'subod_dyn.first',
'subodval1.secondval1': 'subod_dyn.second_disabled',
'subodval1.thirdval1': 'subod_dyn.third_hidden',
'subodval2.firstval2': None,
'subodval2.secondval2': None,
'subodval2.thirdval2': None},
#test a config with dynoption subdir
{'subod.subodval1.firstval1': 'subod.subod_dyn.first',
'subod.subodval1.secondval1': 'subod.subod_dyn.second_disabled',
'subod.subodval1.thirdval1': 'subod.subod_dyn.third_hidden',
'subod.subodval2.firstval2': None,
'subod.subodval2.secondval2': None,
'subod.subodval2.thirdval2': None}
]
@pytest.fixture(scope="function", params=DICT_PATHS)
def paths(request):
print(u'\n{} {}: {}'.format(ICON, request.function.__name__, request.param))
return request.param
def test_options(paths):
lpaths = list(paths.keys())
for multi in (False, True):
api = make_api(paths.values(), multi)
if api is None:
continue
check_all(api, lpaths[0], multi)
check_all(api, lpaths[1], multi, propertyerror=True, extra_properties=['disabled'])
check_all(api, lpaths[2], multi, permissive=True, extra_properties=['hidden'])
if len(lpaths) == 6:
check_all(api, lpaths[3], multi)
check_all(api, lpaths[4], multi, propertyerror=True, extra_properties=['disabled'])
check_all(api, lpaths[5], multi, permissive=True, extra_properties=['hidden'])
##
#print('')
#print(api.help)
@display_info
def test_tree_od_permissive():
"""permissive when optiondescription is hidden
"""
tpaths = [
{'subod.subsubod.first': 'subod.subsubod_hidden.first',
'subod.subsubod.second': 'subod.subsubod_hidden.second',
'subod.subsubod.third': 'subod.subsubod_hidden.third_hidden'},
{'subod.subodval1.firstval1': 'subod.subod_dyn_hidden.first',
'subod.subodval1.secondval1': 'subod.subod_dyn_hidden.second',
'subod.subodval1.thirdval1': 'subod.subod_dyn_hidden.third_hidden',
'subod.subodval2.firstval2': None,
'subod.subodval2.secondval2': None,
'subod.subodval2.thirdval2': None
}
]
for paths in tpaths:
lpaths = list(paths.keys())
for multi in (False, True):
api = make_api(paths.values(), multi)
if api is None:
continue
check_all(api, lpaths[0], multi, permissive=True)
check_all(api, lpaths[1], multi, permissive=True)
check_all(api, lpaths[2], multi, permissive=True, extra_properties=['hidden'])
if len(lpaths) == 6:
check_all(api, lpaths[3], multi, permissive=True)
check_all(api, lpaths[4], multi, permissive=True)
check_all(api, lpaths[5], multi, permissive=True, extra_properties=['hidden'])

View File

@ -83,7 +83,7 @@ def test_force_default_on_freeze():
setting[dummy1].remove('frozen')
del(config.dummy1)
setting[dummy1].append('frozen')
raises(ConfigError, "config.cfgimpl_get_values().setowner(dummy1, owners.frozen)")
raises(PropertiesOptionError, "config.cfgimpl_get_values().setowner(dummy1, owners.frozen)")
def test_force_default_on_freeze_multi():
@ -110,7 +110,7 @@ def test_force_default_on_freeze_multi():
setting[dummy1].remove('frozen')
del(config.dummy1)
setting[dummy1].append('frozen')
raises(ConfigError, "config.cfgimpl_get_values().setowner(dummy1, owners.frozenmulti)")
raises(PropertiesOptionError, "config.cfgimpl_get_values().setowner(dummy1, owners.frozenmulti)")
def test_overrides_changes_option_value():

View File

@ -12,3 +12,15 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .config import Config
from .option import *
from .error import APIError
from .api import getapi
from .option import __all__ as all_options
allfuncs = ['Config', 'getapi', 'APIError']
allfuncs.extend(all_options)
del(all_options)
__all__ = tuple(allfuncs)
del(allfuncs)

342
tiramisu/api.py Normal file
View File

@ -0,0 +1,342 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
from inspect import ismethod, getdoc
from .error import APIError
from .i18n import _
from .setting import owners, undefined
def getter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
get = self._slave_get
else:
get = self._simple_get
return get(path, *args, **kwargs)
return wrapper
def setter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
return self._slave_set(path, *args, **kwargs)
elif opt.impl_is_master_slaves('master'):
return self._master_set(path, *args, **kwargs)
else:
return self._simple_set(path, *args, **kwargs)
return wrapper
def resetter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
reset = self._slave_reset
else:
reset = self._simple_reset
return reset(path, *args, **kwargs)
return wrapper
class CommonTiramisu(object):
icon = '\u2937'
tmpl_help = u' {} {}: {}'
def _get_obj_by_path(self, path, index=None):
return self.config.unwrap_from_path(path,
force_permissive=self.force_permissive,
index=index)
def __getattr__(self, name):
if name == 'help':
return self._help()
else:
if not hasattr(CommonTiramisu, name):
raise APIError(_('unknown method {}').format(name))
else:
super(CommonTiramisu).__getattribute__(name)
def _help(self):
txt = []
for func_name in dir(self):
if not func_name.startswith('_'):
func = getattr(self, func_name)
if ismethod(func):
txt.append(self.tmpl_help.format(self.icon, func_name, getdoc(func)))
return '\n'.join(txt)
class TiramisuAPIOption(CommonTiramisu):
"""get information from an option"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.values = self.config.cfgimpl_get_values()
def ismulti(self, path):
"""test if option could have multi value"""
opt = self._get_obj_by_path(path)
return opt.impl_is_multi()
def ismasterslaves(self, path):
"""test if option is a master or a slave"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves()
def ismaster(self, path):
"""test if option is a master"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves('master')
def isslave(self, path):
"""test if option is a slave"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves('slave')
class TiramisuAPIOwner(CommonTiramisu):
"""manager option's owner"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.values = self.config.cfgimpl_get_values()
@getter
def get(self):
"""get owner for a specified option"""
pass
def _simple_get(self, path):
##FIXME should not be here, just for check property
#self.config.getattr(path,
# force_permissive=self.force_permissive)
# FIXME doublons aussi
opt = self._get_obj_by_path(path)
return self.values.getowner(opt,
force_permissive=self.force_permissive)
def _slave_get(self, path, index):
##FIXME should not be here, just for check property
#self.config.getattr(path,
# index=index,
# force_permissive=self.force_permissive)
# FIXME doublons aussi
opt = self._get_obj_by_path(path,
index=index)
return self.values.getowner(opt,
index=index,
force_permissive=self.force_permissive)
def isdefault(self, path):
"""is option has defaut value"""
#FIXME isdefault for slave should have index!
opt = self._get_obj_by_path(path)
#FIXME should not be here, just for check property
self.config.getattr(path,
force_permissive=self.force_permissive)
return self.values.is_default_owner(opt,
force_permissive=self.force_permissive)
@setter
def set(self):
"""get owner for a specified option"""
pass
def _simple_set(self, path, owner):
#FIXME doublons, opt est deja dans le setter
opt = self._get_obj_by_path(path)
try:
obj_owner = getattr(owners, owner)
except AttributeError:
owners.addowner(owner)
obj_owner = getattr(owners, owner)
self.values.setowner(opt,
obj_owner,
force_permissive=self.force_permissive)
def _master_set(self, path, owner):
return self._simple_set(path, owner)
def _slave_set(self, path, index, owner):
#FIXME doublons, opt est deja dans le setter
opt = self._get_obj_by_path(path, index)
try:
obj_owner = getattr(owners, owner)
except AttributeError:
owners.addowner(owner)
obj_owner = getattr(owners, owner)
self.values.setowner(opt,
obj_owner,
index,
force_permissive=self.force_permissive)
class TiramisuAPIProperty(CommonTiramisu):
"""manager option's property"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.settings = config.cfgimpl_get_settings()
@getter
def get(self, path):
"""get property for a specified option"""
def _simple_get(self, path):
opt = self._get_obj_by_path(path)
return self.settings.getproperties(opt, path, obj=False)
def _slave_get(self, path, index):
opt = self._get_obj_by_path(path)
return self.settings.getproperties(opt, path, index=index, obj=False)
def set(self, path, properties):
"""set properties for a specified option"""
opt = self._get_obj_by_path(path)
self.settings.setproperties(set(properties),
opt,
path)
def reset(self, path):
"""reset all personalised properties
"""
self._get_obj_by_path(path)
self.settings.reset(_path=path)
class TiramisuAPIValue(CommonTiramisu):
"""manager option's value"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
def append(self, path, value=undefined):
opt = self._get_obj_by_path(path)
if not opt.impl_is_master_slaves('master'):
raise APIError('append is only allowed for a master')
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
multi.append(value, force_permissive=self.force_permissive)
@getter
def get(self):
"""get value for a specified option"""
pass
def _simple_get(self, path):
return self.config.getattr(path,
force_permissive=self.force_permissive)
def _slave_get(self, path, index):
return self.config.getattr(path,
index=index,
force_permissive=self.force_permissive)
@setter
def set(self):
"""set a value for a specified option"""
pass
def _simple_set(self, path, value):
self.config.setattr(path,
value,
force_permissive=self.force_permissive)
def _master_set(self, path, index, value):
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
multi[index] = value
def _slave_set(self, path, index, value):
self.config.setattr(path,
value,
index=index,
force_permissive=self.force_permissive)
@resetter
def reset(self, path):
"""reset value for a value"""
pass
def _simple_reset(self, path):
opt = self._get_obj_by_path(path)
self.config.cfgimpl_get_values().reset(opt,
path=path,
force_permissive=self.force_permissive)
def _slave_reset(self, path, index):
#self._get_obj_by_path(path)
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
del(multi[index])
class TiramisuAPI(object):
icon = '\u2937'
tmpl_help = ' {} {}: {}'
def __init__(self, config, force_permissive=False):
self.config = config
self.force_permissive = force_permissive
#FIXME ?
self.config.read_write()
self.config.cfgimpl_get_settings().setpermissive(('hidden',))
#/FIXME ?
self.registers = {}
self.prefix = self.__class__.__name__
for module_name in globals().keys():
if module_name != self.prefix and module_name.startswith(self.prefix):
module = globals()[module_name]
func_name = module_name[11:].lower()
self.registers[func_name] = module
def __getattr__(self, subfunc):
if subfunc in self.registers:
return self.registers[subfunc](self.config,
self.force_permissive)
elif subfunc == 'permissive':
return TiramisuAPI(self.config, force_permissive=True)
elif subfunc == 'help':
return self._help()
else:
raise APIError(_('please specify a valid sub function'))
def _help(self):
txt = ['[permissive]']
for module_name, module in self.registers.items():
module_doc = getdoc(module)
txt.append(self.tmpl_help.format(self.icon, module_name, module_doc))
txt.append(module(None, None).help)
return '\n'.join(txt)
def getapi(config):
"""instanciate TiramisuAPI
:param config: Config object
:type descr: an instance of ``config.Config``
"""
return TiramisuAPI(config)

View File

@ -382,7 +382,7 @@ class SubConfig(object):
def getattr(self, name, force_permissive=False, validate=True,
_setting_properties=undefined, _self_properties=undefined, index=None,
returns_raise=False):
returns_raise=False, returns_option=False):
"""
attribute notation mechanism for accessing the value of an option
:param name: attribute name
@ -457,7 +457,10 @@ class SubConfig(object):
index=index)
if not returns_raise and isinstance(cfg, Exception):
raise cfg
return cfg
if returns_option is True:
return option
else:
return cfg
def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
check_properties=True, force_permissive=False):
@ -724,7 +727,7 @@ class _CommonConfig(SubConfig):
return self.cfgimpl_get_values().getowner(opt, index=index,
force_permissive=force_permissive)
def unwrap_from_path(self, path, force_permissive=False):
def unwrap_from_path(self, path, force_permissive=False, index=None):
"""convenience method to extract and Option() object from the Config()
and it is **fast**: finds the option directly in the appropriate
namespace
@ -733,10 +736,9 @@ class _CommonConfig(SubConfig):
"""
context = self._cfgimpl_get_context()
if '.' in path:
homeconfig, path = self.cfgimpl_get_home_by_path(
path, force_permissive=force_permissive)
return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
return self.cfgimpl_get_description().__getattr__(path, context=context)
self, path = self.cfgimpl_get_home_by_path(path,
force_permissive=force_permissive)
return self.getattr(path, force_permissive=force_permissive, index=index, returns_option=True)
def cfgimpl_get_path(self, dyn=True):
return None

View File

@ -161,3 +161,7 @@ class ValueWarning(UserWarning): # pragma: optional cover
def __init__(self, msg, opt):
self.opt = opt
super(ValueWarning, self).__init__(msg)
class APIError(Exception):
pass

View File

@ -58,7 +58,7 @@ class Option(OnlyOption):
'_choice_values_params',
)
_empty = ''
def __init__(self, name, doc, default=None, default_multi=None,
def __init__(self, name, doc, default=undefined, default_multi=None,
requires=None, multi=False, unique=undefined, callback=None,
callback_params=None, validator=None, validator_params=None,
properties=None, warnings_only=False, extra=None,
@ -68,6 +68,11 @@ class Option(OnlyOption):
if not multi and default_multi is not None:
raise ValueError(_("default_multi is set whereas multi is False"
" in option: {0}").format(name))
if default is undefined:
if multi is False:
default = None
else:
default = []
if multi is True:
is_multi = True
_multi = 0

View File

@ -644,10 +644,10 @@ class MasterSlaves(OptionDescription):
c_opt = opt
return c_opt in self._children[1]
def reset(self, opt, values, setting_properties, _commit=True):
def reset(self, opt, values, setting_properties, _commit=True, force_permissive=False):
for slave in self.getslaves(opt):
values.reset(slave, validate=False, _setting_properties=setting_properties,
_commit=_commit)
_commit=_commit, force_permissive=force_permissive)
def pop(self, opt, values, index):
for slave in self.getslaves(opt):

View File

@ -270,7 +270,7 @@ class Property(object):
raise ConfigError(_('cannot add those properties: {0}').format(propname))
self._properties.add(propname)
if save:
self._setting._setproperties(self._properties, self._opt, self._path, force=True)
self._setting.setproperties(self._properties, self._opt, self._path, force=True)
def remove(self, propname):
"""Removes a property named propname
@ -280,7 +280,7 @@ class Property(object):
"""
if propname in self._properties:
self._properties.remove(propname)
self._setting._setproperties(self._properties, self._opt, self._path)
self._setting.setproperties(self._properties, self._opt, self._path)
def extend(self, propnames):
"""Extends properties to the existing properties
@ -290,7 +290,7 @@ class Property(object):
"""
for propname in propnames:
self._append(propname, save=False)
self._setting._setproperties(self._properties, self._opt, self._path)
self._setting.setproperties(self._properties, self._opt, self._path)
def reset(self):
"""resets the properties (does not **clear** the properties,
@ -353,11 +353,14 @@ class Settings(object):
path = opt.impl_getpath(self._getcontext())
return self.getproperties(opt, path)
def getproperties(self, opt, path, setting_properties=undefined):
return Property(self,
self._getproperties(opt, path,
setting_properties=setting_properties),
opt, path)
def getproperties(self, opt, path, setting_properties=undefined, index=None, obj=True):
"""get properties for a specified option
"""
properties = self._getproperties(opt, path, index=index,
setting_properties=setting_properties)
if obj:
return Property(self, properties, opt, path)
return properties
def __setitem__(self, opt, value): # pragma: optional cover
raise ValueError(_('you should only append/remove properties'))
@ -435,20 +438,25 @@ class Settings(object):
props = self._p_.getproperties(None, default_properties)
if propname not in props:
props.add(propname)
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def remove(self, propname):
"deletes property propname in the Config's properties attribute"
props = self._p_.getproperties(None, default_properties)
if propname in props:
props.remove(propname)
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def extend(self, propnames):
for propname in propnames:
self.append(propname)
def _setproperties(self, properties, opt, path, force=False):
"""just for compatibility
"""
self.setproperties(properties, opt, path, force)
def setproperties(self, properties, opt, path, force=False):
"""save properties for specified path
(never save properties if same has option properties)
"""
@ -617,7 +625,7 @@ class Settings(object):
props = props | append
modified = True
if modified:
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def read_only(self):
"convenience method to freeze, hide and disable"

View File

@ -160,7 +160,8 @@ class Values(object):
"""overrides the builtins `del()` instructions"""
self.reset(opt)
def reset(self, opt, path=None, validate=True, _setting_properties=None, _commit=True):
def reset(self, opt, path=None, validate=True, _setting_properties=None, _commit=True,
force_permissive=False):
context = self._getcontext()
setting = context.cfgimpl_get_settings()
if path is None:
@ -177,11 +178,13 @@ class Values(object):
fake_value.reset(opt, path, validate=False)
ret = fake_value._get_cached_value(opt, path,
setting_properties=_setting_properties,
check_frozen=True)
check_frozen=True,
force_permissive=force_permissive)
if isinstance(ret, Exception):
raise ret
if opt.impl_is_master_slaves('master'):
opt.impl_get_master_slaves().reset(opt, self, _setting_properties, _commit=_commit)
opt.impl_get_master_slaves().reset(opt, self, _setting_properties, _commit=_commit,
force_permissive=force_permissive)
if hasvalue:
if 'force_store_value' in setting._getproperties(opt=opt,
path=path,
@ -462,16 +465,20 @@ class Values(object):
if valid_masterslave and opt.impl_is_master_slaves():
if session is None:
session = self._p_.getsession()
setitem = True
if opt.impl_is_master_slaves('master'):
masterlen = len(value)
slavelen = None
elif index is not None:
masterlen = None
slavelen = index
setitem = False
else:
masterlen = None
slavelen = len(value)
setitem = True
opt.impl_get_master_slaves().impl_validate(self._getcontext(), force_permissive,
setting_properties, masterlen=masterlen,
slavelen=slavelen, opt=opt, setitem=True)
slavelen=slavelen, opt=opt, setitem=setitem)
#val = opt.impl_get_master_slaves().impl_validate(self, opt, len_value, path, session, setitem=setitem)
#if isinstance(val, Exception):
# return val
@ -533,7 +540,7 @@ class Values(object):
if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
return owners.default
if validate_properties:
value = self._get_cached_value(opt, path, True, force_permissive, None, True,
value = self._get_cached_value(opt, path=path, force_permissive=force_permissive,
self_properties=self_properties, session=session,
index=index)
if isinstance(value, Exception):
@ -557,7 +564,7 @@ class Values(object):
only_default=only_default, index=index)
return owner
def setowner(self, opt, owner, index=None):
def setowner(self, opt, owner, index=None, force_permissive=False):
"""
sets a owner to an option
@ -569,16 +576,17 @@ class Values(object):
path = opt.impl_getpath(self._getcontext())
session = self._p_.getsession()
if not self._p_.hasvalue(path, session):
raise ConfigError(_('no value for {0} cannot change owner to {1}'
'').format(path, owner))
props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
False,
True,
path,
index=index)
index=index,
force_permissive=force_permissive)
if props:
raise props
if not self._p_.hasvalue(path, session):
raise ConfigError(_('no value for {0} cannot change owner to {1}'
'').format(path, owner))
self._p_.setowner(path, owner, session, index=index)
def is_default_owner(self, opt, path=None, validate_properties=True,
@ -900,7 +908,7 @@ class Multi(list):
:param index: remove item a index
:type index: int
:param force: force pop item (withoud check master/slave)
:param force: force pop item (without check master/slave)
:type force: boolean
:returns: item at index
"""