remove _setoption in SymLinkOption

objimpl_ => optimpl_
ConflictConfigError => ConflictError
add read_write/read_only/getowner in Config
This commit is contained in:
Emmanuel Garette 2013-04-22 09:19:05 +02:00
parent 682d9fe207
commit e883e5b89e
16 changed files with 355 additions and 419 deletions

View File

@ -38,7 +38,7 @@ def test_freeze_whole_config():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
setting = conf.cfgimpl_get_settings() setting = conf.cfgimpl_get_settings()
setting.read_write() conf.read_write()
setting.append('everything_frozen') setting.append('everything_frozen')
assert conf.gc.dummy is False assert conf.gc.dummy is False
prop = [] prop = []
@ -57,7 +57,7 @@ def test_freeze_one_option():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
setting = conf.cfgimpl_get_settings() setting = conf.cfgimpl_get_settings()
setting.read_write() conf.read_write()
#freeze only one option #freeze only one option
dummy = conf.unwrap_from_path('gc.dummy') dummy = conf.unwrap_from_path('gc.dummy')
setting[dummy].append('frozen') setting[dummy].append('frozen')
@ -76,7 +76,7 @@ def test_frozen_value():
descr = OptionDescription("options", "", [s]) descr = OptionDescription("options", "", [s])
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
setting.append('frozen') setting.append('frozen')
setting[s].append('frozen') setting[s].append('frozen')
prop = [] prop = []
@ -92,7 +92,7 @@ def test_freeze():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
setting = conf.cfgimpl_get_settings() setting = conf.cfgimpl_get_settings()
setting.read_write() conf.read_write()
setting.append('frozen') setting.append('frozen')
name = conf.unwrap_from_path("gc.name") name = conf.unwrap_from_path("gc.name")
setting[name].append('frozen') setting[name].append('frozen')
@ -108,7 +108,7 @@ def test_freeze_multi():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
setting = conf.cfgimpl_get_settings() setting = conf.cfgimpl_get_settings()
setting.read_write() conf.read_write()
setting.append('frozen') setting.append('frozen')
obj = conf.unwrap_from_path('boolop') obj = conf.unwrap_from_path('boolop')
setting[obj].append('frozen') setting[obj].append('frozen')
@ -124,7 +124,7 @@ def test_freeze_get_multi():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
setting = conf.cfgimpl_get_settings() setting = conf.cfgimpl_get_settings()
setting.read_write() conf.read_write()
setting.append('frozen') setting.append('frozen')
valmulti = conf.boolop valmulti = conf.boolop
valmulti.append(False) valmulti.append(False)
@ -141,7 +141,6 @@ def test_freeze_get_multi():
def test_force_store_value(): def test_force_store_value():
descr = make_description_freeze() descr = make_description_freeze()
conf = Config(descr) conf = Config(descr)
opt = conf.unwrap_from_path('wantref') assert conf.getowner('wantref') == 'default'
assert conf.cfgimpl_get_values().getowner(opt) == 'default'
conf.wantref conf.wantref
assert conf.cfgimpl_get_values().getowner(opt) == 'user' assert conf.getowner('wantref') == 'user'

View File

@ -22,25 +22,23 @@ def make_description():
def test_mandatory_ro(): def test_mandatory_ro():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() config.read_only()
setting.read_only()
prop = [] prop = []
try: try:
config.str1 config.str1
except PropertiesOptionError, err: except PropertiesOptionError, err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
setting.read_write() config.read_write()
config.str1 = 'yes' config.str1 = 'yes'
setting.read_only() config.read_only()
assert config.str1 == 'yes' assert config.str1 == 'yes'
def test_mandatory_rw(): def test_mandatory_rw():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() config.read_write()
setting.read_write()
#not mandatory in rw #not mandatory in rw
config.str1 config.str1
config.str1 = 'yes' config.str1 = 'yes'
@ -50,17 +48,16 @@ def test_mandatory_rw():
def test_mandatory_default(): def test_mandatory_default():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() config.read_only()
setting.read_only()
#not mandatory in rw #not mandatory in rw
config.str config.str
setting.read_write() config.read_write()
config.str = 'yes' config.str = 'yes'
setting.read_only() config.read_only()
config.str config.str
setting.read_write() config.read_write()
config.str = None config.str = None
setting.read_only() config.read_only()
prop = [] prop = []
try: try:
config.str config.str
@ -74,9 +71,8 @@ def test_mandatory_none():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
config.str1 = None config.str1 = None
setting = config.cfgimpl_get_settings() assert config.getowner('str1') == 'user'
assert config.cfgimpl_get_values().getowner(descr.str1) == 'user' config.read_only()
setting.read_only()
prop = [] prop = []
try: try:
config.str1 config.str1
@ -89,9 +85,8 @@ def test_mandatory_empty():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
config.str1 = '' config.str1 = ''
setting = config.cfgimpl_get_settings() assert config.getowner('str1') == 'user'
assert config.cfgimpl_get_values().getowner(descr.str1) == 'user' config.read_only()
setting.read_only()
prop = [] prop = []
try: try:
config.str1 config.str1
@ -103,20 +98,19 @@ def test_mandatory_empty():
def test_mandatory_multi_none(): def test_mandatory_multi_none():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings()
config.str3 = [None] config.str3 = [None]
setting.read_only() config.read_only()
assert config.cfgimpl_get_values().getowner(descr.str3) == 'user' assert config.getowner('str3') == 'user'
prop = [] prop = []
try: try:
config.str3 config.str3
except PropertiesOptionError, err: except PropertiesOptionError, err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
setting.read_write() config.read_write()
config.str3 = ['yes', None] config.str3 = ['yes', None]
setting.read_only() config.read_only()
assert config.cfgimpl_get_values().getowner(descr.str3) == 'user' assert config.getowner('str3') == 'user'
prop = [] prop = []
try: try:
config.str3 config.str3
@ -128,20 +122,19 @@ def test_mandatory_multi_none():
def test_mandatory_multi_empty(): def test_mandatory_multi_empty():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings()
config.str3 = [''] config.str3 = ['']
setting.read_only() config.read_only()
assert config.cfgimpl_get_values().getowner(descr.str3) == 'user' assert config.getowner('str3') == 'user'
prop = [] prop = []
try: try:
config.str3 config.str3
except PropertiesOptionError, err: except PropertiesOptionError, err:
prop = err.proptype prop = err.proptype
assert 'mandatory' in prop assert 'mandatory' in prop
setting.read_write() config.read_write()
config.str3 = ['yes', ''] config.str3 = ['yes', '']
setting.read_only() config.read_only()
assert config.cfgimpl_get_values().getowner(descr.str3) == 'user' assert config.getowner('str3') == 'user'
prop = [] prop = []
try: try:
config.str3 config.str3
@ -153,9 +146,8 @@ def test_mandatory_multi_empty():
def test_mandatory_multi_append(): def test_mandatory_multi_append():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings()
config.str3 = ['yes'] config.str3 = ['yes']
setting.read_write() config.read_write()
config.str3.append(None) config.str3.append(None)
@ -164,7 +156,7 @@ def test_mandatory_disabled():
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
config.str1 config.str1
setting.read_only() config.read_only()
prop = [] prop = []
try: try:
config.str1 config.str1
@ -183,18 +175,17 @@ def test_mandatory_disabled():
def test_mandatory_unicode(): def test_mandatory_unicode():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings()
config.unicode2 config.unicode2
setting.read_only() config.read_only()
prop = [] prop = []
try: try:
config.unicode2 config.unicode2
except PropertiesOptionError, err: except PropertiesOptionError, err:
prop = err.proptype prop = err.proptype
assert prop == ['mandatory'] assert prop == ['mandatory']
setting.read_write() config.read_write()
config.unicode2 = u'' config.unicode2 = u''
setting.read_only() config.read_only()
prop = [] prop = []
try: try:
config.unicode2 config.unicode2
@ -207,8 +198,7 @@ def test_mandatory_warnings_ro():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
config.str = '' config.str = ''
setting = config.cfgimpl_get_settings() config.read_only()
setting.read_only()
proc = [] proc = []
try: try:
config.str config.str
@ -216,9 +206,9 @@ def test_mandatory_warnings_ro():
proc = err.proptype proc = err.proptype
assert proc == ['mandatory'] assert proc == ['mandatory']
assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3']
setting.read_write() config.read_write()
config.str = 'a' config.str = 'a'
setting.read_only() config.read_only()
assert list(mandatory_warnings(config)) == ['str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str1', 'unicode2', 'str3']
@ -226,8 +216,7 @@ def test_mandatory_warnings_rw():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
config.str = '' config.str = ''
setting = config.cfgimpl_get_settings() config.read_write()
setting.read_write()
config.str config.str
assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3']
config.str = 'a' config.str = 'a'
@ -239,7 +228,7 @@ def test_mandatory_warnings_disabled():
config = Config(descr) config = Config(descr)
config.str = '' config.str = ''
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
config.str config.str
assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3']
setting[descr.str].append('disabled') setting[descr.str].append('disabled')
@ -251,9 +240,9 @@ def test_mandatory_warnings_frozen():
config = Config(descr) config = Config(descr)
config.str = '' config.str = ''
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
config.str config.str
assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3']
setting[descr.str].append('frozen') setting[descr.str].append('frozen')
setting.read_only() config.read_only()
assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3'] assert list(mandatory_warnings(config)) == ['str', 'str1', 'unicode2', 'str3']

View File

@ -1,64 +1,69 @@
import autopath import autopath
from py.test import raises from py.test import raises
from tiramisu.config import * from tiramisu.config import Config
from tiramisu.option import * from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption, \
from error import ConfigError StrOption, OptionDescription
from tiramisu.error import PropertiesOptionError, ConflictError
def make_description(): def make_description():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True) boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False, wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
wantframework_option = BoolOption('wantframework', 'Test requires', wantframework_option = BoolOption('wantframework', 'Test requires',
default=False, default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption, wantref_option, stroption,
wantframework_option, wantframework_option,
intoption, boolop]) intoption, boolop])
return descr return descr
def make_description_duplicates(): def make_description_duplicates():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
## dummy 1 ## dummy 1
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True) boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False, wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
wantframework_option = BoolOption('wantframework', 'Test requires', wantframework_option = BoolOption('wantframework', 'Test requires',
default=False, default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
# dummy2 (same path) # dummy2 (same path)
gcdummy2 = BoolOption('dummy', 'dummy2', default=True) gcdummy2 = BoolOption('dummy', 'dummy2', default=True)
# dummy3 (same name) # dummy3 (same name)
gcdummy3 = BoolOption('dummy', 'dummy2', default=True) gcdummy3 = BoolOption('dummy', 'dummy2', default=True)
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, gcdummy2, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, gcdummy2, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption, wantref_option, stroption,
wantframework_option, wantframework_option,
intoption, boolop, gcdummy3]) intoption, boolop, gcdummy3])
return descr return descr
def test_identical_paths(): def test_identical_paths():
"""If in the schema (the option description) there is something that """If in the schema (the option description) there is something that
have the same name, an exection is raised have the same name, an exection is raised
""" """
raises(ConflictConfigError, "make_description_duplicates()") raises(ConflictError, "make_description_duplicates()")
def make_description2(): def make_description2():
gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref') gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref')
@ -67,7 +72,7 @@ def make_description2():
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
['std', 'thunk'], 'std') ['std', 'thunk'], 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
@ -75,7 +80,7 @@ def make_description2():
boolop = BoolOption('boolop', 'Test boolean option op', default=True) boolop = BoolOption('boolop', 'Test boolean option op', default=True)
boolop.enable_multi() boolop.enable_multi()
wantref_option = BoolOption('wantref', 'Test requires', default=False, wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
# second multi # second multi
wantframework_option = BoolOption('wantframework', 'Test requires', wantframework_option = BoolOption('wantframework', 'Test requires',
default=False, default=False,
@ -84,11 +89,12 @@ def make_description2():
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption, wantref_option, stroption,
wantframework_option, wantframework_option,
intoption, boolop]) intoption, boolop])
return descr return descr
# FIXME: il faudra tester les validations sur les multis # FIXME: il faudra tester les validations sur les multis
#def test_multi_constraints(): #def test_multi_constraints():
# "a multi in a constraint has to have the same length" # "a multi in a constraint has to have the same length"
@ -134,6 +140,8 @@ def make_description2():
# config.cfgimpl_update() # config.cfgimpl_update()
# assert config.newoption == False # assert config.newoption == False
# ____________________________________________________________ # ____________________________________________________________
def make_description_requires(): def make_description_requires():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
@ -141,7 +149,7 @@ def make_description_requires():
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc", stroption = StrOption('str', 'Test string option', default="abc",
@ -149,15 +157,15 @@ def make_description_requires():
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
stroption, intoption]) stroption, intoption])
return descr return descr
def test_hidden_if_in(): def test_hidden_if_in():
descr = make_description_requires() descr = make_description_requires()
cfg = Config(descr) cfg = Config(descr)
setting = cfg.cfgimpl_get_settings() setting = cfg.cfgimpl_get_settings()
setting.read_write() cfg.read_write()
intoption = cfg.unwrap_from_path('int')
stroption = cfg.unwrap_from_path('str') stroption = cfg.unwrap_from_path('str')
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
cfg.int = 1 cfg.int = 1
@ -165,6 +173,7 @@ def test_hidden_if_in():
raises(PropertiesOptionError, 'cfg.str="uvw"') raises(PropertiesOptionError, 'cfg.str="uvw"')
assert 'hidden' in setting[stroption] assert 'hidden' in setting[stroption]
def test_hidden_if_in_with_group(): def test_hidden_if_in_with_group():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
@ -172,21 +181,22 @@ def test_hidden_if_in_with_group():
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption], gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption],
requires=(('int', 1, 'hidden'),)) requires=(('int', 1, 'hidden'),))
descr = OptionDescription('constraints', '', [gcgroup, booloption, descr = OptionDescription('constraints', '', [gcgroup, booloption,
objspaceoption, stroption, intoption]) objspaceoption, stroption, intoption])
cfg = Config(descr) cfg = Config(descr)
setting = cfg.cfgimpl_get_settings() setting = cfg.cfgimpl_get_settings()
setting.read_write() cfg.read_write()
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
cfg.int = 1 cfg.int = 1
raises(PropertiesOptionError, "cfg.gc.name") raises(PropertiesOptionError, "cfg.gc.name")
def test_disabled_with_group(): def test_disabled_with_group():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
@ -194,50 +204,51 @@ def test_disabled_with_group():
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption], gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption],
requires=(('int', 1, 'disabled'),)) requires=(('int', 1, 'disabled'),))
descr = OptionDescription('constraints', '', [gcgroup, booloption, descr = OptionDescription('constraints', '', [gcgroup, booloption,
objspaceoption, stroption, intoption]) objspaceoption, stroption, intoption])
cfg = Config(descr) cfg = Config(descr)
setting = cfg.cfgimpl_get_settings() cfg.read_write()
setting.read_write()
assert cfg.gc.name assert cfg.gc.name
cfg.int = 1 cfg.int = 1
raises(PropertiesOptionError, "cfg.gc.name") raises(PropertiesOptionError, "cfg.gc.name")
#____________________________________________________________ #____________________________________________________________
def make_description_callback(): def make_description_callback():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', callback="toto") gcdummy = BoolOption('dummy', 'dummy', callback="toto")
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std') ('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc") stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True) boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False, wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
wantframework_option = BoolOption('wantframework', 'Test requires', wantframework_option = BoolOption('wantframework', 'Test requires',
default=False, default=False,
requires=(('boolop', True, 'hidden'),)) requires=(('boolop', True, 'hidden'),))
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption, wantref_option, stroption,
wantframework_option, wantframework_option,
intoption, boolop]) intoption, boolop])
return descr return descr
def test_has_callback(): def test_has_callback():
descr = make_description_callback() descr = make_description_callback()
# here the owner is 'default' # here the owner is 'default'
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
config.bool = False config.bool = False
# because dummy has a callback # because dummy has a callback
dummy = config.unwrap_from_path('gc.dummy') dummy = config.unwrap_from_path('gc.dummy')
@ -245,15 +256,15 @@ def test_has_callback():
setting[dummy].append('frozen') setting[dummy].append('frozen')
raises(PropertiesOptionError, "config.gc.dummy = True") raises(PropertiesOptionError, "config.gc.dummy = True")
def test_freeze_and_has_callback(): def test_freeze_and_has_callback():
descr = make_description_callback() descr = make_description_callback()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
config.bool = False config.bool = False
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.append('freeze') setting.append('freeze')
dummy = config.unwrap_from_path('gc.dummy') dummy = config.unwrap_from_path('gc.dummy')
setting[dummy].append('frozen') setting[dummy].append('frozen')
raises(PropertiesOptionError, "config.gc.dummy = True") raises(PropertiesOptionError, "config.gc.dummy = True")
#____________________________________________________________

View File

@ -50,7 +50,7 @@ def test_default_is_none():
def test_set_defaut_value_from_option_object(): 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.objimpl_getdefault() is False assert b.optimpl_getdefault() is False
def test_force_default_on_freeze(): def test_force_default_on_freeze():

View File

@ -1,15 +1,16 @@
import autopath import autopath
from py.test import raises
from tiramisu.config import *
from tiramisu.option import *
from tiramisu.setting import owners from tiramisu.setting import owners
from tiramisu.config import Config
from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription
def make_description(): def make_description():
gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref') gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space', objspaceoption = ChoiceOption('objspace', 'Object space',
['std', 'thunk'], 'std') ['std', 'thunk'], 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True) booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0) intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3) floatoption = FloatOption('float', 'Test float option', default=2.3)
@ -21,41 +22,41 @@ def make_description():
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption]) gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiram', '', [gcgroup, booloption, objspaceoption, descr = OptionDescription('tiram', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption, wantref_option, stroption,
wantframework_option, wantframework_option,
intoption, boolop]) intoption, boolop])
return descr return descr
def test_default_owner(): def test_default_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = Config(descr)
assert cfg.dummy == False assert cfg.dummy is False
dm = cfg.unwrap_from_path('dummy') assert cfg.getowner('dummy') == 'default'
assert cfg.cfgimpl_get_values().getowner(dm) == 'default'
cfg.dummy = True cfg.dummy = True
assert cfg.cfgimpl_get_values().getowner(dm) == owners.user assert cfg.getowner('dummy') == owners.user
def test_add_owner(): def test_add_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = Config(descr)
assert cfg.dummy == False assert cfg.dummy is False
dm = cfg.unwrap_from_path('dummy') assert cfg.getowner('dummy') == 'default'
assert cfg.cfgimpl_get_values().getowner(dm) == 'default'
owners.add_owner("gen_config") owners.add_owner("gen_config")
cfg.cfgimpl_get_settings().setowner(owners.gen_config) cfg.cfgimpl_get_settings().setowner(owners.gen_config)
cfg.dummy = True cfg.dummy = True
assert cfg.cfgimpl_get_values().getowner(dm) == owners.gen_config assert cfg.getowner('dummy') == owners.gen_config
def test_owner_is_not_a_string(): def test_owner_is_not_a_string():
gcdummy = BoolOption('dummy', 'dummy', default=False) gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr) cfg = Config(descr)
assert cfg.dummy == False assert cfg.dummy is False
dm = cfg.unwrap_from_path('dummy') assert cfg.getowner('dummy') == owners.default
assert cfg.cfgimpl_get_values().getowner(dm) == owners.default assert cfg.getowner('dummy') == 'default'
assert cfg.cfgimpl_get_values().getowner(dm) == 'default' assert isinstance(cfg.getowner('dummy'), owners.Owner)
assert isinstance(cfg.cfgimpl_get_values().getowner(dm), owners.Owner)
cfg.dummy = True cfg.dummy = True
assert cfg.cfgimpl_get_values().getowner(dm) == 'user' assert cfg.getowner('dummy') == 'user'

View File

@ -5,7 +5,7 @@ from py.test import raises
from tiramisu.setting import owners from tiramisu.setting import owners
from tiramisu.config import Config from tiramisu.config import Config
from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription StrOption, OptionDescription, SymLinkOption
from tiramisu.error import PropertiesOptionError from tiramisu.error import PropertiesOptionError
@ -56,10 +56,10 @@ def test_reset():
config = Config(descr) config = Config(descr)
config.string = "foo" config.string = "foo"
assert config.string == "foo" assert config.string == "foo"
assert config.cfgimpl_get_values().getowner(s) == owners.user assert config.getowner('string') == owners.user
del(config.string) del(config.string)
assert config.string == 'string' assert config.string == 'string'
assert config.cfgimpl_get_values().getowner(s) == owners.default assert config.getowner('string') == owners.default
def test_reset_with_multi(): def test_reset_with_multi():
@ -69,13 +69,13 @@ def test_reset_with_multi():
# config.string = [] # config.string = []
del(config.string) del(config.string)
assert config.string == ["string"] assert config.string == ["string"]
assert config.cfgimpl_get_values().getowner(s) == 'default' assert config.getowner('string') == 'default'
config.string = ["eggs", "spam", "foo"] config.string = ["eggs", "spam", "foo"]
assert config.cfgimpl_get_values().getowner(s) == 'user' assert config.getowner('string') == 'user'
config.string = [] config.string = []
del(config.string) del(config.string)
# assert config.string == ["string"] # assert config.string == ["string"]
assert config.cfgimpl_get_values().getowner(s) == 'default' assert config.getowner('string') == 'default'
raises(ValueError, "config.string = None") raises(ValueError, "config.string = None")
@ -113,27 +113,18 @@ def test_item_access_with_multi():
config.string = ["foo", "bar"] config.string = ["foo", "bar"]
assert config.string == ["foo", "bar"] assert config.string == ["foo", "bar"]
assert config.string[0] == "foo" assert config.string[0] == "foo"
# FIXME
config.string[0] = 'changetest' config.string[0] = 'changetest'
# assert config.string[0] == 'changetest' assert config.string[0] == 'changetest'
# assert config.string[
def test_access_with_multi_default(): def test_access_with_multi_default():
s = StrOption("string", "", default=["string"], multi=True) s = StrOption("string", "", default=["string"], multi=True)
descr = OptionDescription("options", "", [s]) descr = OptionDescription("options", "", [s])
config = Config(descr) config = Config(descr)
assert config._cfgimpl_values.getowner(s) == 'default' assert config.getowner('string') == 'default'
config.string = ["foo", "bar"] config.string = ["foo", "bar"]
assert config.string == ["foo", "bar"] assert config.string == ["foo", "bar"]
assert config._cfgimpl_values.getowner(s) == 'user' assert config.getowner('string') == 'user'
#def test_attribute_access_with_multi2():
# s = StrOption("string", "", default="string", multi=True)
# descr = OptionDescription("options", "", [s])
# config = Config(descr)
# config.string = ["foo", "bar"]
# assert config.string == ["foo", "bar"]
def test_multi_with_requires(): def test_multi_with_requires():
@ -144,7 +135,7 @@ def test_multi_with_requires():
descr = OptionDescription("options", "", [s, intoption, stroption]) descr = OptionDescription("options", "", [s, intoption, stroption])
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
config.int = 1 config.int = 1
raises(PropertiesOptionError, "config.str = ['a', 'b']") raises(PropertiesOptionError, "config.str = ['a', 'b']")
@ -174,7 +165,7 @@ def test_multi_with_requires_in_another_group():
descr2 = OptionDescription("opt2", "", [intoption, s, descr]) descr2 = OptionDescription("opt2", "", [intoption, s, descr])
config = Config(descr2) config = Config(descr2)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
config.int = 1 config.int = 1
raises(PropertiesOptionError, "config.opt.str = ['a', 'b']") raises(PropertiesOptionError, "config.opt.str = ['a', 'b']")
@ -191,7 +182,7 @@ def test_apply_requires_from_config():
descr2 = OptionDescription("opt2", "", [intoption, s, descr]) descr2 = OptionDescription("opt2", "", [intoption, s, descr])
config = Config(descr2) config = Config(descr2)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
config.int = 1 config.int = 1
raises(PropertiesOptionError, 'config.opt.str') raises(PropertiesOptionError, 'config.opt.str')
@ -208,7 +199,7 @@ def test_apply_requires_with_disabled():
descr2 = OptionDescription("opt2", "", [intoption, s, descr]) descr2 = OptionDescription("opt2", "", [intoption, s, descr])
config = Config(descr2) config = Config(descr2)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'disabled' in setting[stroption] assert not 'disabled' in setting[stroption]
config.int = 1 config.int = 1
raises(PropertiesOptionError, 'config.opt.str') raises(PropertiesOptionError, 'config.opt.str')
@ -225,7 +216,7 @@ def test_multi_with_requires_with_disabled_in_another_group():
descr2 = OptionDescription("opt2", "", [intoption, s, descr]) descr2 = OptionDescription("opt2", "", [intoption, s, descr])
config = Config(descr2) config = Config(descr2)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'disabled' in setting[stroption] assert not 'disabled' in setting[stroption]
config.int = 1 config.int = 1
raises(PropertiesOptionError, "config.opt.str = ['a', 'b']") raises(PropertiesOptionError, "config.opt.str = ['a', 'b']")
@ -240,7 +231,7 @@ def test_multi_with_requires_that_is_multi():
descr = OptionDescription("options", "", [s, intoption, stroption]) descr = OptionDescription("options", "", [s, intoption, stroption])
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
assert not 'hidden' in setting[stroption] assert not 'hidden' in setting[stroption]
config.int = [1, 1] config.int = [1, 1]
raises(PropertiesOptionError, "config.str = ['a', 'b']") raises(PropertiesOptionError, "config.str = ['a', 'b']")
@ -251,7 +242,7 @@ def test_multi_with_bool():
s = BoolOption("bool", "", default=[False], multi=True) s = BoolOption("bool", "", default=[False], multi=True)
descr = OptionDescription("options", "", [s]) descr = OptionDescription("options", "", [s])
config = Config(descr) config = Config(descr)
assert descr.bool.objimpl_is_multi() is True assert descr.bool.optimpl_is_multi() is True
config.bool = [True, False] config.bool = [True, False]
assert config.cfgimpl_get_values()[s] == [True, False] assert config.cfgimpl_get_values()[s] == [True, False]
assert config.bool == [True, False] assert config.bool == [True, False]
@ -261,7 +252,7 @@ def test_multi_with_bool_two():
s = BoolOption("bool", "", default=[False], multi=True) s = BoolOption("bool", "", default=[False], multi=True)
descr = OptionDescription("options", "", [s]) descr = OptionDescription("options", "", [s])
config = Config(descr) config = Config(descr)
assert descr.bool.objimpl_is_multi() is True assert descr.bool.optimpl_is_multi() is True
raises(ValueError, "config.bool = True") raises(ValueError, "config.bool = True")
@ -271,122 +262,40 @@ def test_choice_access_with_multi():
config = Config(descr) config = Config(descr)
config.t1 = ["a", "b", "a", "b"] config.t1 = ["a", "b", "a", "b"]
assert config.t1 == ["a", "b", "a", "b"] assert config.t1 == ["a", "b", "a", "b"]
# ____________________________________________________________
#def test_setoption_from_option():
# "a setoption directly from the option is **not** a good practice"
# booloption = BoolOption('bool', 'Test boolean option', default=True)
# descr = OptionDescription('descr', '', [booloption])
# cfg = Config(descr)
# booloption.setoption(cfg, False)
# assert cfg.bool == False
#____________________________________________________________ #____________________________________________________________
#def test_dwim_set(): def test_symlink_option():
# descr = OptionDescription("opt", "", [ boolopt = BoolOption("b", "", default=False)
# OptionDescription("sub", "", [ linkopt = SymLinkOption("c", "s1.b", opt=boolopt)
# BoolOption("b1", ""), descr = OptionDescription("opt", "",
# ChoiceOption("c1", "", ('a', 'b', 'c'), 'a'), [linkopt, OptionDescription("s1", "", [boolopt])])
# BoolOption("d1", ""), config = Config(descr)
# ]), setattr(config, "s1.b", True)
# BoolOption("b2", ""), setattr(config, "s1.b", False)
# BoolOption("d1", ""), assert config.s1.b is False
# ]) assert config.c is False
# c = Config(descr) config.c = True
# c.set(b1=False, c1='b') assert config.s1.b is True
# assert not c.sub.b1 assert config.c is True
# assert c.sub.c1 == 'b' config.c = False
# # new config, because you cannot change values once they are set assert config.s1.b is False
# c = Config(descr) assert config.c is False
# c.set(b2=False, **{'sub.c1': 'c'})
# assert not c.b2
# assert c.sub.c1 == 'c'
# raises(ConflictOptionError, "c.set(d1=True)")
# raises(AttributeError, "c.set(unknown='foo')")
#def test_more_set():
# descr = OptionDescription("opt", "", [
# OptionDescription("s1", "", [
# BoolOption("a", "", default=False)]),
# IntOption("int", "", default=42)])
# d = {'s1.a': True, 'int': 23}
# config = Config(descr)
# config.set(**d)
# assert config.s1.a
# assert config.int == 23
#def test_set_with_hidden_option():
# boolopt = BoolOption("a", "", default=False, properties=(('hidden'),))
# descr = OptionDescription("opt", "", [
# OptionDescription("s1", "", [boolopt]),
# IntOption("int", "", default=42)])
# d = {'s1.a': True, 'int': 23}
# config = Config(descr)
# setting = config.cfgimpl_get_settings()
# setting.read_write()
# raises(PropertiesOptionError, "config.set(**d)")
#
#
#def test_set_with_unknown_option():
# boolopt = BoolOption("b", "", default=False)
# descr = OptionDescription("opt", "", [
# OptionDescription("s1", "", [boolopt]),
# IntOption("int", "", default=42)])
# d = {'s1.a': True, 'int': 23}
# config = Config(descr)
# raises(AttributeError, "config.set(**d)")
#
#
#def test_set_symlink_option():
# boolopt = BoolOption("b", "", default=False)
# linkopt = SymLinkOption("c", "s1.b", opt=boolopt)
# descr = OptionDescription("opt", "",
# [linkopt, OptionDescription("s1", "", [boolopt])])
# config = Config(descr)
# setattr(config, "s1.b", True)
# setattr(config, "s1.b", False)
# assert config.s1.b is False
# assert config.c is False
# config.c = True
# assert config.s1.b is True
# assert config.c is True
# config.c = False
# assert config.s1.b is False
# assert config.c is False
#
##____________________________________________________________
#def test_config_impl_values():
# descr = make_description()
# config = Config(descr)
# config.bool = False
## gcdummy.setoption(config, True, "user")
## config.setoption("gc.dummy", True, "user")
# #config.gc.dummy = True
## config.setoption("bool", False, "user")
# config.set(dummy=False)
# assert config.gc._cfgimpl_context._cfgimpl_values.values == {'dummy': False, 'float': 2.3, 'name': 'ref'}
# ## acces to the option object
## config.gc._cfgimpl_descr.dummy.setoption(config, True, "user")
# assert config.gc.dummy == False
## config.set(dummy=True)
## assert config.gc.dummy == True
#____________________________________________________________ #____________________________________________________________
#def test_accepts_multiple_changes_from_option(): def test_accepts_multiple_changes_from_option():
# s = StrOption("string", "", default="string") s = StrOption("string", "", default="string")
# descr = OptionDescription("options", "", [s]) descr = OptionDescription("options", "", [s])
# config = Config(descr) config = Config(descr)
# config.string = "egg" config.string = "egg"
# assert s.getdefault() == "string" assert s.optimpl_getdefault() == "string"
# assert config.string == "egg" assert config.string == "egg"
# s.setoption(config, 'blah') config.string = 'blah'
# assert s.getdefault() == "string" assert s.optimpl_getdefault() == "string"
# assert config.string == "blah" assert config.string == "blah"
# s.setoption(config, 'bol') config.string = 'bol'
# assert config.string == 'bol' assert config.string == 'bol'
def test_allow_multiple_changes_from_config(): def test_allow_multiple_changes_from_config():
@ -403,8 +312,6 @@ def test_allow_multiple_changes_from_config():
assert config.string == "oh" assert config.string == "oh"
config.string = "blah" config.string = "blah"
assert config.string == "blah" assert config.string == "blah"
# config.set(string2='blah')
# assert config.bip.string2 == 'blah'
# ____________________________________________________________ # ____________________________________________________________
@ -427,6 +334,5 @@ def test_access_by_get_whith_hide():
BoolOption("b2", ""), BoolOption("b2", ""),
BoolOption("d1", "")]) BoolOption("d1", "")])
c = Config(descr) c = Config(descr)
setting = c.cfgimpl_get_settings() c.read_write()
setting.read_write()
raises(AttributeError, "c.find(byname='b1')") raises(AttributeError, "c.find(byname='b1')")

View File

@ -43,7 +43,7 @@ def test_is_hidden():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
dummy = config.unwrap_from_path('gc.dummy') dummy = config.unwrap_from_path('gc.dummy')
assert not 'frozen' in setting[dummy] assert not 'frozen' in setting[dummy]
# setattr # setattr
@ -56,7 +56,7 @@ def test_group_is_hidden():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
gc = config.unwrap_from_path('gc') gc = config.unwrap_from_path('gc')
config.unwrap_from_path('gc.dummy') config.unwrap_from_path('gc.dummy')
setting[gc].append('hidden') setting[gc].append('hidden')
@ -80,7 +80,7 @@ def test_group_is_hidden_multi():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
obj = config.unwrap_from_path('objspace') obj = config.unwrap_from_path('objspace')
objspace = config.objspace objspace = config.objspace
setting[obj].append('hidden') setting[obj].append('hidden')
@ -101,7 +101,7 @@ def test_global_show():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
dummy = config.unwrap_from_path('gc.dummy') dummy = config.unwrap_from_path('gc.dummy')
setting[dummy].append('hidden') setting[dummy].append('hidden')
assert 'hidden' in setting[dummy] assert 'hidden' in setting[dummy]

View File

@ -50,7 +50,7 @@ def test_optname_shall_not_start_with_numbers():
def test_option_has_an_api_name(): def test_option_has_an_api_name():
raises(ValueError, "BoolOption('cfgimpl_get_settings', 'dummy', default=False)") raises(ValueError, "BoolOption('cfgimpl_get_settings', 'dummy', default=False)")
raises(ValueError, "BoolOption('unwrap_from_path', 'dummy', default=False)") raises(ValueError, "BoolOption('unwrap_from_path', 'dummy', default=False)")
raises(ValueError, "BoolOption('objimpl_getdoc', 'dummy', default=False)") raises(ValueError, "BoolOption('optimpl_getdoc', 'dummy', default=False)")
raises(ValueError, "BoolOption('_unvalid', 'dummy', default=False)") raises(ValueError, "BoolOption('_unvalid', 'dummy', default=False)")
raises(ValueError, "BoolOption('6unvalid', 'dummy', default=False)") raises(ValueError, "BoolOption('6unvalid', 'dummy', default=False)")
BoolOption('unvalid6', 'dummy', default=False) BoolOption('unvalid6', 'dummy', default=False)

View File

@ -27,13 +27,13 @@ def make_description():
master = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) master = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1 = OptionDescription('interface1', '', [master]) interface1 = OptionDescription('interface1', '', [master])
interface1.objimpl_set_group_type(groups.family) interface1.optimpl_set_group_type(groups.family)
general = OptionDescription('general', '', [numero_etab, nom_machine, general = OptionDescription('general', '', [numero_etab, nom_machine,
nombre_interfaces, activer_proxy_client, nombre_interfaces, activer_proxy_client,
mode_conteneur_actif, adresse_serveur_ntp, mode_conteneur_actif, adresse_serveur_ntp,
time_zone]) time_zone])
general.objimpl_set_group_type(groups.family) general.optimpl_set_group_type(groups.family)
creole = OptionDescription('creole', 'first tiramisu configuration', [general, interface1]) creole = OptionDescription('creole', 'first tiramisu configuration', [general, interface1])
descr = OptionDescription('baseconfig', 'baseconifgdescr', [creole]) descr = OptionDescription('baseconfig', 'baseconifgdescr', [creole])
return descr return descr
@ -58,14 +58,26 @@ def test_base_config():
assert config.creole.make_dict(flatten=True) == result assert config.creole.make_dict(flatten=True) == result
def test_make_dict_filter():
descr = make_description()
config = Config(descr)
result = {'general.numero_etab': None, 'general.nombre_interfaces': 1,
'general.serveur_ntp': [], 'general.mode_conteneur_actif': False,
'general.time_zone': 'Paris', 'general.nom_machine': 'eoleng',
'general.activer_proxy_client': False}
assert config.creole.make_dict(withoption='numero_etab') == result
raises(AttributeError, "config.creole.make_dict(withoption='numero_etab', withvalue='toto')")
assert config.creole.make_dict(withoption='numero_etab', withvalue=None) == result
def test_get_group_type(): def test_get_group_type():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
grp = config.unwrap_from_path('creole.general') grp = config.unwrap_from_path('creole.general')
assert grp.objimpl_get_group_type() == groups.family assert grp.optimpl_get_group_type() == groups.family
assert grp.objimpl_get_group_type() == 'family' assert grp.optimpl_get_group_type() == 'family'
assert isinstance(grp.objimpl_get_group_type(), groups.GroupType) assert isinstance(grp.optimpl_get_group_type(), groups.GroupType)
raises(TypeError, 'grp.objimpl_set_group_type(groups.default)') raises(TypeError, 'grp.optimpl_set_group_type(groups.default)')
def test_iter_on_groups(): def test_iter_on_groups():
@ -91,31 +103,31 @@ def test_groups_with_master():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
assert interface1.objimpl_get_group_type() == groups.master assert interface1.optimpl_get_group_type() == groups.master
def test_groups_with_master_in_config(): def test_groups_with_master_in_config():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
Config(interface1) Config(interface1)
assert interface1.objimpl_get_group_type() == groups.master assert interface1.optimpl_get_group_type() == groups.master
def test_allowed_groups(): def test_allowed_groups():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ValueError, "interface1.objimpl_set_group_type('toto')") raises(ValueError, "interface1.optimpl_set_group_type('toto')")
def test_master_not_valid_name(): def test_master_not_valid_name():
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)
invalid_group = OptionDescription('interface1', '', [ip_admin_eth0, netmask_admin_eth0]) invalid_group = OptionDescription('interface1', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ValueError, "invalid_group.objimpl_set_group_type(groups.master)") raises(ValueError, "invalid_group.optimpl_set_group_type(groups.master)")
def test_sub_group_in_master_group(): def test_sub_group_in_master_group():
@ -123,14 +135,14 @@ def test_sub_group_in_master_group():
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)
subgroup = OptionDescription("subgroup", '', []) subgroup = OptionDescription("subgroup", '', [])
invalid_group = OptionDescription('ip_admin_eth0', '', [subgroup, ip_admin_eth0, netmask_admin_eth0]) invalid_group = OptionDescription('ip_admin_eth0', '', [subgroup, ip_admin_eth0, netmask_admin_eth0])
raises(ValueError, "invalid_group.objimpl_set_group_type(groups.master)") raises(ValueError, "invalid_group.optimpl_set_group_type(groups.master)")
def test_group_always_has_multis(): def test_group_always_has_multis():
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")
group = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) group = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ValueError, "group.objimpl_set_group_type(groups.master)") raises(ValueError, "group.optimpl_set_group_type(groups.master)")
#____________________________________________________________ #____________________________________________________________
@ -138,42 +150,38 @@ def test_values_with_master_and_slaves():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
maconfig = OptionDescription('toto', '', [interface1]) maconfig = OptionDescription('toto', '', [interface1])
cfg = Config(maconfig) cfg = Config(maconfig)
opt = cfg.unwrap_from_path("ip_admin_eth0.ip_admin_eth0")
opt_slave = cfg.unwrap_from_path("ip_admin_eth0.netmask_admin_eth0")
owner = cfg._cfgimpl_context._cfgimpl_settings.getowner() owner = cfg._cfgimpl_context._cfgimpl_settings.getowner()
assert interface1.objimpl_get_group_type() == groups.master assert interface1.optimpl_get_group_type() == groups.master
assert cfg.cfgimpl_get_values().getowner(opt) == owners.default assert cfg.getowner("ip_admin_eth0.ip_admin_eth0") == owners.default
assert cfg.cfgimpl_get_values().getowner(opt_slave) == owners.default assert cfg.getowner("ip_admin_eth0.netmask_admin_eth0") == owners.default
assert cfg.ip_admin_eth0.netmask_admin_eth0 == [] assert cfg.ip_admin_eth0.netmask_admin_eth0 == []
cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145") cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145")
assert cfg.ip_admin_eth0.ip_admin_eth0 == ["192.168.230.145"] assert cfg.ip_admin_eth0.ip_admin_eth0 == ["192.168.230.145"]
assert cfg.ip_admin_eth0.netmask_admin_eth0 == [None] assert cfg.ip_admin_eth0.netmask_admin_eth0 == [None]
assert cfg.cfgimpl_get_values().getowner(opt) == owner assert cfg.getowner("ip_admin_eth0.ip_admin_eth0") == owner
assert cfg.cfgimpl_get_values().getowner(opt_slave) == owners.default assert cfg.getowner("ip_admin_eth0.netmask_admin_eth0") == owners.default
def test_reset_values_with_master_and_slaves(): def test_reset_values_with_master_and_slaves():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
maconfig = OptionDescription('toto', '', [interface1]) maconfig = OptionDescription('toto', '', [interface1])
cfg = Config(maconfig) cfg = Config(maconfig)
opt = cfg.unwrap_from_path("ip_admin_eth0.ip_admin_eth0")
opt_slave = cfg.unwrap_from_path("ip_admin_eth0.netmask_admin_eth0")
owner = cfg._cfgimpl_context._cfgimpl_settings.getowner() owner = cfg._cfgimpl_context._cfgimpl_settings.getowner()
assert interface1.objimpl_get_group_type() == groups.master assert interface1.optimpl_get_group_type() == groups.master
assert cfg.cfgimpl_get_values().getowner(opt) == owners.default assert cfg.getowner("ip_admin_eth0.ip_admin_eth0") == owners.default
assert cfg.cfgimpl_get_values().getowner(opt_slave) == owners.default assert cfg.getowner("ip_admin_eth0.netmask_admin_eth0") == owners.default
cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145") cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145")
assert cfg.cfgimpl_get_values().getowner(opt) == owner assert cfg.getowner("ip_admin_eth0.ip_admin_eth0") == owner
assert cfg.cfgimpl_get_values().getowner(opt_slave) == owners.default assert cfg.getowner("ip_admin_eth0.netmask_admin_eth0") == owners.default
del(cfg.ip_admin_eth0.ip_admin_eth0) del(cfg.ip_admin_eth0.ip_admin_eth0)
assert cfg.cfgimpl_get_values().getowner(opt) == owners.default assert cfg.getowner("ip_admin_eth0.ip_admin_eth0") == owners.default
assert cfg.cfgimpl_get_values().getowner(opt_slave) == owners.default assert cfg.getowner("ip_admin_eth0.netmask_admin_eth0") == owners.default
assert cfg.ip_admin_eth0.ip_admin_eth0 == [] assert cfg.ip_admin_eth0.ip_admin_eth0 == []
assert cfg.ip_admin_eth0.netmask_admin_eth0 == [] assert cfg.ip_admin_eth0.netmask_admin_eth0 == []
@ -182,7 +190,7 @@ def test_values_with_master_and_slaves_slave():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
maconfig = OptionDescription('toto', '', [interface1]) maconfig = OptionDescription('toto', '', [interface1])
cfg = Config(maconfig) cfg = Config(maconfig)
assert cfg.ip_admin_eth0.netmask_admin_eth0 == [] assert cfg.ip_admin_eth0.netmask_admin_eth0 == []
@ -204,7 +212,7 @@ def test_values_with_master_and_slaves_master():
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 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1.objimpl_set_group_type(groups.master) interface1.optimpl_set_group_type(groups.master)
maconfig = OptionDescription('toto', '', [interface1]) maconfig = OptionDescription('toto', '', [interface1])
cfg = Config(maconfig) cfg = Config(maconfig)
cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145") cfg.ip_admin_eth0.ip_admin_eth0.append("192.168.230.145")

View File

@ -14,7 +14,7 @@ def test_permissive():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
props = [] props = []
try: try:
config.u1 config.u1
@ -43,7 +43,7 @@ def test_permissive_mandatory():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_only() config.read_only()
props = [] props = []
try: try:
config.u1 config.u1
@ -65,7 +65,7 @@ def test_permissive_frozen():
descr = make_description() descr = make_description()
config = Config(descr) config = Config(descr)
setting = config.cfgimpl_get_settings() setting = config.cfgimpl_get_settings()
setting.read_write() config.read_write()
setting.set_permissive(('frozen', 'disabled',)) setting.set_permissive(('frozen', 'disabled',))
try: try:
config.u1 = 1 config.u1 = 1

View File

@ -51,7 +51,7 @@ def carry_out_calculation(name, config, callback, callback_params):
if check_disabled: if check_disabled:
continue continue
raise PropertiesOptionError(err, err.proptype) raise PropertiesOptionError(err, err.proptype)
is_multi = opt.is_multi() is_multi = opt.optimpl_is_multi()
if is_multi: if is_multi:
if opt_value is not None: if opt_value is not None:
len_value = len(opt_value) len_value = len(opt_value)

View File

@ -62,6 +62,9 @@ class SubConfig(object):
def cfgimpl_get_description(self): def cfgimpl_get_description(self):
return self._cfgimpl_descr return self._cfgimpl_descr
def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
# ____________________________________________________________ # ____________________________________________________________
# attribute methods # attribute methods
def __setattr__(self, name, value): def __setattr__(self, name, value):
@ -72,19 +75,18 @@ class SubConfig(object):
return return
self._setattr(name, value) self._setattr(name, value)
def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
def _setattr(self, name, value, force_permissive=False): def _setattr(self, name, value, force_permissive=False):
if '.' in name: if '.' in name:
homeconfig, name = self.cfgimpl_get_home_by_path(name) homeconfig, name = self.cfgimpl_get_home_by_path(name)
return homeconfig.__setattr__(name, value) return homeconfig.__setattr__(name, value)
child = getattr(self._cfgimpl_descr, name) child = getattr(self._cfgimpl_descr, name)
if type(child) != SymLinkOption: if not isinstance(child, SymLinkOption):
self.cfgimpl_get_values().setitem(child, value, self.cfgimpl_get_values().setitem(child, value,
force_permissive=force_permissive) force_permissive=force_permissive)
else: else:
child._setoption(self.cfgimpl_get_context(), value) context = self.cfgimpl_get_context()
path = context.cfgimpl_get_description().optimpl_get_path_by_opt(child._opt)
context._setattr(path, value, force_permissive=force_permissive)
def __delattr__(self, name): def __delattr__(self, name):
child = getattr(self._cfgimpl_descr, name) child = getattr(self._cfgimpl_descr, name)
@ -117,11 +119,11 @@ class SubConfig(object):
opt_or_descr = getattr(self.cfgimpl_get_description(), name) opt_or_descr = getattr(self.cfgimpl_get_description(), name)
# symlink options # symlink options
if isinstance(opt_or_descr, SymLinkOption): if isinstance(opt_or_descr, SymLinkOption):
rootconfig = self.cfgimpl_get_context() context = self.cfgimpl_get_context()
path = rootconfig.cfgimpl_get_description().objimpl_get_path_by_opt(opt_or_descr.opt) path = context.cfgimpl_get_description().optimpl_get_path_by_opt(opt_or_descr._opt)
return rootconfig._getattr(path, validate=validate, return context._getattr(path, validate=validate,
force_properties=force_properties, force_properties=force_properties,
force_permissive=force_permissive) force_permissive=force_permissive)
elif isinstance(opt_or_descr, OptionDescription): elif isinstance(opt_or_descr, OptionDescription):
self.cfgimpl_get_settings().validate_properties(opt_or_descr, self.cfgimpl_get_settings().validate_properties(opt_or_descr,
True, False, True, False,
@ -144,14 +146,14 @@ class SubConfig(object):
return self, path[-1] return self, path[-1]
def __hash__(self): def __hash__(self):
return hash(self.cfgimpl_get_description().objimpl_getkey(self)) return hash(self.cfgimpl_get_description().optimpl_getkey(self))
def __eq__(self, other): def __eq__(self, other):
"Config comparison" "Config comparison"
if not isinstance(other, Config): if not isinstance(other, Config):
return False return False
return self.cfgimpl_get_description().objimpl_getkey(self) == \ return self.cfgimpl_get_description().optimpl_getkey(self) == \
other.cfgimpl_get_description().objimpl_getkey(other) other.cfgimpl_get_description().optimpl_getkey(other)
def __ne__(self, other): def __ne__(self, other):
"Config comparison" "Config comparison"
@ -163,7 +165,7 @@ class SubConfig(object):
def __iter__(self): def __iter__(self):
"""Pythonesque way of parsing group's ordered options. """Pythonesque way of parsing group's ordered options.
iteration only on Options (not OptionDescriptions)""" iteration only on Options (not OptionDescriptions)"""
for child in self.cfgimpl_get_description().objimpl_getchildren(): for child in self.cfgimpl_get_description().optimpl_getchildren():
if not isinstance(child, OptionDescription): if not isinstance(child, OptionDescription):
try: try:
yield child._name, getattr(self, child._name) yield child._name, getattr(self, child._name)
@ -175,7 +177,7 @@ class SubConfig(object):
def iter_all(self): def iter_all(self):
"""A way of parsing options **and** groups. """A way of parsing options **and** groups.
iteration on Options and OptionDescriptions.""" iteration on Options and OptionDescriptions."""
for child in self.cfgimpl_get_description().objimpl_getchildren(): for child in self.cfgimpl_get_description().optimpl_getchildren():
try: try:
yield child._name, getattr(self, child._name) yield child._name, getattr(self, child._name)
except GeneratorExit: except GeneratorExit:
@ -196,11 +198,11 @@ class SubConfig(object):
if group_type is not None: if group_type is not None:
if not isinstance(group_type, groups.GroupType): if not isinstance(group_type, groups.GroupType):
raise TypeError(_("unknown group_type: {0}").format(group_type)) raise TypeError(_("unknown group_type: {0}").format(group_type))
for child in self.cfgimpl_get_description().objimpl_getchildren(): for child in self.cfgimpl_get_description().optimpl_getchildren():
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
try: try:
if group_type is None or (group_type is not None and if group_type is None or (group_type is not None and
child.objimpl_get_group_type() == group_type): child.optimpl_get_group_type() == group_type):
yield child._name, getattr(self, child._name) yield child._name, getattr(self, child._name)
except GeneratorExit: except GeneratorExit:
raise StopIteration raise StopIteration
@ -225,7 +227,7 @@ class SubConfig(object):
def cfgimpl_get_path(self): def cfgimpl_get_path(self):
descr = self.cfgimpl_get_description() descr = self.cfgimpl_get_description()
context_descr = self.cfgimpl_get_context().cfgimpl_get_description() context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
return context_descr.objimpl_get_path_by_opt(descr) return context_descr.optimpl_get_path_by_opt(descr)
def find(self, bytype=None, byname=None, byvalue=None, type_='option'): def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
""" """
@ -272,7 +274,7 @@ class SubConfig(object):
type_='path', type_='path',
_subpath=mypath): _subpath=mypath):
path = '.'.join(path.split('.')[:-1]) path = '.'.join(path.split('.')[:-1])
opt = self.cfgimpl_get_context().cfgimpl_get_description().objimpl_get_opt_by_path(path) opt = self.cfgimpl_get_context().cfgimpl_get_description().optimpl_get_opt_by_path(path)
if mypath is not None: if mypath is not None:
if mypath == path: if mypath == path:
withoption = None withoption = None
@ -287,7 +289,7 @@ class SubConfig(object):
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten) self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
#withoption can be set to None below ! #withoption can be set to None below !
if withoption is None: if withoption is None:
for opt in self.cfgimpl_get_description().objimpl_getchildren(): for opt in self.cfgimpl_get_description().optimpl_getchildren():
path = opt._name path = opt._name
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten) self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
if _currpath == []: if _currpath == []:
@ -330,7 +332,17 @@ class Config(SubConfig):
self._cfgimpl_build_all_paths() self._cfgimpl_build_all_paths()
def _cfgimpl_build_all_paths(self): def _cfgimpl_build_all_paths(self):
self._cfgimpl_descr.objimpl_build_cache() self._cfgimpl_descr.optimpl_build_cache()
def read_only(self):
self.cfgimpl_get_settings().read_only()
def read_write(self):
self.cfgimpl_get_settings().read_write()
def getowner(self, path):
opt = self.cfgimpl_get_description().optimpl_get_opt_by_path(path)
return self.cfgimpl_get_values().getowner(opt)
def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')): def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
if 'values' in only: if 'values' in only:
@ -446,7 +458,7 @@ def mandatory_warnings(config):
""" """
#if value in cache, properties are not calculated #if value in cache, properties are not calculated
config.cfgimpl_reset_cache(only=('values',)) config.cfgimpl_reset_cache(only=('values',))
for path in config.cfgimpl_get_description().objimpl_getpaths(include_groups=True): for path in config.cfgimpl_get_description().optimpl_getpaths(include_groups=True):
try: try:
config._getattr(path, force_properties=('mandatory',)) config._getattr(path, force_properties=('mandatory',))
except PropertiesOptionError, err: except PropertiesOptionError, err:

View File

@ -22,9 +22,8 @@
#ValueError if function's parameter not correct #ValueError if function's parameter not correct
# or if not logical # or if not logical
# or if validation falied # or if validation failled
# or multi must be a list # or multi must be a list
# or error with multi length
#TypeError if parameter has no good type #TypeError if parameter has no good type
#AttributeError if no option or optiondescription in optiondescription (also when specified a path) #AttributeError if no option or optiondescription in optiondescription (also when specified a path)
@ -44,7 +43,7 @@ class ConfigError(StandardError):
pass pass
class ConflictConfigError(ConfigError): class ConflictError(StandardError):
"duplicate config" "duplicate config"
pass pass

View File

@ -25,13 +25,14 @@ from copy import copy
from types import FunctionType from types import FunctionType
from IPy import IP from IPy import IP
from tiramisu.error import ConflictConfigError from tiramisu.error import ConflictError
from tiramisu.setting import groups, multitypes from tiramisu.setting import groups, multitypes
from tiramisu.i18n import _ from tiramisu.i18n import _
name_regexp = re.compile(r'^\d+') name_regexp = re.compile(r'^\d+')
forbidden_names = ['iter_all', 'iter_group', 'find', 'find_fisrt', forbidden_names = ['iter_all', 'iter_group', 'find', 'find_fisrt',
'make_dict', 'unwrap_from_path'] 'make_dict', 'unwrap_from_path', 'read_only',
'read_write', 'getowner']
def valid_name(name): def valid_name(name):
@ -41,7 +42,7 @@ def valid_name(name):
return False return False
if re.match(name_regexp, name) is None and not name.startswith('_') \ if re.match(name_regexp, name) is None and not name.startswith('_') \
and name not in forbidden_names \ and name not in forbidden_names \
and not name.startswith('objimpl_') and \ and not name.startswith('optimpl_') and \
not name.startswith('cfgimpl_'): not name.startswith('cfgimpl_'):
return True return True
else: else:
@ -53,7 +54,7 @@ def valid_name(name):
class BaseInformation(object): class BaseInformation(object):
__slots__ = ('_informations') __slots__ = ('_informations')
def objimpl_set_information(self, key, value): def optimpl_set_information(self, key, value):
"""updates the information's attribute """updates the information's attribute
(wich is a dictionnary) (wich is a dictionnary)
@ -62,7 +63,7 @@ class BaseInformation(object):
""" """
self._informations[key] = value self._informations[key] = value
def objimpl_get_information(self, key, default=None): def optimpl_get_information(self, key, default=None):
"""retrieves one information's item """retrieves one information's item
:param key: the item string (ex: "help") :param key: the item string (ex: "help")
@ -111,7 +112,7 @@ class Option(BaseInformation):
raise ValueError(_("invalid name: {0} for option").format(name)) raise ValueError(_("invalid name: {0} for option").format(name))
self._name = name self._name = name
self._informations = {} self._informations = {}
self.objimpl_set_information('doc', doc) self.optimpl_set_information('doc', doc)
validate_requires_arg(requires, self._name) validate_requires_arg(requires, self._name)
self._requires = requires self._requires = requires
self._multi = multi self._multi = multi
@ -152,14 +153,14 @@ class Option(BaseInformation):
# raise ValidateError("invalid default value {0} " # raise ValidateError("invalid default value {0} "
# "for option {1} : not list type" # "for option {1} : not list type"
# "".format(str(default), name)) # "".format(str(default), name))
if not self.objimpl_validate(default): if not self.optimpl_validate(default):
raise ValueError(_("invalid default value {0} " raise ValueError(_("invalid default value {0} "
"for option {1}" "for option {1}"
"").format(str(default), name)) "").format(str(default), name))
self._multitype = multitypes.default self._multitype = multitypes.default
self._default_multi = default_multi self._default_multi = default_multi
else: else:
if default is not None and not self.objimpl_validate(default): if default is not None and not self.optimpl_validate(default):
raise ValueError(_("invalid default value {0} " raise ValueError(_("invalid default value {0} "
"for option {1}").format(str(default), name)) "for option {1}").format(str(default), name))
self._default = default self._default = default
@ -170,7 +171,7 @@ class Option(BaseInformation):
' must be a tuple').format(type(properties), self._name)) ' must be a tuple').format(type(properties), self._name))
self._properties = properties # 'hidden', 'disabled'... self._properties = properties # 'hidden', 'disabled'...
def objimpl_validate(self, value, context=None, validate=True): def optimpl_validate(self, value, context=None, validate=True):
""" """
:param value: the option's value :param value: the option's value
:param validate: if true enables ``self._validator`` validation :param validate: if true enables ``self._validator`` validation
@ -210,48 +211,48 @@ class Option(BaseInformation):
return False return False
return True return True
def objimpl_getdefault(self, default_multi=False): def optimpl_getdefault(self, default_multi=False):
"accessing the default value" "accessing the default value"
if not default_multi or not self.objimpl_is_multi(): if not default_multi or not self.optimpl_is_multi():
return self._default return self._default
else: else:
return self.getdefault_multi() return self.getdefault_multi()
def objimpl_getdefault_multi(self): def optimpl_getdefault_multi(self):
"accessing the default value for a multi" "accessing the default value for a multi"
return self._default_multi return self._default_multi
def objimpl_get_multitype(self): def optimpl_get_multitype(self):
return self._multitype return self._multitype
def objimpl_get_master_slaves(self): def optimpl_get_master_slaves(self):
return self._master_slaves return self._master_slaves
def objimpl_is_empty_by_default(self): def optimpl_is_empty_by_default(self):
"no default value has been set yet" "no default value has been set yet"
if ((not self.objimpl_is_multi() and self._default is None) or if ((not self.optimpl_is_multi() and self._default is None) or
(self.objimpl_is_multi() and (self._default == [] or None in self._default))): (self.optimpl_is_multi() and (self._default == [] or None in self._default))):
return True return True
return False return False
def objimpl_getdoc(self): def optimpl_getdoc(self):
"accesses the Option's doc" "accesses the Option's doc"
return self.objimpl_get_information('doc') return self.optimpl_get_information('doc')
def objimpl_has_callback(self): def optimpl_has_callback(self):
"to know if a callback has been defined or not" "to know if a callback has been defined or not"
if self._callback is None: if self._callback is None:
return False return False
else: else:
return True return True
def objimpl_getkey(self, value): def optimpl_getkey(self, value):
return value return value
def objimpl_is_multi(self): def optimpl_is_multi(self):
return self._multi return self._multi
def objimpl_add_consistency(self, func, opts): def optimpl_add_consistency(self, func, opts):
pass pass
if self._consistencies is None: if self._consistencies is None:
self._consistencies = [] self._consistencies = []
@ -266,7 +267,7 @@ class Option(BaseInformation):
descr = context.cfgimpl_get_description() descr = context.cfgimpl_get_description()
for opt_ in opts: for opt_ in opts:
if opt_ is not opt: if opt_ is not opt:
path = descr.objimpl_get_path_by_opt(opt_) path = descr.optimpl_get_path_by_opt(opt_)
val = context._getattr(path, validate=False) val = context._getattr(path, validate=False)
if val is not None: if val is not None:
if val in values: if val in values:
@ -364,12 +365,8 @@ class SymLinkOption(object):
self._name = name self._name = name
self._opt = opt self._opt = opt
def _setoption(self, context, value):
path = context.cfgimpl_get_description().objimpl_get_path_by_opt(self._opt)
setattr(context, path, value)
def __getattr__(self, name): def __getattr__(self, name):
if name in ('_name', '_opt', '_setoption', '_consistencies'): if name in ('_name', '_opt', '_consistencies'):
return object.__gettattr__(self, name) return object.__gettattr__(self, name)
else: else:
return getattr(self._opt, name) return getattr(self._opt, name)
@ -379,17 +376,25 @@ class IPOption(Option):
__slots__ = ('_opt_type', '_only_private') __slots__ = ('_opt_type', '_only_private')
_opt_type = 'ip' _opt_type = 'ip'
def objimpl_set_private(self): def __init__(self, name, doc, default=None, default_multi=None,
self._only_private = True requires=None, multi=False, callback=None,
callback_params=None, validator=None, validator_args=None,
properties=None, only_private=False):
super(IPOption, self).__init__(name, doc, default=default,
default_multi=default_multi,
callback=callback,
callback_params=callback_params,
requires=requires,
multi=multi,
validator=validator,
validator_args=validator_args,
properties=properties)
self._only_private = only_private
def _validate(self, value): def _validate(self, value):
try:
only_private = self._only_private
except AttributeError:
only_private = False
try: try:
ip = IP('{0}/32'.format(value)) ip = IP('{0}/32'.format(value))
if only_private: if self._only_private:
return ip.iptype() == 'PRIVATE' return ip.iptype() == 'PRIVATE'
return True return True
except ValueError: except ValueError:
@ -457,17 +462,17 @@ class NetmaskOption(Option):
descr = context.cfgimpl_get_description() descr = context.cfgimpl_get_description()
if opt is opt_ipnetwork: if opt is opt_ipnetwork:
val_ipnetwork = value val_ipnetwork = value
path = descr.objimpl_get_path_by_opt(opt_netmask) path = descr.optimpl_get_path_by_opt(opt_netmask)
val_netmask = context._getattr(path, validate=False) val_netmask = context._getattr(path, validate=False)
if opt_netmask.objimpl_is_multi(): if opt_netmask.optimpl_is_multi():
val_netmask = val_netmask[index] val_netmask = val_netmask[index]
if val_netmask is None: if val_netmask is None:
return True return True
else: else:
val_netmask = value val_netmask = value
path = descr.objimpl_get_path_by_opt(opt_ipnetwork) path = descr.optimpl_get_path_by_opt(opt_ipnetwork)
val_ipnetwork = getattr(context, path) val_ipnetwork = getattr(context, path)
if opt_ipnetwork.objimpl_is_multi(): if opt_ipnetwork.optimpl_is_multi():
val_ipnetwork = val_ipnetwork[index] val_ipnetwork = val_ipnetwork[index]
if val_ipnetwork is None: if val_ipnetwork is None:
return True return True
@ -540,7 +545,7 @@ class OptionDescription(BaseInformation):
raise ValueError(_("invalid name: {0} for option descr").format(name)) raise ValueError(_("invalid name: {0} for option descr").format(name))
self._name = name self._name = name
self._informations = {} self._informations = {}
self.objimpl_set_information('doc', doc) self.optimpl_set_information('doc', doc)
child_names = [child._name for child in children] child_names = [child._name for child in children]
#better performance like this #better performance like this
valid_child = copy(child_names) valid_child = copy(child_names)
@ -548,8 +553,8 @@ class OptionDescription(BaseInformation):
old = None old = None
for child in valid_child: for child in valid_child:
if child == old: if child == old:
raise ConflictConfigError(_('duplicate option name: ' raise ConflictError(_('duplicate option name: '
'{0}').format(child)) '{0}').format(child))
old = child old = child
self._children = (tuple(child_names), tuple(children)) self._children = (tuple(child_names), tuple(children))
validate_requires_arg(requires, self._name) validate_requires_arg(requires, self._name)
@ -563,8 +568,8 @@ class OptionDescription(BaseInformation):
# the group_type is useful for filtering OptionDescriptions in a config # the group_type is useful for filtering OptionDescriptions in a config
self._group_type = groups.default self._group_type = groups.default
def objimpl_getdoc(self): def optimpl_getdoc(self):
return self.objimpl_get_information('doc') return self.optimpl_get_information('doc')
def __getattr__(self, name): def __getattr__(self, name):
try: try:
@ -573,32 +578,32 @@ class OptionDescription(BaseInformation):
raise AttributeError(_('unknown Option {} in OptionDescription {}' raise AttributeError(_('unknown Option {} in OptionDescription {}'
'').format(name, self._name)) '').format(name, self._name))
def objimpl_getkey(self, config): def optimpl_getkey(self, config):
return tuple([child.objimpl_getkey(getattr(config, child._name)) return tuple([child.optimpl_getkey(getattr(config, child._name))
for child in self.objimpl_getchildren()]) for child in self.optimpl_getchildren()])
def objimpl_getpaths(self, include_groups=False, _currpath=None): def optimpl_getpaths(self, include_groups=False, _currpath=None):
"""returns a list of all paths in self, recursively """returns a list of all paths in self, recursively
_currpath should not be provided (helps with recursion) _currpath should not be provided (helps with recursion)
""" """
if _currpath is None: if _currpath is None:
_currpath = [] _currpath = []
paths = [] paths = []
for option in self.objimpl_getchildren(): for option in self.optimpl_getchildren():
attr = option._name attr = option._name
if isinstance(option, OptionDescription): if isinstance(option, OptionDescription):
if include_groups: if include_groups:
paths.append('.'.join(_currpath + [attr])) paths.append('.'.join(_currpath + [attr]))
paths += option.objimpl_getpaths(include_groups=include_groups, paths += option.optimpl_getpaths(include_groups=include_groups,
_currpath=_currpath + [attr]) _currpath=_currpath + [attr])
else: else:
paths.append('.'.join(_currpath + [attr])) paths.append('.'.join(_currpath + [attr]))
return paths return paths
def objimpl_getchildren(self): def optimpl_getchildren(self):
return self._children[1] return self._children[1]
def objimpl_build_cache(self, cache_path=None, cache_option=None, _currpath=None, _consistencies=None): def optimpl_build_cache(self, cache_path=None, cache_option=None, _currpath=None, _consistencies=None):
if _currpath is None and self._cache_paths is not None: if _currpath is None and self._cache_paths is not None:
return return
if _currpath is None: if _currpath is None:
@ -610,7 +615,7 @@ class OptionDescription(BaseInformation):
if cache_path is None: if cache_path is None:
cache_path = [self._name] cache_path = [self._name]
cache_option = [self] cache_option = [self]
for option in self.objimpl_getchildren(): for option in self.optimpl_getchildren():
attr = option._name attr = option._name
if attr.startswith('_cfgimpl'): if attr.startswith('_cfgimpl'):
continue continue
@ -624,7 +629,7 @@ class OptionDescription(BaseInformation):
_consistencies.setdefault(opt, []).append((func, opts)) _consistencies.setdefault(opt, []).append((func, opts))
else: else:
_currpath.append(attr) _currpath.append(attr)
option.objimpl_build_cache(cache_path, cache_option, _currpath, _consistencies) option.optimpl_build_cache(cache_path, cache_option, _currpath, _consistencies)
_currpath.pop() _currpath.pop()
if save: if save:
#valid no duplicated option #valid no duplicated option
@ -633,26 +638,26 @@ class OptionDescription(BaseInformation):
old = None old = None
for child in valid_child: for child in valid_child:
if child == old: if child == old:
raise ConflictConfigError(_('duplicate option: ' raise ConflictError(_('duplicate option: '
'{0}').format(child)) '{0}').format(child))
old = child old = child
self._cache_paths = (tuple(cache_option), tuple(cache_path)) self._cache_paths = (tuple(cache_option), tuple(cache_path))
self._consistencies = _consistencies self._consistencies = _consistencies
def obgimpl_get_opt_by_path(self, path): def optimpl_get_opt_by_path(self, path):
try: try:
return self._cache_paths[0][self._cache_paths[1].index(path)] return self._cache_paths[0][self._cache_paths[1].index(path)]
except ValueError: except ValueError:
raise AttributeError(_('no option for path {}').format(path)) raise AttributeError(_('no option for path {}').format(path))
def objimpl_get_path_by_opt(self, opt): def optimpl_get_path_by_opt(self, opt):
try: try:
return self._cache_paths[1][self._cache_paths[0].index(opt)] return self._cache_paths[1][self._cache_paths[0].index(opt)]
except ValueError: except ValueError:
raise AttributeError(_('no option {} found').format(opt)) raise AttributeError(_('no option {} found').format(opt))
# ____________________________________________________________ # ____________________________________________________________
def objimpl_set_group_type(self, group_type): def optimpl_set_group_type(self, group_type):
"""sets a given group object to an OptionDescription """sets a given group object to an OptionDescription
:param group_type: an instance of `GroupType` or `MasterGroupType` :param group_type: an instance of `GroupType` or `MasterGroupType`
@ -669,11 +674,11 @@ class OptionDescription(BaseInformation):
#for collect all slaves #for collect all slaves
slaves = [] slaves = []
master = None master = None
for child in self.objimpl_getchildren(): for child in self.optimpl_getchildren():
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
raise ValueError(_("master group {} shall not have " raise ValueError(_("master group {} shall not have "
"a subgroup").format(self._name)) "a subgroup").format(self._name))
if not child.objimpl_is_multi(): if not child.optimpl_is_multi():
raise ValueError(_("not allowed option {0} in group {1}" raise ValueError(_("not allowed option {0} in group {1}"
": this option is not a multi" ": this option is not a multi"
"").format(child._name, self._name)) "").format(child._name, self._name))
@ -687,7 +692,7 @@ class OptionDescription(BaseInformation):
raise ValueError(_('master group with wrong master name for {}' raise ValueError(_('master group with wrong master name for {}'
'').format(self._name)) '').format(self._name))
master._master_slaves = tuple(slaves) master._master_slaves = tuple(slaves)
for child in self.objimpl_getchildren(): for child in self.optimpl_getchildren():
if child != master: if child != master:
child._master_slaves = master child._master_slaves = master
child._multitype = multitypes.slave child._multitype = multitypes.slave
@ -697,7 +702,7 @@ class OptionDescription(BaseInformation):
else: else:
raise ValueError(_('not allowed group_type : {0}').format(group_type)) raise ValueError(_('not allowed group_type : {0}').format(group_type))
def objimpl_get_group_type(self): def optimpl_get_group_type(self):
return self._group_type return self._group_type
def _valid_consistency(self, opt, value, context, index): def _valid_consistency(self, opt, value, context, index):

View File

@ -166,6 +166,9 @@ class Property(object):
def __contains__(self, propname): def __contains__(self, propname):
return propname in self._properties return propname in self._properties
def __repr__(self):
return str(self._properties)
#____________________________________________________________ #____________________________________________________________
class Setting(object): class Setting(object):
@ -188,6 +191,9 @@ class Setting(object):
def __contains__(self, propname): def __contains__(self, propname):
return propname in self._get_properties() return propname in self._get_properties()
def __repr__(self):
return str(self._get_properties())
def __getitem__(self, opt): def __getitem__(self, opt):
return Property(self, self._get_properties(opt), opt) return Property(self, self._get_properties(opt), opt)
@ -281,8 +287,8 @@ class Setting(object):
properties.append('mandatory') properties.append('mandatory')
if self._validate_frozen(opt_or_descr, value, is_write): if self._validate_frozen(opt_or_descr, value, is_write):
properties.append('frozen') properties.append('frozen')
raise_text = _('cannot change the value to {0} for ' raise_text = _('cannot change the value for '
'option {1} this option is frozen') 'option {0} this option is frozen')
if properties != []: if properties != []:
raise PropertiesOptionError(raise_text.format(opt_or_descr._name, raise PropertiesOptionError(raise_text.format(opt_or_descr._name,
str(properties)), str(properties)),
@ -353,7 +359,7 @@ def apply_requires(opt, config):
settings = config.cfgimpl_get_settings() settings = config.cfgimpl_get_settings()
setting = Property(settings, settings._get_properties(opt, False), opt) setting = Property(settings, settings._get_properties(opt, False), opt)
trigger_actions = build_actions(opt._requires) trigger_actions = build_actions(opt._requires)
optpath = config.cfgimpl_get_context().cfgimpl_get_description().objimpl_get_path_by_opt(opt) optpath = config.cfgimpl_get_context().cfgimpl_get_description().optimpl_get_path_by_opt(opt)
for requires in trigger_actions.values(): for requires in trigger_actions.values():
matches = False matches = False
for require in requires: for require in requires:

View File

@ -43,8 +43,8 @@ class Values(object):
"return value or default value if not set" "return value or default value if not set"
#if no value #if no value
if opt not in self._values: if opt not in self._values:
value = opt.objimpl_getdefault() value = opt.optimpl_getdefault()
if opt.objimpl_is_multi(): if opt.optimpl_is_multi():
value = Multi(value, self.context, opt) value = Multi(value, self.context, opt)
else: else:
#if value #if value
@ -62,11 +62,11 @@ class Values(object):
def _is_empty(self, opt, value): def _is_empty(self, opt, value):
"convenience method to know if an option is empty" "convenience method to know if an option is empty"
empty = opt._empty empty = opt._empty
if (not opt.objimpl_is_multi() and (value is None or value == empty)) or \ if (not opt.optimpl_is_multi() and (value is None or value == empty)) or \
(opt.objimpl_is_multi() and (value == [] or (opt.optimpl_is_multi() and (value == [] or
None in value or empty in value)): None in value or empty in value)):
return True return True
if self.is_default_owner(opt) and opt.objimpl_is_empty_by_default(): if self.is_default_owner(opt) and opt.optimpl_is_empty_by_default():
return True return True
return False return False
@ -97,7 +97,7 @@ class Values(object):
setting = self.context.cfgimpl_get_settings() setting = self.context.cfgimpl_get_settings()
value = self._get_value(opt) value = self._get_value(opt)
is_frozen = 'frozen' in setting[opt] is_frozen = 'frozen' in setting[opt]
if opt.objimpl_has_callback(): if opt.optimpl_has_callback():
#if value is set and : #if value is set and :
# - not frozen # - not frozen
# - frozen and not force_default_on_freeze # - frozen and not force_default_on_freeze
@ -107,16 +107,16 @@ class Values(object):
pass pass
else: else:
value = self._getcallback_value(opt) value = self._getcallback_value(opt)
if opt.objimpl_is_multi(): if opt.optimpl_is_multi():
value = Multi(value, self.context, opt) value = Multi(value, self.context, opt)
#suppress value if already set #suppress value if already set
self._reset(opt) self._reset(opt)
# frozen and force default # frozen and force default
elif is_frozen and 'force_default_on_freeze' in setting[opt]: elif is_frozen and 'force_default_on_freeze' in setting[opt]:
value = opt.objimpl_getdefault() value = opt.optimpl_getdefault()
if opt.objimpl_is_multi(): if opt.optimpl_is_multi():
value = Multi(value, self.context, opt) value = Multi(value, self.context, opt)
if validate and not opt.objimpl_validate(value, self.context, 'validator' in setting): if validate and not opt.optimpl_validate(value, self.context, 'validator' in setting):
raise ValueError(_('invalid calculated value returned' raise ValueError(_('invalid calculated value returned'
' for option {0}: {1}').format(opt._name, value)) ' for option {0}: {1}').format(opt._name, value))
if self.is_default_owner(opt) and \ if self.is_default_owner(opt) and \
@ -135,11 +135,11 @@ class Values(object):
def _setitem(self, opt, value, force_permissive=False, force_properties=None): def _setitem(self, opt, value, force_permissive=False, force_properties=None):
#valid opt #valid opt
if not opt.objimpl_validate(value, self.context, if not opt.optimpl_validate(value, self.context,
'validator' in self.context.cfgimpl_get_settings()): 'validator' in self.context.cfgimpl_get_settings()):
raise ValueError(_('invalid value {}' raise ValueError(_('invalid value {}'
' for option {}').format(value, opt._name)) ' for option {}').format(value, opt._name))
if opt.objimpl_is_multi() and not isinstance(value, Multi): if opt.optimpl_is_multi() and not isinstance(value, Multi):
value = Multi(value, self.context, opt) value = Multi(value, self.context, opt)
self._setvalue(opt, value, force_permissive=force_permissive, self._setvalue(opt, value, force_permissive=force_permissive,
force_properties=force_properties) force_properties=force_properties)
@ -208,16 +208,16 @@ class Multi(list):
self.context = context self.context = context
if not isinstance(value, list): if not isinstance(value, list):
value = [value] value = [value]
if self.opt.objimpl_get_multitype() == multitypes.slave: if self.opt.optimpl_get_multitype() == multitypes.slave:
value = self._valid_slave(value) value = self._valid_slave(value)
elif self.opt.objimpl_get_multitype() == multitypes.master: elif self.opt.optimpl_get_multitype() == multitypes.master:
self._valid_master(value) self._valid_master(value)
super(Multi, self).__init__(value) super(Multi, self).__init__(value)
def _valid_slave(self, value): def _valid_slave(self, value):
#if slave, had values until master's one #if slave, had values until master's one
masterp = self.context.cfgimpl_get_description().objimpl_get_path_by_opt( masterp = self.context.cfgimpl_get_description().optimpl_get_path_by_opt(
self.opt.objimpl_get_master_slaves()) self.opt.optimpl_get_master_slaves())
mastervalue = getattr(self.context, masterp) mastervalue = getattr(self.context, masterp)
masterlen = len(mastervalue) masterlen = len(mastervalue)
if len(value) > masterlen or (len(value) < masterlen and if len(value) > masterlen or (len(value) < masterlen and
@ -227,7 +227,7 @@ class Multi(list):
self.opt._name, masterp)) self.opt._name, masterp))
elif len(value) < masterlen: elif len(value) < masterlen:
for num in range(0, masterlen - len(value)): for num in range(0, masterlen - len(value)):
value.append(self.opt.objimpl_getdefault_multi()) value.append(self.opt.optimpl_getdefault_multi())
#else: same len so do nothing #else: same len so do nothing
return value return value
@ -244,7 +244,7 @@ class Multi(list):
self.opt._name, slave._name)) self.opt._name, slave._name))
elif len(value_slave) < masterlen: elif len(value_slave) < masterlen:
for num in range(0, masterlen - len(value_slave)): for num in range(0, masterlen - len(value_slave)):
value_slave.append(slave.objimpl_getdefault_multi(), force=True) value_slave.append(slave.optimpl_getdefault_multi(), force=True)
def __setitem__(self, key, value): def __setitem__(self, key, value):
self._validate(value) self._validate(value)
@ -257,14 +257,14 @@ class Multi(list):
only if the option is a master only if the option is a master
""" """
if not force: if not force:
if self.opt.objimpl_get_multitype() == multitypes.slave: if self.opt.optimpl_get_multitype() == multitypes.slave:
raise SlaveError(_("cannot append a value on a multi option {0}" raise SlaveError(_("cannot append a value on a multi option {0}"
" which is a slave").format(self.opt._name)) " which is a slave").format(self.opt._name))
elif self.opt.objimpl_get_multitype() == multitypes.master: elif self.opt.optimpl_get_multitype() == multitypes.master:
for slave in self.opt.objimpl_get_master_slaves(): for slave in self.opt.optimpl_get_master_slaves():
values = self.context.cfgimpl_get_values() values = self.context.cfgimpl_get_values()
if not values.is_default_owner(slave): if not values.is_default_owner(slave):
values[slave].append(slave.objimpl_getdefault_multi(), values[slave].append(slave.optimpl_getdefault_multi(),
force=True) force=True)
self._validate(value) self._validate(value)
#assume not checking mandatory property #assume not checking mandatory property
@ -285,11 +285,11 @@ class Multi(list):
:return: the requested element :return: the requested element
""" """
if not force: if not force:
if self.opt.objimpl_get_multitype() == multitypes.slave: if self.opt.optimpl_get_multitype() == multitypes.slave:
raise SlaveError(_("cannot pop a value on a multi option {0}" raise SlaveError(_("cannot pop a value on a multi option {0}"
" which is a slave").format(self.opt._name)) " which is a slave").format(self.opt._name))
elif self.opt.objimpl_get_multitype() == multitypes.master: elif self.opt.optimpl_get_multitype() == multitypes.master:
for slave in self.opt.objimpl_get_master_slaves(): for slave in self.opt.optimpl_get_master_slaves():
self.context.cfgimpl_get_values()[slave].pop(key, force=True) self.context.cfgimpl_get_values()[slave].pop(key, force=True)
self.context.cfgimpl_get_values()._setvalue(self.opt, self) self.context.cfgimpl_get_values()._setvalue(self.opt, self)
return super(Multi, self).pop(key) return super(Multi, self).pop(key)