This commit is contained in:
Emmanuel Garette 2019-02-24 20:23:16 +01:00
parent 375b3c91de
commit af55e20afe
12 changed files with 76 additions and 80 deletions

View File

@ -12,7 +12,7 @@ from tiramisu import Config
from tiramisu.config import SubConfig from tiramisu.config import SubConfig
from tiramisu.i18n import _ from tiramisu.i18n import _
from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \ from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, UnicodeOption, OptionDescription, undefined BoolOption, UnicodeOption, SymLinkOption, OptionDescription, undefined
from tiramisu.error import ConflictError, ConfigError, PropertiesOptionError, APIError from tiramisu.error import ConflictError, ConfigError, PropertiesOptionError, APIError
from tiramisu.storage import list_sessions from tiramisu.storage import list_sessions
@ -68,20 +68,13 @@ def test_base_config_name():
# assert raises(TypeError, "Config('str')") # assert raises(TypeError, "Config('str')")
#def test_base_path(): def test_base_path():
# gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
# descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
# cfg = Config(descr) Config(descr)
# assert cfg._impl_path is None base = OptionDescription('config', '', [descr])
# base = OptionDescription('config', '', [descr]) base
# cfg = Config(base) raises(ConfigError, "Config(base)")
# assert cfg._impl_path is None
# assert cfg.getattr('tiramisu', None, validate_properties=False)._impl_path == 'tiramisu'
# nbase = OptionDescription('baseconfig', '', [base])
# cfg = Config(nbase)
# assert cfg._impl_path is None
# assert cfg.getattr('config', None, validate_properties=False)._impl_path == 'config'
# assert cfg.getattr('config.tiramisu', None, validate_properties=False)._impl_path == 'config.tiramisu'
def test_base_config_force_permissive(): def test_base_config_force_permissive():
@ -306,3 +299,40 @@ def test_config_subconfig():
od2 = OptionDescription('od2', '', [od1]) od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf1') conf1 = Config(od2, session_id='conf1')
raises(ConfigError, "conf2 = Config(od1, session_id='conf2')") raises(ConfigError, "conf2 = Config(od1, session_id='conf2')")
def test_config_invalidsession():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
raises(ValueError, 'Config(o2, session_id=2)')
def test_config_od_name():
i = IntOption('i', '')
s = SymLinkOption('s', i)
o = OptionDescription('val', '', [i, s])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').option.name() == 'i'
assert c.option('val.s').option.name() == 's'
assert c.option('val.s').option.name(follow_symlink=True) == 'i'
def test_config_od_type():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').option.type() == 'integer'
def test_config_default():
i = IntOption('i', '', 8)
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').value.default() == 8
c.option('val.i').value.set(9)
assert c.option('val.i').value.get() == 9
assert c.option('val.i').value.default() == 8

View File

@ -104,6 +104,7 @@ def test_network_cidr():
cfg.option('a').value.set('0.0.0.0/0') cfg.option('a').value.set('0.0.0.0/0')
raises(ValueError, "cfg.option('a').value.set('192.168.1.1')") raises(ValueError, "cfg.option('a').value.set('192.168.1.1')")
raises(ValueError, "cfg.option('a').value.set('192.168.1.1/24')") raises(ValueError, "cfg.option('a').value.set('192.168.1.1/24')")
raises(ValueError, "cfg.option('a').value.set('2001:db00::0/24')")
def test_network_invalid(): def test_network_invalid():
@ -133,6 +134,7 @@ def test_broadcast():
raises(ValueError, "cfg.option('a').value.set('192.168.0.300')") raises(ValueError, "cfg.option('a').value.set('192.168.0.300')")
raises(ValueError, "cfg.option('a').value.set(1)") raises(ValueError, "cfg.option('a').value.set(1)")
raises(ValueError, "cfg.option('a').value.set(2)") raises(ValueError, "cfg.option('a').value.set(2)")
raises(ValueError, "cfg.option('a').value.set('2001:db8::1')")
cfg.option('a').value.set('0.0.0.0') cfg.option('a').value.set('0.0.0.0')
cfg.option('a').value.set('255.255.255.0') cfg.option('a').value.set('255.255.255.0')

View File

@ -222,3 +222,8 @@ def test_intoption():
cfg.option('test2').value.set(2) cfg.option('test2').value.set(2)
cfg.option('test2').value.set(3) cfg.option('test2').value.set(3)
raises(ValueError, "cfg.option('test2').value.set(4)") raises(ValueError, "cfg.option('test2').value.set(4)")
def test_get_display_type():
i1 = IntOption('test1', 'description', min_number=3)
assert i1.get_display_type() == 'integer'

View File

@ -82,6 +82,9 @@ def test_mod_read_only_write():
config.property.setdefault(type='read_write', when='append', properties={'disabled', config.property.setdefault(type='read_write', when='append', properties={'disabled',
'hidden'}) 'hidden'})
config.property.setdefault(type='read_write', when='remove', properties=set([])) config.property.setdefault(type='read_write', when='remove', properties=set([]))
raises(ValueError, "config.property.setdefault(type='unknown', when='append', properties={'disabled'})")
raises(ValueError, "config.property.setdefault(type='read_only', when='unknown', properties={'disabled'})")
raises(TypeError, "config.property.setdefault(type='read_only', when='append', properties=['disabled'])")
assert config.property.getdefault() == {'cache'} assert config.property.getdefault() == {'cache'}
assert config.property.getdefault('read_only', 'append') == {'disabled'} assert config.property.getdefault('read_only', 'append') == {'disabled'}
@ -116,6 +119,8 @@ def test_mod_read_only_write():
'everything_frozen', 'everything_frozen',
'mandatory', 'mandatory',
'empty'} 'empty'}
raises(ValueError, "config2.property.getdefault('unknown', 'remove')")
raises(ValueError, "config2.property.getdefault('read_write', 'unknown')")
def test_setitem(): def test_setitem():
@ -286,6 +291,7 @@ def test_apply_requires_from_config():
raises(PropertiesOptionError, "api.option('opt.str').value.get()") raises(PropertiesOptionError, "api.option('opt.str').value.get()")
assert 'hidden' in api.forcepermissive.option('opt.str').property.get() assert 'hidden' in api.forcepermissive.option('opt.str').property.get()
assert 'hidden' not in api.forcepermissive.option('opt.str').option.properties() assert 'hidden' not in api.forcepermissive.option('opt.str').option.properties()
assert 'hidden' not in api.forcepermissive.option('opt.str').option.properties(only_raises=True)
def test_apply_requires_with_disabled(): def test_apply_requires_with_disabled():
@ -301,6 +307,7 @@ def test_apply_requires_with_disabled():
api.option('int').value.set(1) api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.get()") raises(PropertiesOptionError, "api.option('opt.str').value.get()")
assert 'disabled' not in api.unrestraint.option('opt.str').option.properties() assert 'disabled' not in api.unrestraint.option('opt.str').option.properties()
assert 'disabled' not in api.unrestraint.option('opt.str').option.properties(only_raises=True)
assert 'disabled' in api.unrestraint.option('opt.str').property.get() assert 'disabled' in api.unrestraint.option('opt.str').property.get()

View File

@ -148,11 +148,7 @@ class _TiramisuOptionOptionDescription(CommonTiramisuOption):
return self._option_bag.option return self._option_bag.option
def type(self): def type(self):
type_ = self._option_bag.option.__class__.__name__ return self._option_bag.option.get_display_type()
if type_.endswith('Option'):
type_ = type_[:-6]
type_ = type_.lower()
return type_
def isleadership(self): def isleadership(self):
"""Test if option is a leader or a follower""" """Test if option is a leader or a follower"""
@ -659,29 +655,6 @@ class _TiramisuOptionDescription(_TiramisuOption):
return t_option return t_option
ret.append(t_option) ret.append(t_option)
return ret return ret
#
# def get(self, name):
# self._get_option()
# current_option = self._option_bag.option.get_child(name,
# self._config_bag,
# self._subconfig.cfgimpl_get_path)
# path = self._option_bag.path + '.' + name
# option_bag= OptionBag()
# option_bag.set_option(current_option,
# path,
# None,
# self._config_bag)
# if current_option.impl_is_optiondescription():
# subconfig = self._subconfig.getattr(name,
# option_bag)
# else:
# subconfig = self._subconfig
# return TiramisuOption(name,
# path,
# None,
# subconfig,
# self._config_bag,
# option_bag)
def group_type(self): def group_type(self):
"""Get type for an optiondescription (only for optiondescription)""" """Get type for an optiondescription (only for optiondescription)"""

View File

@ -77,5 +77,5 @@ class ParamIndex(Param):
__slots__ = tuple() __slots__ = tuple()
def tiramisu_copy(val): def tiramisu_copy(val): # pragma: no cover
return val return val

View File

@ -18,7 +18,6 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
import re
from types import FunctionType from types import FunctionType
from typing import FrozenSet, Callable, Tuple, Set, Optional, Union, Any, List from typing import FrozenSet, Callable, Tuple, Set, Optional, Union, Any, List
import weakref import weakref
@ -36,14 +35,12 @@ STATIC_TUPLE = frozenset()
submulti = 2 submulti = 2
NAME_REGEXP = re.compile(r'^[a-zA-Z][a-zA-Z\d_-]*$')
def valid_name(name): def valid_name(name):
if not isinstance(name, str): if not isinstance(name, str):
return False return False
return True return True
# return re.match(NAME_REGEXP, name) is not None
#____________________________________________________________ #____________________________________________________________

View File

@ -18,7 +18,7 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_address, IPv4Address, ip_network from ipaddress import ip_address, ip_network
from ..error import ConfigError from ..error import ConfigError
from ..setting import undefined, Undefined, OptionBag from ..setting import undefined, Undefined, OptionBag
@ -42,8 +42,7 @@ class BroadcastOption(Option):
if val.startswith("0") and len(val) > 1: if val.startswith("0") and len(val) > 1:
raise ValueError() raise ValueError()
try: try:
if not isinstance(ip_address(value), IPv4Address): ip_address(value)
raise ValueError()
except ValueError: except ValueError:
raise ValueError() raise ValueError()

View File

@ -111,22 +111,14 @@ class DomainnameOption(StrOption):
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
if self.impl_get_extra('_allow_ip') is True: try:
try: ip_address(value)
if not isinstance(ip_address(value), IPv4Address): except ValueError:
raise ValueError() pass
except ValueError:
pass
else:
return
else: else:
try: if self.impl_get_extra('_allow_ip') is True:
if not isinstance(ip_address(value), IPv4Address): return
raise ValueError() raise ValueError(_('must not be an IP'))
except ValueError:
pass
else:
raise ValueError(_('must not be an IP'))
part_name_length = self._get_len(self.impl_get_extra('_dom_type')) part_name_length = self._get_len(self.impl_get_extra('_dom_type'))
if self.impl_get_extra('_dom_type') == 'domainname': if self.impl_get_extra('_dom_type') == 'domainname':
if not self.impl_get_extra('_allow_without_dot') and not "." in value: if not self.impl_get_extra('_allow_without_dot') and not "." in value:

View File

@ -18,7 +18,7 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_address, ip_interface, ip_network, IPv4Address, IPv4Interface from ipaddress import ip_address, ip_interface, ip_network
from ..error import ConfigError from ..error import ConfigError
from ..setting import undefined, Undefined, OptionBag from ..setting import undefined, Undefined, OptionBag
@ -90,11 +90,9 @@ class IPOption(StrOption):
# 'standard' validation # 'standard' validation
try: try:
if not cidr: if not cidr:
if not isinstance(ip_address(value), IPv4Address): ip_address(value)
raise ValueError()
else: else:
if not isinstance(ip_interface(value), IPv4Address): ip_interface(value)
raise ValueError()
except ValueError: except ValueError:
raise ValueError() raise ValueError()

View File

@ -18,7 +18,7 @@
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/ # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ipaddress import ip_address, ip_network, IPv4Network from ipaddress import ip_address, ip_network
from ..setting import undefined from ..setting import undefined
from ..i18n import _ from ..i18n import _
@ -78,8 +78,7 @@ class NetworkOption(Option):
if val.startswith("0") and len(val) > 1: if val.startswith("0") and len(val) > 1:
raise ValueError() raise ValueError()
try: try:
if not isinstance(ip_network(value), IPv4Network): ip_network(value)
raise ValueError()
except ValueError: except ValueError:
raise ValueError() raise ValueError()

View File

@ -206,13 +206,7 @@ class Option(BaseOption):
def impl_get_extra(self, def impl_get_extra(self,
key: str) -> Any: key: str) -> Any:
extra = getattr(self, '_extra', {}) return getattr(self, '_extra', {}).get(key)
if isinstance(extra, tuple):
if key in extra[0]:
return extra[1][extra[0].index(key)]
return None
else:
return extra.get(key)
#__________________________________________________________________________ #__________________________________________________________________________
# validator # validator