8 Commits

6 changed files with 53 additions and 21 deletions

14
tests/test_simple.py Normal file
View File

@ -0,0 +1,14 @@
from json import loads
from tiramisu_api import Config
from pytest import raises
def test_list_option():
filename = 'tests/data/boolean1.json'
with open(filename, 'r') as fh:
json = loads(fh.read())
#
config = Config(json)
opts = []
raises(AttributeError, "config.option('unknown').value.get()")
raises(AttributeError, "config.option('options.unknown').value.get()")

View File

@ -1,5 +1,5 @@
from .api import Config from .api import Config
__version__ = "0.2" __version__ = "0.5"
__all__ = ('Config',) __all__ = ('Config',)

View File

@ -26,7 +26,8 @@ TYPE = {'boolean': bool,
'broadcast_address': str, 'broadcast_address': str,
'port': str, 'port': str,
'domainname': str, 'domainname': str,
'date': str} 'date': str,
'float': float}
class Option: class Option:
@ -225,13 +226,14 @@ class _Value:
withwarning: bool=False, withwarning: bool=False,
flatten: bool=False): flatten: bool=False):
ret = {} ret = {}
self._dict_walk(ret, if self.schema:
self.schema, self._dict_walk(ret,
self.path, self.schema,
fullpath, self.path,
withwarning, fullpath,
flatten, withwarning,
None) flatten,
None)
return ret return ret
@ -326,11 +328,11 @@ class TiramisuOptionValue(_Value):
def set(self, value): def set(self, value):
type_ = self.schema['type'] type_ = self.schema['type']
leader_old_value = undefined leader_old_value = undefined
if self.config.is_hidden(self.path, self.index): remote = self.config.form.get(self.path, {}).get('remote', False)
if not remote and self.config.is_hidden(self.path, self.index):
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option') raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
if self.config.isleader(self.path): if self.config.isleader(self.path):
leader_old_value = self.config.get_value(self.path) leader_old_value = self.config.get_value(self.path)
remote = self.config.form.get(self.path, {}).get('remote', False)
if self.index is None and self.schema.get('isMulti', False): if self.index is None and self.schema.get('isMulti', False):
if not isinstance(value, list): if not isinstance(value, list):
raise ValueError('value must be a list') raise ValueError('value must be a list')
@ -574,7 +576,7 @@ class ContextOption(_Option):
schema: Dict) -> None: schema: Dict) -> None:
self.config = config self.config = config
self.schema = {'properties': schema} self.schema = {'properties': schema}
self.index = None self.index = None
def __call__(self, def __call__(self,
path: str, path: str,
@ -597,7 +599,7 @@ class ContextOwner:
schema: Dict) -> None: schema: Dict) -> None:
self.config = config self.config = config
self.schema = {'properties': schema} self.schema = {'properties': schema}
self.index = None self.index = None
def get(self): def get(self):
return self.config.global_model.get('owner', 'tmp') return self.config.global_model.get('owner', 'tmp')
@ -609,9 +611,12 @@ class ContextValue(_Value):
config: 'Config', config: 'Config',
schema: Dict) -> None: schema: Dict) -> None:
self.config = config self.config = config
first = next(iter(schema.keys())) if schema:
self.path = first.rsplit('.', 1)[0] first = next(iter(schema.keys()))
self.schema = {'properties': schema} self.path = first.rsplit('.', 1)[0]
self.schema = {'properties': schema}
else:
self.schema = {}
def __call__(self) -> TiramisuOptionValue: def __call__(self) -> TiramisuOptionValue:
return TiramisuOptionValue(self.config, return TiramisuOptionValue(self.config,
@ -644,6 +649,7 @@ class Config:
# config # config
def __init__(self, def __init__(self,
dico): dico):
self._unrestraint = False
if DEBUG: if DEBUG:
from pprint import pprint from pprint import pprint
pprint(dico) pprint(dico)
@ -668,6 +674,7 @@ class Config:
self.root = first_path.rsplit('.', 1)[0] self.root = first_path.rsplit('.', 1)[0]
else: else:
self.root = '' self.root = ''
self.dico = dico
def __getattr__(self, def __getattr__(self,
subfunc: str) -> Any: subfunc: str) -> Any:
@ -682,6 +689,11 @@ class Config:
if subfunc == 'owner': if subfunc == 'owner':
return ContextOwner(self, return ContextOwner(self,
self.schema) self.schema)
if subfunc == 'unrestraint':
ret = Config(self.dico)
ret._unrestraint = True
ret.temp = self.temp
return ret
raise APIError(_('please specify a valid sub function ({})').format(subfunc)) raise APIError(_('please specify a valid sub function ({})').format(subfunc))
def add_value(self, def add_value(self,
@ -811,12 +823,16 @@ class Config:
subpaths = path.split('.')[len(root):] subpaths = path.split('.')[len(root):]
else: else:
subpaths = path.split('.') subpaths = path.split('.')
current_subpath = 'root'
for subpath in subpaths: for subpath in subpaths:
if root_path: if root_path:
root_path += '.' + subpath root_path += '.' + subpath
else: else:
root_path = subpath root_path = subpath
schema = schema['properties'][root_path] schema = schema['properties'].get(root_path)
if schema is None:
raise AttributeError(_('option "{0}" inconnue dans l\'optiondescription "{1}"').format(subpath, current_subpath))
current_subpath = subpath
return schema return schema
def isleader(self, def isleader(self,
@ -843,6 +859,8 @@ class Config:
path: str, path: str,
index: Optional[int], index: Optional[int],
permissive: bool=False) -> bool: permissive: bool=False) -> bool:
if self._unrestraint:
return False
if permissive: if permissive:
property_ = 'hidden' property_ = 'hidden'
needs = True needs = True

View File

@ -1,6 +1,6 @@
try: try:
from tiramisu.error import APIError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError, ConfigError, display_list from tiramisu.error import APIError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError, ConfigError, display_list
except ModuleNotFoundError: except ImportError:
import weakref import weakref
from .i18n import _ from .i18n import _
@ -130,7 +130,7 @@ except ModuleNotFoundError:
if self.msg: if self.msg:
return self.msg return self.msg
if self._option_bag is None: if self._option_bag is None:
return "unknown error" return "option désactivée"
req = self._settings.apply_requires(self._option_bag, req = self._settings.apply_requires(self._option_bag,
True) True)
# if req != {} or self._orig_opt is not None: # if req != {} or self._orig_opt is not None:

View File

@ -1,6 +1,6 @@
try: try:
from tiramisu.i18n import _ from tiramisu.i18n import _
except ModuleNotFoundError: except ImportError:
# FIXME # FIXME
def _(val): def _(val):
return val return val

View File

@ -1,6 +1,6 @@
try: try:
from tiramisu.setting import undefined from tiramisu.setting import undefined
except ModuleNotFoundError: except ImportError:
class Undefined(object): class Undefined(object):
def __str__(self): def __str__(self):
return 'Undefined' return 'Undefined'