From 3bef45c9dbd4f31c79a9a5eed2d2d842aa33e161 Mon Sep 17 00:00:00 2001 From: Emmanuel Garette Date: Wed, 22 Jan 2020 20:46:18 +0100 Subject: [PATCH] New Postgres storage --- tests/config.py | 43 + tests/test_cache.py | 851 ++++----- tests/test_choice_option.py | 293 +-- tests/test_config.py | 427 +++-- tests/test_config_api.py | 537 +++--- tests/test_config_domain.py | 377 ++-- tests/test_config_ip.py | 596 +++--- tests/test_dereference.py | 241 +-- tests/test_duplicate_config.py | 82 +- tests/test_dyn_optiondescription.py | 1909 ++++++++++--------- tests/test_freeze.py | 179 +- tests/test_leadership.py | 1117 +++++------ tests/test_mandatory.py | 752 ++++---- tests/test_metaconfig.py | 133 +- tests/test_mixconfig.py | 144 +- tests/test_multi_parents.py | 16 +- tests/test_option.py | 212 ++- tests/test_option_callback.py | 1402 +++++++------- tests/test_option_default.py | 314 ++-- tests/test_option_owner.py | 257 +-- tests/test_option_setting.py | 859 ++++----- tests/test_option_type.py | 219 +-- tests/test_option_username.py | 23 +- tests/test_option_validator.py | 1360 +++++++------- tests/test_option_with_special_name.py | 28 +- tests/test_permissive.py | 667 +++---- tests/test_requires.py | 1959 ++++++++++---------- tests/test_slots.py | 151 +- tests/test_state.py | 223 +-- tests/test_storage.py | 472 +++-- tests/test_submulti.py | 557 +++--- tests/test_symlink.py | 316 ++-- tiramisu/__init__.py | 2 +- tiramisu/api.py | 768 +++++--- tiramisu/asyncinit.py | 8 +- tiramisu/autolib.py | 29 +- tiramisu/config.py | 328 ++-- tiramisu/error.py | 16 +- tiramisu/function.py | 6 +- tiramisu/i18n.py | 2 +- tiramisu/log.py | 2 +- tiramisu/option/baseoption.py | 2 +- tiramisu/option/booloption.py | 2 +- tiramisu/option/broadcastoption.py | 2 +- tiramisu/option/choiceoption.py | 2 +- tiramisu/option/dateoption.py | 2 +- tiramisu/option/domainnameoption.py | 2 +- tiramisu/option/dynoptiondescription.py | 2 +- tiramisu/option/emailoption.py | 2 +- tiramisu/option/filenameoption.py | 2 +- tiramisu/option/floatoption.py | 2 +- tiramisu/option/intoption.py | 2 +- tiramisu/option/ipoption.py | 2 +- tiramisu/option/leadership.py | 28 +- tiramisu/option/netmaskoption.py | 2 +- tiramisu/option/networkoption.py | 2 +- tiramisu/option/option.py | 2 +- tiramisu/option/optiondescription.py | 16 +- tiramisu/option/passwordoption.py | 2 +- tiramisu/option/portoption.py | 2 +- tiramisu/option/stroption.py | 2 +- tiramisu/option/symlinkoption.py | 2 +- tiramisu/option/syndynoption.py | 2 +- tiramisu/option/syndynoptiondescription.py | 8 +- tiramisu/option/urloption.py | 2 +- tiramisu/option/usernameoption.py | 2 +- tiramisu/setting.py | 185 +- tiramisu/storage/__init__.py | 101 +- tiramisu/storage/cache/dictionary.py | 2 +- tiramisu/storage/cacheobj.py | 34 +- tiramisu/storage/dictionary/__init__.py | 8 +- tiramisu/storage/dictionary/setting.py | 95 +- tiramisu/storage/dictionary/storage.py | 103 +- tiramisu/storage/dictionary/value.py | 171 +- tiramisu/storage/postgres/__init__.py | 32 + tiramisu/storage/postgres/setting.py | 179 ++ tiramisu/storage/postgres/storage.py | 183 ++ tiramisu/storage/postgres/value.py | 298 +++ tiramisu/storage/sqlite3/__init__.py | 12 +- tiramisu/storage/sqlite3/setting.py | 133 +- tiramisu/storage/sqlite3/sqlite3db.py | 2 +- tiramisu/storage/sqlite3/storage.py | 210 ++- tiramisu/storage/sqlite3/value.py | 206 +- tiramisu/todict.py | 2 +- tiramisu/value.py | 147 +- 85 files changed, 10814 insertions(+), 9262 deletions(-) create mode 100644 tiramisu/storage/postgres/__init__.py create mode 100644 tiramisu/storage/postgres/setting.py create mode 100644 tiramisu/storage/postgres/storage.py create mode 100644 tiramisu/storage/postgres/value.py diff --git a/tests/config.py b/tests/config.py index 90d6207..776d851 100644 --- a/tests/config.py +++ b/tests/config.py @@ -1,4 +1,6 @@ # from json import dumps, loads +import asyncio +from os import environ try: from tiramisu_api import Config class TestConfig(Config): @@ -40,3 +42,44 @@ async def global_owner(config, config_type): @pytest.fixture(params=PARAMS) def config_type(request): return request.param + + +LOOP = None +@pytest.fixture(scope='session') +def event_loop(request): + """Create an instance of the default event loop for each test case.""" + global LOOP + if LOOP is None: + LOOP = asyncio.get_event_loop_policy().new_event_loop() + return LOOP + + +async def _delete_sessions(meta): + if await meta.config.type() != 'config': + for conf in await meta.config.list(): + await _delete_sessions(conf) + await meta.session.reset() + + +async def delete_sessions(confs): + if not isinstance(confs, list): + confs = [confs] + for conf in confs: + await _delete_sessions(conf) + if environ.get('TIRAMISU_STORAGE') == 'postgres': + async with confs[0]._config_bag.context.getconnection() as connection: + assert await connection.fetchrow('SELECT * FROM session') is None + assert await connection.fetchrow('SELECT * FROM value') is None + assert await connection.fetchrow('SELECT * FROM information') is None + assert await connection.fetchrow('SELECT * FROM property') is None + assert await connection.fetchrow('SELECT * FROM permissive') is None + elif environ.get('TIRAMISU_STORAGE') == 'sqlite3': + async with confs[0]._config_bag.context.getconnection() as connection: + assert await connection.select('SELECT * FROM session') is None + assert await connection.select('SELECT * FROM value') is None + assert await connection.select('SELECT * FROM information') is None + assert await connection.select('SELECT * FROM property') is None + assert await connection.select('SELECT * FROM permissive') is None + else: + from tiramisu import list_sessions + assert not await list_sessions() diff --git a/tests/test_cache.py b/tests/test_cache.py index d1046fa..94b0a74 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -10,17 +10,7 @@ from tiramisu import BoolOption, IPOption, IntOption, StrOption, OptionDescripti list_sessions, default_storage, delete_session, calc_value from tiramisu.error import ConfigError, PropertiesOptionError from tiramisu.setting import groups - - -def teardown_function(function): - if default_storage.is_persistent(): - sessions = list_sessions() - if not sessions: - return - assert len(sessions) == 1 - delete_session(sessions[0]) - else: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop global incr @@ -42,216 +32,225 @@ def make_description(): async def test_cache_config(): od1 = make_description() assert od1.impl_already_build_caches() is False - c = await Config(od1) - assert od1.impl_already_build_caches() is True - c + async with await Config(od1) as cfg: + assert od1.impl_already_build_caches() is True + cfg + assert not await list_sessions() @pytest.mark.asyncio async def test_cache(): od1 = make_description() - cfg = await Config(od1) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.option('u2').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' in values.get_cached() - assert 'u2' in settings.get_cached() + async with await Config(od1) as cfg: + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.option('u2').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' in values.get_cached() + assert 'u2' in settings.get_cached() + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_importation(): od1 = make_description() - cfg = await Config(od1) - await cfg.option('u2').value.set(1) - export = await cfg.value.exportation() - assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} - await cfg.option('u2').value.set(2) - assert await cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []} - await cfg.value.importation(export) - assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} + async with await Config(od1) as cfg: + await cfg.option('u2').value.set(1) + export = await cfg.value.exportation() + assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} + await cfg.option('u2').value.set(2) + assert await cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []} + await cfg.value.importation(export) + assert await cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []} + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_importation_property(): od1 = make_description() - cfg = await Config(od1) - await cfg.option('u2').property.add('prop') - export = await cfg.property.exportation() - assert await cfg.option('u2').property.get() == {'prop'} - await cfg.option('u2').property.add('prop2') - assert await cfg.option('u2').property.get() == {'prop', 'prop2'} - await cfg.property.importation(export) - assert await cfg.option('u2').property.get() == {'prop'} + async with await Config(od1) as cfg: + await cfg.option('u2').property.add('prop') + export = await cfg.property.exportation() + assert await cfg.option('u2').property.get() == {'prop'} + await cfg.option('u2').property.add('prop2') + assert await cfg.option('u2').property.get() == {'prop', 'prop2'} + await cfg.property.importation(export) + assert await cfg.option('u2').property.get() == {'prop'} + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_importation_permissive(): od1 = make_description() - cfg = await Config(od1) - await cfg.option('u2').permissive.set(frozenset(['prop'])) - export = await cfg.permissive.exportation() - assert await cfg.option('u2').permissive.get() == {'prop'} - await cfg.option('u2').permissive.set(frozenset(['prop', 'prop2'])) - assert await cfg.option('u2').permissive.get() == {'prop', 'prop2'} - await cfg.permissive.importation(export) - assert await cfg.option('u2').permissive.get() == {'prop'} + async with await Config(od1) as cfg: + await cfg.option('u2').permissive.set(frozenset(['prop'])) + export = await cfg.permissive.exportation() + assert await cfg.option('u2').permissive.get() == {'prop'} + await cfg.option('u2').permissive.set(frozenset(['prop', 'prop2'])) + assert await cfg.option('u2').permissive.get() == {'prop', 'prop2'} + await cfg.permissive.importation(export) + assert await cfg.option('u2').permissive.get() == {'prop'} + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_reset(): od1 = make_description() - cfg = await Config(od1) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - #when change a value - await cfg.option('u1').value.get() - await cfg.option('u2').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' in values.get_cached() - assert 'u2' in settings.get_cached() - assert 'u1' in values.get_cached() - settings.get_cached() - await cfg.option('u2').value.set(1) - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' in values.get_cached() - assert 'u2' not in settings.get_cached() - #when remove a value - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.option('u2').value.reset() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' not in values.get_cached() - assert 'u2' not in settings.get_cached() - #when add/del property - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.option('u2').property.add('test') - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' not in values.get_cached() - assert 'u2' not in settings.get_cached() - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.option('u2').property.pop('test') - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' not in values.get_cached() - assert 'u2' not in settings.get_cached() - #when enable/disabled property - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.property.add('test') - assert 'u1' not in values.get_cached() - assert 'u1' not in settings.get_cached() - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.property.pop('test') - assert 'u1' not in values.get_cached() - assert 'u1' not in settings.get_cached() + async with await Config(od1) as cfg: + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + #when change a value + await cfg.option('u1').value.get() + await cfg.option('u2').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' in values.get_cached() + assert 'u2' in settings.get_cached() + assert 'u1' in values.get_cached() + settings.get_cached() + await cfg.option('u2').value.set(1) + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' in values.get_cached() + assert 'u2' not in settings.get_cached() + #when remove a value + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.option('u2').value.reset() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' not in values.get_cached() + assert 'u2' not in settings.get_cached() + #when add/del property + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.option('u2').property.add('test') + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' not in values.get_cached() + assert 'u2' not in settings.get_cached() + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.option('u2').property.pop('test') + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' not in values.get_cached() + assert 'u2' not in settings.get_cached() + #when enable/disabled property + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.property.add('test') + assert 'u1' not in values.get_cached() + assert 'u1' not in settings.get_cached() + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.property.pop('test') + assert 'u1' not in values.get_cached() + assert 'u1' not in settings.get_cached() + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_reset_multi(): od1 = make_description() - cfg = await Config(od1) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - await cfg.option('u1').value.get() - await cfg.option('u3').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' in settings.get_cached() - #when change a value - await cfg.option('u3').value.set([1]) - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' not in settings.get_cached() - #when append value - await cfg.option('u1').value.get() - await cfg.option('u3').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' in settings.get_cached() - await cfg.option('u3').value.set([1, 2]) - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' not in settings.get_cached() - #when pop value - await cfg.option('u1').value.get() - await cfg.option('u3').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' in settings.get_cached() - await cfg.option('u3').value.set([1]) - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' in values.get_cached() - assert 'u3' not in settings.get_cached() - #when remove a value - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.option('u3').value.reset() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u3' not in values.get_cached() - assert 'u3' not in settings.get_cached() + async with await Config(od1) as cfg: + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + await cfg.option('u1').value.get() + await cfg.option('u3').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' in settings.get_cached() + #when change a value + await cfg.option('u3').value.set([1]) + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' not in settings.get_cached() + #when append value + await cfg.option('u1').value.get() + await cfg.option('u3').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' in settings.get_cached() + await cfg.option('u3').value.set([1, 2]) + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' not in settings.get_cached() + #when pop value + await cfg.option('u1').value.get() + await cfg.option('u3').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' in settings.get_cached() + await cfg.option('u3').value.set([1]) + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' in values.get_cached() + assert 'u3' not in settings.get_cached() + #when remove a value + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.option('u3').value.reset() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u3' not in values.get_cached() + assert 'u3' not in settings.get_cached() + assert not await list_sessions() @pytest.mark.asyncio async def test_reset_cache(): od1 = make_description() - cfg = await Config(od1) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - await cfg.option('u1').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - await cfg.cache.reset() - assert 'u1' not in values.get_cached() - assert 'u1' not in settings.get_cached() - await cfg.option('u1').value.get() - await cfg.option('u2').value.get() - assert 'u1' in values.get_cached() - assert 'u1' in settings.get_cached() - assert 'u2' in values.get_cached() - assert 'u2' in settings.get_cached() - await cfg.cache.reset() - assert 'u1' not in values.get_cached() - assert 'u1' not in settings.get_cached() - assert 'u2' not in values.get_cached() - assert 'u2' not in settings.get_cached() + async with await Config(od1) as cfg: + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + await cfg.option('u1').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + await cfg.cache.reset() + assert 'u1' not in values.get_cached() + assert 'u1' not in settings.get_cached() + await cfg.option('u1').value.get() + await cfg.option('u2').value.get() + assert 'u1' in values.get_cached() + assert 'u1' in settings.get_cached() + assert 'u2' in values.get_cached() + assert 'u2' in settings.get_cached() + await cfg.cache.reset() + assert 'u1' not in values.get_cached() + assert 'u1' not in settings.get_cached() + assert 'u2' not in values.get_cached() + assert 'u2' not in settings.get_cached() + assert not await list_sessions() @pytest.mark.asyncio async def test_cache_not_cache(): od1 = make_description() - cfg = await Config(od1) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - await cfg.property.pop('cache') - await cfg.option('u1').value.get() - assert 'u1' not in values.get_cached() - assert 'u1' not in settings.get_cached() + async with await Config(od1) as cfg: + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + await cfg.property.pop('cache') + await cfg.option('u1').value.get() + assert 'u1' not in values.get_cached() + assert 'u1' not in settings.get_cached() + assert not await list_sessions() @pytest.mark.asyncio @@ -260,47 +259,48 @@ async def test_cache_leadership(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od1 = OptionDescription('toto', '', [interface1]) - cfg = await Config(od1) - await cfg.property.read_write() - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - assert values.get_cached() == {} - #assert settings.get_cached() == {} - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - cache = values.get_cached() - assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) - assert cache['ip_admin_eth0.ip_admin_eth0'][None][0] == ['192.168.1.2'] - #assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None]) - #assert cache['ip_admin_eth0.netmask_admin_eth0'][None][0] == [None] - #assert cache['ip_admin_eth0.netmask_admin_eth0'][0][0] is None - cache = settings.get_cached() - assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert set(cache['ip_admin_eth0'].keys()) == set([None]) - assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) - assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([0, None]) - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() - cache = values.get_cached() - assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) - assert cache['ip_admin_eth0.ip_admin_eth0'][None][0] == ['192.168.1.2', '192.168.1.1'] - #assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None]) - #assert cache['ip_admin_eth0.netmask_admin_eth0'][None][0] == [None, None] - #assert cache['ip_admin_eth0.netmask_admin_eth0'][0][0] is None - #assert cache['ip_admin_eth0.netmask_admin_eth0'][1][0] is None - cache = settings.get_cached() - assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert set(cache['ip_admin_eth0'].keys()) == set([None]) - assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) - assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None, 0, 1]) - #DEL, insert, ... + async with await Config(od1) as cfg: + await cfg.property.read_write() + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + assert values.get_cached() == {} + #assert settings.get_cached() == {} + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + cache = values.get_cached() + assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) + assert cache['ip_admin_eth0.ip_admin_eth0'][None][0] == ['192.168.1.2'] + #assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None]) + #assert cache['ip_admin_eth0.netmask_admin_eth0'][None][0] == [None] + #assert cache['ip_admin_eth0.netmask_admin_eth0'][0][0] is None + cache = settings.get_cached() + assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert set(cache['ip_admin_eth0'].keys()) == set([None]) + assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) + assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([0, None]) + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() + cache = values.get_cached() + assert set(cache.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) + assert cache['ip_admin_eth0.ip_admin_eth0'][None][0] == ['192.168.1.2', '192.168.1.1'] + #assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None]) + #assert cache['ip_admin_eth0.netmask_admin_eth0'][None][0] == [None, None] + #assert cache['ip_admin_eth0.netmask_admin_eth0'][0][0] is None + #assert cache['ip_admin_eth0.netmask_admin_eth0'][1][0] is None + cache = settings.get_cached() + assert set(cache.keys()) == set([None, 'ip_admin_eth0', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert set(cache['ip_admin_eth0'].keys()) == set([None]) + assert set(cache['ip_admin_eth0.ip_admin_eth0'].keys()) == set([None]) + assert set(cache['ip_admin_eth0.netmask_admin_eth0'].keys()) == set([None, 0, 1]) + #DEL, insert, ... + assert not await list_sessions() def compare(calculated, expected): @@ -320,63 +320,64 @@ async def test_cache_callback(): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val1)))) val5 = StrOption('val5', "", [Calculation(calc_value, Params(ParamValue('yes')))], multi=True) od1 = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5]) - cfg = await Config(od1) - await cfg.property.read_write() - await cfg.value.dict() - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - compare(values.get_cached(), {'val1': {None: ('val', None)}, - 'val2': {None: ('val', None)}, - 'val3': {None: ('yes', None)}, - 'val4': {None: ('val', None)}, - 'val5': {None: (['yes'], None)}}) - await cfg.option('val1').value.set('new') - compare(values.get_cached(), {'val3': {None: ('yes', None)}, - 'val1': {None: ('new', None)}, - 'val5': {None: (['yes'], None)}}) - await cfg.value.dict() - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('yes', None)}, - 'val4': {None: ('new', None)}, - 'val5': {None: (['yes'], None)}}) - await cfg.option('val3').value.set('new2') - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val4': {None: ('new', None)}, - 'val1': {None: ('new', None)}, - 'val3': {None: ('new2', None, True)}, - 'val5': {None: (['yes'], None)}}) - await cfg.value.dict() - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('new2', None)}, - 'val4': {None: ('new', None)}, - 'val5': {None: (['yes'], None)}}) - await cfg.option('val4').value.set('new3') - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('new2', None)}, - 'val4': {None: ('new3', None, True)}, - 'val5': {None: (['yes'], None)}}) - await cfg.value.dict() - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('new2', None)}, - 'val4': {None: ('new3', None)}, - 'val5': {None: (['yes'], None)}}) - await cfg.option('val5').value.set([undefined, 'new4']) - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('new2', None)}, - 'val4': {None: ('new3', None)}, - 'val5': {None: (['yes', 'new4'], None)}}) - await cfg.value.dict() - compare(values.get_cached(), {'val1': {None: ('new', None)}, - 'val2': {None: ('new', None)}, - 'val3': {None: ('new2', None)}, - 'val4': {None: ('new3', None)}, - 'val5': {None: (['yes', 'new4'], None)}}) + async with await Config(od1) as cfg: + await cfg.property.read_write() + await cfg.value.dict() + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + compare(values.get_cached(), {'val1': {None: ('val', None)}, + 'val2': {None: ('val', None)}, + 'val3': {None: ('yes', None)}, + 'val4': {None: ('val', None)}, + 'val5': {None: (['yes'], None)}}) + await cfg.option('val1').value.set('new') + compare(values.get_cached(), {'val3': {None: ('yes', None)}, + 'val1': {None: ('new', None)}, + 'val5': {None: (['yes'], None)}}) + await cfg.value.dict() + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('yes', None)}, + 'val4': {None: ('new', None)}, + 'val5': {None: (['yes'], None)}}) + await cfg.option('val3').value.set('new2') + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val4': {None: ('new', None)}, + 'val1': {None: ('new', None)}, + 'val3': {None: ('new2', None, True)}, + 'val5': {None: (['yes'], None)}}) + await cfg.value.dict() + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('new2', None)}, + 'val4': {None: ('new', None)}, + 'val5': {None: (['yes'], None)}}) + await cfg.option('val4').value.set('new3') + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('new2', None)}, + 'val4': {None: ('new3', None, True)}, + 'val5': {None: (['yes'], None)}}) + await cfg.value.dict() + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('new2', None)}, + 'val4': {None: ('new3', None)}, + 'val5': {None: (['yes'], None)}}) + await cfg.option('val5').value.set([undefined, 'new4']) + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('new2', None)}, + 'val4': {None: ('new3', None)}, + 'val5': {None: (['yes', 'new4'], None)}}) + await cfg.value.dict() + compare(values.get_cached(), {'val1': {None: ('new', None)}, + 'val2': {None: ('new', None)}, + 'val3': {None: ('new2', None)}, + 'val4': {None: ('new3', None)}, + 'val5': {None: (['yes', 'new4'], None)}}) + assert not await list_sessions() @pytest.mark.asyncio @@ -385,51 +386,52 @@ async def test_cache_leader_and_followers(): val2 = StrOption('val2', "", multi=True) interface1 = Leadership('val1', '', [val1, val2]) od1 = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(od1) - await cfg.property.read_write() - await cfg.value.dict() - global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] - val1_props = [] - val1_val1_props = ['empty', 'unique'] - val1_val2_props = [] - global_props = frozenset(global_props) - val1_props = frozenset(val1_props) - val1_val1_props = frozenset(val1_val1_props) - val1_val2_props = frozenset(val1_val2_props) - #None because no value - idx_val2 = None - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - compare(settings.get_cached(), {None: {None: (global_props, None)}, - 'val1': {None: (val1_props, None)}, - 'val1.val1': {None: (val1_val1_props, None)}, - 'val1.val2': {idx_val2: (val1_val2_props, None)}}) - # len is 0 so don't get any value - compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) - # - await cfg.option('val1.val1').value.set([undefined]) - val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} - compare(settings.get_cached(), {None: {None: (set(global_props), None)}, - 'val1.val1': {None: (val1_val1_props, None)}, - 'val1.val2': val_val2_props}) - compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) - await cfg.value.dict() - #has value - idx_val2 = 0 - val_val2 = None - val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} - compare(settings.get_cached(), {None: {None: (global_props, None)}, - 'val1': {None: (val1_props, None)}, - 'val1.val1': {None: (val1_val1_props, None)}, - 'val1.val2': val_val2_props}) - compare(values.get_cached(), {'val1.val1': {None: ([None], None)}, - 'val1.val2': {idx_val2: (val_val2, None)}}) - await cfg.option('val1.val1').value.set([undefined, undefined]) - await cfg.value.dict() - await cfg.option('val1.val2', 1).value.set('oui') - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) - compare(values.get_cached(), {'val1.val2': {1: ('oui', None, True)}}) - val1_val2_props = {0: (frozenset([]), None), 1: (frozenset([]), None)} + async with await Config(od1) as cfg: + await cfg.property.read_write() + await cfg.value.dict() + global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] + val1_props = [] + val1_val1_props = ['empty', 'unique'] + val1_val2_props = [] + global_props = frozenset(global_props) + val1_props = frozenset(val1_props) + val1_val1_props = frozenset(val1_val1_props) + val1_val2_props = frozenset(val1_val2_props) + #None because no value + idx_val2 = None + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + compare(settings.get_cached(), {None: {None: (global_props, None)}, + 'val1': {None: (val1_props, None)}, + 'val1.val1': {None: (val1_val1_props, None)}, + 'val1.val2': {idx_val2: (val1_val2_props, None)}}) + # len is 0 so don't get any value + compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) + # + await cfg.option('val1.val1').value.set([undefined]) + val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} + compare(settings.get_cached(), {None: {None: (set(global_props), None)}, + 'val1.val1': {None: (val1_val1_props, None)}, + 'val1.val2': val_val2_props}) + compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) + await cfg.value.dict() + #has value + idx_val2 = 0 + val_val2 = None + val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)} + compare(settings.get_cached(), {None: {None: (global_props, None)}, + 'val1': {None: (val1_props, None)}, + 'val1.val1': {None: (val1_val1_props, None)}, + 'val1.val2': val_val2_props}) + compare(values.get_cached(), {'val1.val1': {None: ([None], None)}, + 'val1.val2': {idx_val2: (val_val2, None)}}) + await cfg.option('val1.val1').value.set([undefined, undefined]) + await cfg.value.dict() + await cfg.option('val1.val2', 1).value.set('oui') + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) + compare(values.get_cached(), {'val1.val2': {1: ('oui', None, True)}}) + val1_val2_props = {0: (frozenset([]), None), 1: (frozenset([]), None)} + assert not await list_sessions() @pytest.mark.asyncio @@ -438,32 +440,32 @@ async def test_cache_leader_callback(): val2 = StrOption('val2', "", Calculation(calc_value, Params(kwargs={'value': ParamOption(val1)})), multi=True) interface1 = Leadership('val1', '', [val1, val2]) od1 = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(od1) - await cfg.property.read_write() - await cfg.value.dict() - global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] - val1_props = [] - val1_val1_props = ['empty', 'unique'] - val1_val2_props = [] - global_props = frozenset(global_props) - val1_props = frozenset(val1_props) - val1_val1_props = frozenset(val1_val1_props) - val1_val2_props = frozenset(val1_val2_props) - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - compare(settings.get_cached(), {None: {None: (global_props, None)}, - 'val1': {None: (val1_props, None)}, - 'val1.val1': {None: (val1_val1_props, None)}, - 'val1.val2': {None: (val1_val2_props, None)}}) - compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) - await cfg.option('val1.val1').value.set([undefined]) - compare(settings.get_cached(), {None: {None: (set(global_props), None)}, - 'val1': {None: (set(), None, True)}, - 'val1.val1': {None: (val1_val1_props, None)}, - 'val1.val2': {None: (val1_val2_props, None)}}) + async with await Config(od1) as cfg: + await cfg.property.read_write() + await cfg.value.dict() + global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value'] + val1_props = [] + val1_val1_props = ['empty', 'unique'] + val1_val2_props = [] + global_props = frozenset(global_props) + val1_props = frozenset(val1_props) + val1_val1_props = frozenset(val1_val1_props) + val1_val2_props = frozenset(val1_val2_props) + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + compare(settings.get_cached(), {None: {None: (global_props, None)}, + 'val1': {None: (val1_props, None)}, + 'val1.val1': {None: (val1_val1_props, None)}, + 'val1.val2': {None: (val1_val2_props, None)}}) + compare(values.get_cached(), {'val1.val1': {None: ([], None)}}) + await cfg.option('val1.val1').value.set([undefined]) + compare(settings.get_cached(), {None: {None: (set(global_props), None)}, + 'val1.val1': {None: (val1_val1_props, None)}, + 'val1.val2': {None: (val1_val2_props, None)}}) - compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) - await cfg.value.dict() + compare(values.get_cached(), {'val1.val1': {None: ([None], None, True)}}) + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -475,48 +477,49 @@ async def test_cache_requires(): 'expected': ParamValue(False), 'default': ParamValue(None)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) - od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - assert values.get_cached() == {} - assert await cfg.option('ip_address_service').value.get() == None - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) + od1 = OptionDescription('service', '', [a, b]) + async with await Config(od1) as cfg: + await cfg.property.read_write() + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + assert values.get_cached() == {} + assert await cfg.option('ip_address_service').value.get() == None + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) - compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, - 'activate_service': {None: (True, None)}}) - await cfg.value.dict() - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) + compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, + 'activate_service': {None: (True, None)}}) + await cfg.value.dict() + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) - compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, - 'activate_service': {None: (True, None)}}) - await cfg.option('ip_address_service').value.set('1.1.1.1') - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}}) + compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, + 'activate_service': {None: (True, None)}}) + await cfg.option('ip_address_service').value.set('1.1.1.1') + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}}) - compare(values.get_cached(), {'activate_service': {None: (True, None)}, 'ip_address_service': {None: ('1.1.1.1', None, True)}}) - await cfg.value.dict() - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) + compare(values.get_cached(), {'activate_service': {None: (True, None)}, 'ip_address_service': {None: ('1.1.1.1', None, True)}}) + await cfg.value.dict() + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) - compare(values.get_cached(), {'ip_address_service': {None: ('1.1.1.1', None)}, - 'activate_service': {None: (True, None)}}) - await cfg.option('activate_service').value.set(False) - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) + compare(values.get_cached(), {'ip_address_service': {None: ('1.1.1.1', None)}, + 'activate_service': {None: (True, None)}}) + await cfg.option('activate_service').value.set(False) + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}}) - compare(values.get_cached(), {'activate_service': {None: (False, None)}}) - await cfg.value.dict() - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set(['disabled']), None)}}) + compare(values.get_cached(), {'activate_service': {None: (False, None)}}) + await cfg.value.dict() + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set(['disabled']), None)}}) - compare(values.get_cached(), {'activate_service': {None: (False, None)}}) + compare(values.get_cached(), {'activate_service': {None: (False, None)}}) + assert not await list_sessions() @pytest.mark.asyncio @@ -528,29 +531,30 @@ async def test_cache_global_properties(): 'expected': ParamValue(False), 'default': ParamValue(None)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) - od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - values = cfg._config_bag.context._impl_values_cache - settings = cfg._config_bag.context._impl_properties_cache - assert values.get_cached() == {} - assert await cfg.option('ip_address_service').value.get() == None - compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) + od1 = OptionDescription('service', '', [a, b]) + async with await Config(od1) as cfg: + await cfg.property.read_write() + values = cfg._config_bag.context._impl_values_cache + settings = cfg._config_bag.context._impl_properties_cache + assert values.get_cached() == {} + assert await cfg.option('ip_address_service').value.get() == None + compare(settings.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) - compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, - 'activate_service': {None: (True, None)}}) - await cfg.property.pop('disabled') - assert await cfg.option('ip_address_service').value.get() == None - compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) - await cfg.property.add('test') - assert await cfg.option('ip_address_service').value.get() == None - compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'test', 'force_store_value']), None)}, - 'activate_service': {None: (set([]), None)}, - 'ip_address_service': {None: (set([]), None)}}) + compare(values.get_cached(), {'ip_address_service': {None: (None, None)}, + 'activate_service': {None: (True, None)}}) + await cfg.property.pop('disabled') + assert await cfg.option('ip_address_service').value.get() == None + compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) + await cfg.property.add('test') + assert await cfg.option('ip_address_service').value.get() == None + compare(settings.get_cached(), {None: {None: (set(['cache', 'frozen', 'hidden', 'validator', 'warnings', 'test', 'force_store_value']), None)}, + 'activate_service': {None: (set([]), None)}, + 'ip_address_service': {None: (set([]), None)}}) + assert not await list_sessions() @pytest.mark.asyncio @@ -558,19 +562,20 @@ async def test_callback_value_incr(): val1 = IntOption('val1', "", Calculation(return_incr), properties=('expire',)) val2 = IntOption('val2', "", Calculation(calc_value, Params(ParamOption(val1)))) od1 = OptionDescription('rootconfig', '', [val1, val2]) - cfg = await Config(od1) - assert await cfg.cache.get_expiration_time() == 5 - await cfg.cache.set_expiration_time(1) - assert await cfg.cache.get_expiration_time() == 1 - await cfg.property.read_write() - assert await cfg.option('val1').value.get() == 1 - sleep(1) - assert await cfg.option('val2').value.get() == 1 - sleep(1) - assert await cfg.option('val1').value.get() == 1 - assert await cfg.option('val2').value.get() == 1 - sleep(2) - assert await cfg.option('val1').value.get() == 2 - assert await cfg.option('val2').value.get() == 2 - assert await cfg.option('val1').value.get() == 2 - assert await cfg.option('val2').value.get() == 2 + async with await Config(od1) as cfg: + assert await cfg.cache.get_expiration_time() == 5 + await cfg.cache.set_expiration_time(1) + assert await cfg.cache.get_expiration_time() == 1 + await cfg.property.read_write() + assert await cfg.option('val1').value.get() == 1 + sleep(1) + assert await cfg.option('val2').value.get() == 1 + sleep(1) + assert await cfg.option('val1').value.get() == 1 + assert await cfg.option('val2').value.get() == 1 + sleep(2) + assert await cfg.option('val1').value.get() == 2 + assert await cfg.option('val2').value.get() == 2 + assert await cfg.option('val1').value.get() == 2 + assert await cfg.option('val2').value.get() == 2 + assert not await list_sessions() diff --git a/tests/test_choice_option.py b/tests/test_choice_option.py index 60dbb4d..9d0fcb5 100644 --- a/tests/test_choice_option.py +++ b/tests/test_choice_option.py @@ -4,17 +4,13 @@ import pytest from .autopath import do_autopath do_autopath() -from .config import config_type, get_config, value_list, global_owner +from .config import config_type, get_config, value_list, global_owner, event_loop from tiramisu import ChoiceOption, StrOption, OptionDescription, Config, owners, Calculation, \ undefined, Params, ParamValue, ParamOption, list_sessions from tiramisu.error import ConfigError -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def return_val(val): return val @@ -35,101 +31,107 @@ def return_error(*args, **kwargs): async def test_choiceoption(config_type): choice = ChoiceOption('choice', '', values=('val1', 'val2')) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - owner = await global_owner(cfg, config_type) - assert await cfg.option('choice').owner.get() == owners.default - assert await cfg.option('choice').owner.isdefault() - # - await cfg.option('choice').value.set('val1') - assert await cfg.option('choice').owner.get() == owner - assert not await cfg.option('choice').owner.isdefault() - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.get() == owners.default - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.get() == owners.default - assert await cfg.option('choice').owner.isdefault() - # - assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + owner = await global_owner(cfg, config_type) + assert await cfg.option('choice').owner.get() == owners.default + assert await cfg.option('choice').owner.isdefault() + # + await cfg.option('choice').value.set('val1') + assert await cfg.option('choice').owner.get() == owner + assert not await cfg.option('choice').owner.isdefault() + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.get() == owners.default + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.get() == owners.default + assert await cfg.option('choice').owner.isdefault() + # + assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') + assert not await list_sessions() @pytest.mark.asyncio async def test_choiceoption_function(config_type): choice = ChoiceOption('choice', '', values=Calculation(return_list)) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - owner = await global_owner(cfg, config_type) - assert await cfg.option('choice').owner.isdefault() - # - await cfg.option('choice').value.set('val1') - assert await cfg.option('choice').owner.get() == owner - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.isdefault() - # - assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + owner = await global_owner(cfg, config_type) + assert await cfg.option('choice').owner.isdefault() + # + await cfg.option('choice').value.set('val1') + assert await cfg.option('choice').owner.get() == owner + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.isdefault() + # + assert value_list(await cfg.option('choice').value.list()) == ('val1', 'val2') + assert not await list_sessions() @pytest.mark.asyncio async def test_choiceoption_function_error(): choice = ChoiceOption('choice', '', values=Calculation(return_error)) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('choice').value.set('val1') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('choice').value.set('val1') + assert not await list_sessions() @pytest.mark.asyncio async def test_choiceoption_function_error_args(): choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(ParamValue('val1')))) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('choice').value.set('val1') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('choice').value.set('val1') + assert not await list_sessions() @pytest.mark.asyncio async def test_choiceoption_function_error_kwargs(): choice = ChoiceOption('choice', '', values=Calculation(return_error, Params(kwargs={'kwargs': ParamValue('val1')}))) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('choice').value.set('val1') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('choice').value.set('val1') + assert not await list_sessions() @pytest.mark.asyncio async def test_choiceoption_calc_function(config_type): choice = ChoiceOption('choice', "", values=Calculation(return_calc_list, Params(ParamValue('val1')))) odesc = OptionDescription('od', '', [choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - owner = await global_owner(cfg, config_type) - assert await cfg.option('choice').owner.isdefault() - # - await cfg.option('choice').value.set('val1') - assert await cfg.option('choice').owner.get() == owner - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.isdefault() + async with await Config(odesc) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + owner = await global_owner(cfg, config_type) + assert await cfg.option('choice').owner.isdefault() + # + await cfg.option('choice').value.set('val1') + assert await cfg.option('choice').owner.get() == owner + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -139,21 +141,22 @@ async def test_choiceoption_calc_opt_function(config_type): "", values=Calculation(return_calc_list, Params(ParamOption(str_)))) odesc = OptionDescription('od', '', [str_, choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - owner = await cfg.owner.get() - cfg = await get_config(cfg, config_type) - assert await cfg.option('choice').owner.isdefault() - # - await cfg.option('choice').value.set('val1') - assert await cfg.option('choice').owner.get() == owner - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.isdefault() + async with await Config(odesc) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + cfg = await get_config(cfg, config_type) + assert await cfg.option('choice').owner.isdefault() + # + await cfg.option('choice').value.set('val1') + assert await cfg.option('choice').owner.get() == owner + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -163,10 +166,11 @@ async def test_choiceoption_calc_opt_function_propertyerror(): "", values=Calculation(return_calc_list, Params(ParamOption(str_)))) odesc = OptionDescription('od', '', [str_, choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('choice').value.set('no') + async with await Config(odesc) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('choice').value.set('no') + assert not await list_sessions() #def test_choiceoption_calc_opt_multi_function(config_type): @@ -186,31 +190,32 @@ async def test_choiceoption_calc_opt_multi_function(): values=Calculation(return_val, Params(ParamOption(str_))), multi=True) odesc = OptionDescription('od', '', [str_, choice, ch2]) - cfg = await Config(odesc) - await cfg.property.read_write() - owner = await cfg.owner.get() - cfg = await get_config(cfg, config_type, True) - assert await cfg.option('choice').owner.isdefault() - assert await cfg.option('choice').value.get() == [] - # - await cfg.option('choice').value.set(['val1']) - assert await cfg.option('choice').owner.get() == owner - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set([undefined]) - # - await cfg.option('choice').value.set(['val1']) - assert await cfg.option('choice').owner.get() == owner - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('ch2').value.get() + async with await Config(odesc) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + cfg = await get_config(cfg, config_type, True) + assert await cfg.option('choice').owner.isdefault() + assert await cfg.option('choice').value.get() == [] + # + await cfg.option('choice').value.set(['val1']) + assert await cfg.option('choice').owner.get() == owner + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set([undefined]) + # + await cfg.option('choice').value.set(['val1']) + assert await cfg.option('choice').owner.get() == owner + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('ch2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -227,31 +232,32 @@ async def test_choiceoption_calc_opt_multi_function_kwargs(config_type): values=Calculation(return_val, Params(kwargs={'val': ParamOption(str_)})), multi=True) odesc = OptionDescription('od', '', [str_, choice, ch2]) - cfg = await Config(odesc) - await cfg.property.read_write() - owner = await cfg.owner.get() - # FIXME cfg = await get_config(cfg, config_type) - assert await cfg.option('choice').owner.isdefault() - assert await cfg.option('choice').value.get() == [] - # - await cfg.option('choice').value.set(['val1']) - assert await cfg.option('choice').owner.get() == owner - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set([undefined]) - # - await cfg.option('choice').value.set(['val1']) - assert await cfg.option('choice').owner.get() == owner - # - await cfg.option('choice').value.reset() - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('choice').value.set('no') - assert await cfg.option('choice').owner.isdefault() - # - with pytest.raises(ValueError): - await cfg.option('ch2').value.get() + async with await Config(odesc) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + # FIXME cfg = await get_config(cfg, config_type) + assert await cfg.option('choice').owner.isdefault() + assert await cfg.option('choice').value.get() == [] + # + await cfg.option('choice').value.set(['val1']) + assert await cfg.option('choice').owner.get() == owner + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set([undefined]) + # + await cfg.option('choice').value.set(['val1']) + assert await cfg.option('choice').owner.get() == owner + # + await cfg.option('choice').value.reset() + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('choice').value.set('no') + assert await cfg.option('choice').owner.isdefault() + # + with pytest.raises(ValueError): + await cfg.option('ch2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -263,7 +269,8 @@ async def test_choiceoption_calc_not_list(): values=Calculation(return_val, Params(ParamOption(str_))), multi=True) odesc = OptionDescription('od', '', [str_, choice]) - cfg = await Config(odesc) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('choice').value.set(['val1']) + async with await Config(odesc) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('choice').value.set(['val1']) + assert not await list_sessions() diff --git a/tests/test_config.py b/tests/test_config.py index 0080bbe..7d50837 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,22 +6,18 @@ import weakref from .autopath import do_autopath do_autopath() -from .config import config_type, get_config, value_list, global_owner +from .config import config_type, get_config, value_list, global_owner, event_loop import pytest from tiramisu import Config from tiramisu.config import SubConfig from tiramisu.i18n import _ from tiramisu import Config, IntOption, FloatOption, ChoiceOption, \ - BoolOption, StrOption, SymLinkOption, OptionDescription, undefined + BoolOption, StrOption, SymLinkOption, OptionDescription, undefined, delete_session from tiramisu.error import ConflictError, ConfigError, PropertiesOptionError, APIError from tiramisu.storage import list_sessions -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def make_description(): gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref') gcdummy = BoolOption('dummy', 'dummy', default=False) @@ -52,20 +48,22 @@ async def test_base_config(config_type): """ gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('dummy').value.get() is False - #dmo = await cfg.unwrap_from_path('dummy') - #assert dmo.impl_getname() == 'dummy' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('dummy').value.get() is False + #dmo = await cfg.unwrap_from_path('dummy') + #assert dmo.impl_getname() == 'dummy' + assert not await list_sessions() @pytest.mark.asyncio async def test_base_config_name(): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr, session_id='cfg') - await cfg.config.name() == 'cfg' - #raises(ValueError, "Config(descr, session_id='unvalid name')") + async with await Config(descr, session_id='cfg') as cfg: + await cfg.session.id() == 'cfg' + #raises(ValueError, "Config(descr, session_id='unvalid name')") + assert not await list_sessions() # # #@pytest.mark.asyncio @@ -77,22 +75,25 @@ async def test_base_config_name(): async def test_base_path(): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - await Config(descr) - base = OptionDescription('config', '', [descr]) - base - with pytest.raises(ConfigError): - await Config(base) + async with await Config(descr) as cfg: + base = OptionDescription('config', '', [descr]) + with pytest.raises(ConfigError): + async with await Config(base, session_id='error'): + pass + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio async def test_base_config_force_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - with pytest.raises(PropertiesOptionError): - await cfg.option('boolop').value.get() - assert await cfg.forcepermissive.option('boolop').value.get() is True + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + with pytest.raises(PropertiesOptionError): + await cfg.option('boolop').value.get() + assert await cfg.forcepermissive.option('boolop').value.get() is True + assert not await list_sessions() @pytest.mark.asyncio @@ -101,111 +102,115 @@ async def test_base_config_in_a_tree(): config_type = 'tiramisu' "how options are organized into a tree, see :ref:`tree`" descr = make_description() - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - # - await cfg.option('bool').value.set(False) - # - assert await cfg.option('gc.name').value.get() == 'ref' - await cfg.option('gc.name').value.set('framework') - assert await cfg.option('gc.name').value.get() == 'framework' - # - assert await cfg.option('objspace').value.get() == 'std' - await cfg.option('objspace').value.set('thunk') - assert await cfg.option('objspace').value.get() == 'thunk' - # - assert await cfg.option('gc.float').value.get() == 2.3 - await cfg.option('gc.float').value.set(3.4) - assert await cfg.option('gc.float').value.get() == 3.4 - # - assert await cfg.option('int').value.get() == 0 - await cfg.option('int').value.set(123) - assert await cfg.option('int').value.get() == 123 - # - assert await cfg.option('wantref').value.get() is False - await cfg.option('wantref').value.set(True) - assert await cfg.option('wantref').value.get() is True - # - assert await cfg.option('str').value.get() == 'abc' - await cfg.option('str').value.set('def') - assert await cfg.option('str').value.get() == 'def' - # - with pytest.raises(AttributeError): - await cfg.option('gc.foo').value.get() - ## - cfg = await Config(descr) - assert await cfg.option('bool').value.get() is True - assert await cfg.option('gc.name').value.get() == 'ref' - assert await cfg.option('wantframework').value.get() is False + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + # + await cfg.option('bool').value.set(False) + # + assert await cfg.option('gc.name').value.get() == 'ref' + await cfg.option('gc.name').value.set('framework') + assert await cfg.option('gc.name').value.get() == 'framework' + # + assert await cfg.option('objspace').value.get() == 'std' + await cfg.option('objspace').value.set('thunk') + assert await cfg.option('objspace').value.get() == 'thunk' + # + assert await cfg.option('gc.float').value.get() == 2.3 + await cfg.option('gc.float').value.set(3.4) + assert await cfg.option('gc.float').value.get() == 3.4 + # + assert await cfg.option('int').value.get() == 0 + await cfg.option('int').value.set(123) + assert await cfg.option('int').value.get() == 123 + # + assert await cfg.option('wantref').value.get() is False + await cfg.option('wantref').value.set(True) + assert await cfg.option('wantref').value.get() is True + # + assert await cfg.option('str').value.get() == 'abc' + await cfg.option('str').value.set('def') + assert await cfg.option('str').value.get() == 'def' + # + with pytest.raises(AttributeError): + await cfg.option('gc.foo').value.get() + ## + async with await Config(descr) as cfg: + assert await cfg.option('bool').value.get() is True + assert await cfg.option('gc.name').value.get() == 'ref' + assert await cfg.option('wantframework').value.get() is False + assert not await list_sessions() @pytest.mark.asyncio async def test_not_valid_properties(): with pytest.raises(AssertionError): stroption = StrOption('str', 'Test string option', default='abc', properties='mandatory') + assert not await list_sessions() @pytest.mark.asyncio async def test_information_config(): descr = make_description() - cfg = await Config(descr) - string = 'some informations' - # - assert list(await cfg.information.list()) == [] - await cfg.information.set('info', string) - assert await cfg.information.get('info') == string - assert list(await cfg.information.list()) == ['info'] - # - with pytest.raises(ValueError): - await cfg.information.get('noinfo') - assert await cfg.information.get('noinfo', 'default') == 'default' - await cfg.information.reset('info') - with pytest.raises(ValueError): - await cfg.information.get('info') - with pytest.raises(ValueError): - await cfg.information.reset('noinfo') - assert list(await cfg.information.list()) == [] + async with await Config(descr) as cfg: + string = 'some informations' + # + assert list(await cfg.information.list()) == [] + await cfg.information.set('info', string) + assert await cfg.information.get('info') == string + assert list(await cfg.information.list()) == ['info'] + # + with pytest.raises(ValueError): + await cfg.information.get('noinfo') + assert await cfg.information.get('noinfo', 'default') == 'default' + await cfg.information.reset('info') + with pytest.raises(ValueError): + await cfg.information.get('info') + with pytest.raises(ValueError): + await cfg.information.reset('noinfo') + assert list(await cfg.information.list()) == [] + assert not await list_sessions() @pytest.mark.asyncio async def test_information_option(): descr = make_description() - cfg = await Config(descr) - string = 'some informations' - # - list(await cfg.option('gc.name').information.list()) == [] - await cfg.option('gc.name').information.set('info', string) - assert await cfg.option('gc.name').information.get('info') == string - list(await cfg.option('gc.name').information.list()) == ['info'] - # - with pytest.raises(ValueError): - await cfg.option('gc.name').information.get('noinfo') - assert await cfg.option('gc.name').information.get('noinfo', 'default') == 'default' - await cfg.option('gc.name').information.reset('info') - with pytest.raises(ValueError): - await cfg.option('gc.name').information.get('info') - with pytest.raises(ValueError): - await cfg.option('gc.name').information.reset('noinfo') - list(await cfg.option('gc.name').information.list()) == [] - # - assert await cfg.option('wantref').information.get('info') == 'default value' - await cfg.option('wantref').information.set('info', 'default value') - assert await cfg.option('wantref').information.get('info') == 'default value' - await cfg.option('wantref').information.reset('info') - assert await cfg.option('wantref').information.get('info') == 'default value' + async with await Config(descr) as cfg: + string = 'some informations' + # + list(await cfg.option('gc.name').information.list()) == [] + await cfg.option('gc.name').information.set('info', string) + assert await cfg.option('gc.name').information.get('info') == string + list(await cfg.option('gc.name').information.list()) == ['info'] + # + with pytest.raises(ValueError): + await cfg.option('gc.name').information.get('noinfo') + assert await cfg.option('gc.name').information.get('noinfo', 'default') == 'default' + await cfg.option('gc.name').information.reset('info') + with pytest.raises(ValueError): + await cfg.option('gc.name').information.get('info') + with pytest.raises(ValueError): + await cfg.option('gc.name').information.reset('noinfo') + list(await cfg.option('gc.name').information.list()) == [] + # + assert await cfg.option('wantref').information.get('info') == 'default value' + await cfg.option('wantref').information.set('info', 'default value') + assert await cfg.option('wantref').information.get('info') == 'default value' + await cfg.option('wantref').information.reset('info') + assert await cfg.option('wantref').information.get('info') == 'default value' + assert not await list_sessions() -def to_tuple(val): - ret = [] - for v in val: - t = [] - for w in v: - if isinstance(w, list): - t.append(tuple(w)) - else: - t.append(w) - ret.append(tuple(t)) - return tuple(ret) +def compare(val1, val2): + assert len(val1[0]) == len(val2[0]) + for idx1, val_1 in enumerate(val1[0]): + idx2 = val2[0].index(val_1) + assert val1[0][idx1] == val2[0][idx2] + assert val1[1][idx1] == val2[1][idx2] + if isinstance(val2[2][idx2], tuple): + assert val2[2][idx2] == tuple(val1[2][idx1]) + else: + assert val2[2][idx2] == val1[2][idx1] + assert val1[3][idx1] == val2[3][idx2] @pytest.mark.asyncio @@ -218,27 +223,28 @@ async def test_get_modified_values(): g6 = StrOption('g6', '', multi=True) d1 = OptionDescription('od', '', [g1, g2, g3, g4, g5, g6]) root = OptionDescription('root', '', [d1]) - cfg = await Config(root) - assert to_tuple(await cfg.value.exportation()) == ((), (), (), ()) - assert not await cfg.option('od.g5').option.ismulti() - assert not await cfg.option('od.g5').option.issubmulti() - await cfg.option('od.g5').value.set('yes') - assert to_tuple(await cfg.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',)) - await cfg.option('od.g4').value.set(False) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user')) - await cfg.option('od.g4').value.set(undefined) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user')) - await cfg.option('od.g4').value.reset() - assert to_tuple(await cfg.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',)) - assert await cfg.option('od.g6').option.ismulti() - await cfg.option('od.g6').value.set([undefined]) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user')) - await cfg.option('od.g6').value.set([]) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user')) - await cfg.option('od.g6').value.set(['3']) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user')) - await cfg.option('od.g6').value.set([]) - assert to_tuple(await cfg.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user')) + async with await Config(root) as cfg: + compare(await cfg.value.exportation(), ((), (), (), ())) + assert not await cfg.option('od.g5').option.ismulti() + assert not await cfg.option('od.g5').option.issubmulti() + await cfg.option('od.g5').value.set('yes') + compare(await cfg.value.exportation(), (('od.g5',), (None,), ('yes',), ('user',))) + await cfg.option('od.g4').value.set(False) + compare(await cfg.value.exportation(), (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user'))) + await cfg.option('od.g4').value.set(undefined) + compare(await cfg.value.exportation(), (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user'))) + await cfg.option('od.g4').value.reset() + compare(await cfg.value.exportation(), (('od.g5',), (None,), ('yes',), ('user',))) + assert await cfg.option('od.g6').option.ismulti() + await cfg.option('od.g6').value.set([undefined]) + compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user'))) + await cfg.option('od.g6').value.set([]) + compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))) + await cfg.option('od.g6').value.set(['3']) + compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user'))) + await cfg.option('od.g6').value.set([]) + compare(await cfg.value.exportation(), (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))) + assert not await list_sessions() @pytest.mark.asyncio @@ -246,12 +252,13 @@ async def test_get_modified_values_not_modif(config_type): g1 = StrOption('g1', '', multi=True) d1 = OptionDescription('od', '', [g1]) root = OptionDescription('root', '', [d1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('od.g1').value.get() == [] - value = await cfg.option('od.g1').value.get() - value.append('val') - assert await cfg.option('od.g1').value.get() == [] + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('od.g1').value.get() == [] + value = await cfg.option('od.g1').value.get() + value.append('val') + assert await cfg.option('od.g1').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -259,8 +266,9 @@ async def test_duplicated_option(): g1 = IntOption('g1', '', 1) g1 #in same OptionDescription - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): d1 = OptionDescription('od', '', [g1, g1]) + assert not await list_sessions() @pytest.mark.asyncio @@ -270,16 +278,19 @@ async def test_duplicated_option_diff_od(): #in different OptionDescription d2 = OptionDescription('od2', '', [g1, d1]) d2 - with pytest.raises(ConflictError): - await Config(d2) + with pytest.raises(ConflictError): + await Config(d2, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio async def test_cannot_assign_value_to_option_description(): descr = make_description() - cfg = await Config(descr) - with pytest.raises(APIError): - await cfg.option('gc').value.set(3) + async with await Config(descr) as cfg: + with pytest.raises(APIError): + await cfg.option('gc').value.set(3) + assert not await list_sessions() @pytest.mark.asyncio @@ -288,33 +299,35 @@ async def test_config_multi(config_type): i2 = IntOption('test2', '', multi=True, default_multi=1) i3 = IntOption('test3', '', default=[2], multi=True, default_multi=1) od = OptionDescription('test', '', [i1, i2, i3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.option('test1').value.get() == [] - assert await cfg.option('test2').value.get() == [] - await cfg.option('test2').value.set([undefined]) - assert await cfg.option('test2').value.get() == [1] - assert await cfg.option('test3').value.get() == [2] - await cfg.option('test3').value.set([undefined, undefined]) - assert await cfg.option('test3').value.get() == [2, 1] + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('test1').value.get() == [] + assert await cfg.option('test2').value.get() == [] + await cfg.option('test2').value.set([undefined]) + assert await cfg.option('test2').value.get() == [1] + assert await cfg.option('test3').value.get() == [2] + await cfg.option('test3').value.set([undefined, undefined]) + assert await cfg.option('test3').value.get() == [2, 1] + assert not await list_sessions() @pytest.mark.asyncio async def test_prefix_error(): i1 = IntOption('test1', '') od = OptionDescription('test', '', [i1]) - cfg = await Config(od) - await cfg.property.read_write() - await cfg.option('test1').value.set(1) - try: - await cfg.option('test1').value.set('yes') - except Exception as err: - assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('yes', _('integer'), 'test1') - try: - await cfg.option('test1').value.set('yes') - except Exception as err: - err.prefix = '' - assert str(err) == _('invalid value') + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.option('test1').value.set(1) + try: + await cfg.option('test1').value.set('yes') + except Exception as err: + assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('yes', _('integer'), 'test1') + try: + await cfg.option('test1').value.set('yes') + except Exception as err: + err.prefix = '' + assert str(err) == _('invalid value') + assert not await list_sessions() @pytest.mark.asyncio @@ -323,22 +336,23 @@ async def test_no_validation(): config_type = 'tiramisu' i1 = IntOption('test1', '') od = OptionDescription('test', '', [i1]) - config = await Config(od) - await config.property.read_write() - cfg = await get_config(config, config_type) - await cfg.option('test1').value.set(1) - with pytest.raises(ValueError): + async with await Config(od) as config: + await config.property.read_write() + cfg = await get_config(config, config_type) + await cfg.option('test1').value.set(1) + with pytest.raises(ValueError): + await cfg.option('test1').value.set('yes') + assert await cfg.option('test1').value.get() == 1 + await config.property.pop('validator') + cfg = await get_config(config, config_type) await cfg.option('test1').value.set('yes') - assert await cfg.option('test1').value.get() == 1 - await config.property.pop('validator') - cfg = await get_config(config, config_type) - await cfg.option('test1').value.set('yes') - assert await cfg.option('test1').value.get() == 'yes' - await cfg.property.add('validator') - with pytest.raises(ValueError): - await cfg.option('test1').value.get() - await cfg.option('test1').value.reset() - assert await cfg.option('test1').value.get() is None + assert await cfg.option('test1').value.get() == 'yes' + await cfg.property.add('validator') + with pytest.raises(ValueError): + await cfg.option('test1').value.get() + await cfg.option('test1').value.reset() + assert await cfg.option('test1').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -346,10 +360,11 @@ async def test_subconfig(): i = IntOption('i', '') o = OptionDescription('val', '', [i]) o2 = OptionDescription('val', '', [o]) - cfg = await Config(o2) - cfg - with pytest.raises(TypeError): - await SubConfig(i, weakref.ref(cfg)) + async with await Config(o2) as cfg: + cfg + with pytest.raises(TypeError): + await SubConfig(i, weakref.ref(cfg)) + assert not await list_sessions() @pytest.mark.asyncio @@ -360,9 +375,11 @@ async def test_config_subconfig(): i4 = IntOption('i4', '', default=2) od1 = OptionDescription('od1', '', [i1, i2, i3, i4]) od2 = OptionDescription('od2', '', [od1]) - cfg = await Config(od2, session_id='conf1') - with pytest.raises(ConfigError): - conf2 = await Config(od1, session_id='conf2') + async with await Config(od2, session_id='conf1') as cfg: + with pytest.raises(ConfigError): + conf2 = await Config(od1, session_id='conf2') + await delete_session('conf2') + assert not await list_sessions() @pytest.mark.asyncio @@ -370,8 +387,9 @@ async def test_config_invalidsession(): i = IntOption('i', '') o = OptionDescription('val', '', [i]) o2 = OptionDescription('val', '', [o]) - with pytest.raises(ValueError): + with pytest.raises(ValueError): await Config(o2, session_id=2) + assert not await list_sessions() @pytest.mark.asyncio @@ -380,11 +398,12 @@ async def test_config_od_name(config_type): s = SymLinkOption('s', i) o = OptionDescription('val', '', [i, s]) o2 = OptionDescription('val', '', [o]) - cfg = await Config(o2) - cfg = await get_config(cfg, config_type) - assert await cfg.option('val.i').option.name() == 'i' - assert await cfg.option('val.s').option.name() == 's' - assert await cfg.option('val.s').option.name(follow_symlink=True) == 'i' + async with await Config(o2) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('val.i').option.name() == 'i' + assert await cfg.option('val.s').option.name() == 's' + assert await cfg.option('val.s').option.name(follow_symlink=True) == 'i' + assert not await list_sessions() @pytest.mark.asyncio @@ -392,9 +411,10 @@ async def test_config_od_type(config_type): i = IntOption('i', '') o = OptionDescription('val', '', [i]) o2 = OptionDescription('val', '', [o]) - cfg = await Config(o2) - cfg = await get_config(cfg, config_type) - assert await cfg.option('val.i').option.type() == 'integer' + async with await Config(o2) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('val.i').option.type() == 'integer' + assert not await list_sessions() @pytest.mark.asyncio @@ -402,9 +422,10 @@ async def test_config_default(config_type): i = IntOption('i', '', 8) o = OptionDescription('val', '', [i]) o2 = OptionDescription('val', '', [o]) - cfg = await Config(o2) - cfg = await get_config(cfg, config_type) - assert await cfg.option('val.i').value.default() == 8 - await cfg.option('val.i').value.set(9) - assert await cfg.option('val.i').value.get() == 9 - assert await cfg.option('val.i').value.default() == 8 + async with await Config(o2) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('val.i').value.default() == 8 + await cfg.option('val.i').value.set(9) + assert await cfg.option('val.i').value.get() == 9 + assert await cfg.option('val.i').value.default() == 8 + assert not await list_sessions() diff --git a/tests/test_config_api.py b/tests/test_config_api.py index ef1bcb8..2bfa337 100644 --- a/tests/test_config_api.py +++ b/tests/test_config_api.py @@ -3,7 +3,7 @@ import pytest from .autopath import do_autopath do_autopath() -from .config import config_type, get_config, value_list, global_owner +from .config import config_type, get_config, value_list, global_owner, event_loop from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \ BoolOption, FilenameOption, SymLinkOption, IPOption, \ @@ -14,10 +14,10 @@ from tiramisu.storage import list_sessions import warnings -def teardown_function(function): - # test_od_not_list emit a warnings because of doesn't create a Config - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +#def teardown_function(function): +# # test_od_not_list emit a warnings because of doesn't create a Config +# with warnings.catch_warnings(record=True) as w: +# assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) def make_description(): @@ -55,15 +55,17 @@ def _is_same_opt(opt1, opt2): @pytest.mark.asyncio async def test_od_not_list(): b = BoolOption('bool', '', multi=True) - with pytest.raises(AssertionError): + with pytest.raises(AssertionError): OptionDescription('od', '', b) + assert not await list_sessions() @pytest.mark.asyncio async def test_str(): descr = make_description() - c = await Config(descr) - c # does not crash + async with await Config(descr) as cfg: + cfg # does not crash + assert not await list_sessions() @pytest.mark.asyncio @@ -74,20 +76,21 @@ async def test_make_dict(config_type): BoolOption("a", "", default=False), BoolOption("b", "", default=False, properties=('hidden',))]), IntOption("int", "", default=42)]) - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - cfg = await get_config(cfg, config_type) - d = await cfg.value.dict() - assert d == {"s1.a": False, "int": 42} - await cfg.option('int').value.set(43) - await cfg.option('s1.a').value.set(True) - d = await cfg.value.dict() - assert d == {"s1.a": True, "int": 43} - d2 = await cfg.value.dict(flatten=True) - assert d2 == {'a': True, 'int': 43} - if config_type == 'tiramisu': - assert await cfg.forcepermissive.value.dict() == {"s1.a": True, "s1.b": False, "int": 43} + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + cfg = await get_config(cfg, config_type) + d = await cfg.value.dict() + assert d == {"s1.a": False, "int": 42} + await cfg.option('int').value.set(43) + await cfg.option('s1.a').value.set(True) + d = await cfg.value.dict() + assert d == {"s1.a": True, "int": 43} + d2 = await cfg.value.dict(flatten=True) + assert d2 == {'a': True, 'int': 43} + if config_type == 'tiramisu': + assert await cfg.forcepermissive.value.dict() == {"s1.a": True, "s1.b": False, "int": 43} + assert not await list_sessions() @pytest.mark.asyncio @@ -100,13 +103,14 @@ async def test_make_dict_with_disabled(config_type): BoolOption("a", "", default=False), BoolOption("b", "", default=False)], properties=('disabled',)), IntOption("int", "", default=42)]) - cfg = await Config(descr) - await cfg.property.read_only() - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {"s1.a": False, "int": 42} - if config_type == 'tiramisu': - assert await cfg.forcepermissive.value.dict() == {"s1.a": False, "int": 42} - assert await cfg.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False} + async with await Config(descr) as cfg: + await cfg.property.read_only() + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {"s1.a": False, "int": 42} + if config_type == 'tiramisu': + assert await cfg.forcepermissive.value.dict() == {"s1.a": False, "int": 42} + assert await cfg.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False} + assert not await list_sessions() @pytest.mark.asyncio @@ -119,11 +123,12 @@ async def test_make_dict_with_disabled_in_callback(config_type): BoolOption("a", "", default=False), BoolOption("b", "", default=False)], properties=('disabled',)), IntOption("int", "", default=42)]) - cfg = await Config(descr) - await cfg.property.read_only() - cfg = await get_config(cfg, config_type) - d = await cfg.value.dict() - assert d == {"s1.a": False, "int": 42} + async with await Config(descr) as cfg: + await cfg.property.read_only() + cfg = await get_config(cfg, config_type) + d = await cfg.value.dict() + assert d == {"s1.a": False, "int": 42} + assert not await list_sessions() @pytest.mark.asyncio @@ -138,282 +143,288 @@ async def test_make_dict_fullpath(config_type): BoolOption("b", "", default=False)], properties=('disabled',)), IntOption("int", "", default=42)]), IntOption("introot", "", default=42)]) - cfg = await Config(descr) - await cfg.property.read_only() - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42} - if config_type == 'tiramisu': - # FIXME - assert await cfg.option('opt').value.dict() == {"s1.a": False, "int": 42} - assert await cfg.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42} - if config_type == 'tiramisu': - # FIXME - assert await cfg.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42} + async with await Config(descr) as cfg: + await cfg.property.read_only() + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42} + if config_type == 'tiramisu': + # FIXME + assert await cfg.option('opt').value.dict() == {"s1.a": False, "int": 42} + assert await cfg.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42} + if config_type == 'tiramisu': + # FIXME + assert await cfg.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42} + assert not await list_sessions() @pytest.mark.asyncio async def test_find_in_config(): "finds option in config" descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - await cfg.permissive.add('hidden') - ret = list(await cfg.option.find('dummy')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) - # - ret_find = await cfg.option.find('dummy', first=True) - ret = await ret_find.option.get() - _is_same_opt(ret, await cfg.option('gc.dummy').option.get()) - # - ret = list(await cfg.option.find('float')) - assert len(ret) == 2 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) - _is_same_opt(await ret[1].option.get(), await cfg.option('float').option.get()) - # - ret = await cfg.option.find('bool', first=True) - _is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) - ret = await cfg.option.find('bool', value=True, first=True) - _is_same_opt(await ret.option.get(), await cfg.option('bool').option.get()) - ret = await cfg.option.find('dummy', first=True) - _is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) - ret = await cfg.option.find('float', first=True) - _is_same_opt(await ret.option.get(), await cfg.option('gc.float').option.get()) - #FIXME cannot find an option without name - #ret = await cfg.find(bytype=ChoiceOption) - #assert len(ret) == 2 - #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name')) - #_is_same_opt(ret[1], await cfg.unwrap_from_path('objspace')) - # - #_is_same_opt(await cfg.find_first(bytype=ChoiceOption), await cfg.unwrap_from_path('gc.name')) - #ret = await cfg.find(byvalue='ref') - #assert len(ret) == 1 - #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name')) - #_is_same_opt(await cfg.find_first(byvalue='ref'), await cfg.unwrap_from_path('gc.name')) - # - ret = list(await cfg.option.find('prop')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) - # - ret = list(await cfg.option.find('prop', value=None)) - assert len(ret) == 1 - ret = list(await cfg.option.find('prop')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) - # - await cfg.property.read_write() - with pytest.raises(AttributeError): - ret = await cfg.option.find('prop') - assert await ret.option.get() - ret = list(await cfg.unrestraint.option.find(name='prop')) - assert len(ret) == 2 - _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) - _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) - # - ret = list(await cfg.forcepermissive.option.find('prop')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) - # - ret = await cfg.forcepermissive.option.find('prop', first=True) - _is_same_opt(await ret.option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) - # combinaison of filters - ret = list(await cfg.unrestraint.option.find('prop', type=BoolOption)) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) - ret = await cfg.unrestraint.option.find('prop', type=BoolOption, first=True) - _is_same_opt(await ret.option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) - # - ret = list(await cfg.option.find('dummy', value=False)) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) - # - ret = await cfg.option.find('dummy', value=False, first=True) - _is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) - #subcfgig - ret = list(await cfg.option('gc').find('dummy')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) - # - ret = list(await cfg.option('gc').find('float')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) - # - ret = list(await cfg.option('gc').find('bool')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.gc2.bool').option.get()) - ret = await cfg.option('gc').find('bool', value=False, first=True) - _is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) - # - with pytest.raises(AttributeError): - ret = await cfg.option('gc').find('bool', value=True, first=True) - assert await ret.option.get() - # - with pytest.raises(AttributeError): - ret = await cfg.option('gc').find('wantref') - await ret.option.get() - # - ret = list(await cfg.unrestraint.option('gc').find('prop')) - assert len(ret) == 2 - _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) - _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) - # - await cfg.property.read_only() - ret = list(await cfg.option('gc').find('prop')) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) - # not OptionDescription - with pytest.raises(AttributeError): - await cfg.option.find('gc', first=True) - with pytest.raises(AttributeError): - await cfg.option.find('gc2', first=True) + async with await Config(descr) as cfg: + await cfg.property.read_only() + await cfg.permissive.add('hidden') + ret = list(await cfg.option.find('dummy')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) + # + ret_find = await cfg.option.find('dummy', first=True) + ret = await ret_find.option.get() + _is_same_opt(ret, await cfg.option('gc.dummy').option.get()) + # + ret = list(await cfg.option.find('float')) + assert len(ret) == 2 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) + _is_same_opt(await ret[1].option.get(), await cfg.option('float').option.get()) + # + ret = await cfg.option.find('bool', first=True) + _is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) + ret = await cfg.option.find('bool', value=True, first=True) + _is_same_opt(await ret.option.get(), await cfg.option('bool').option.get()) + ret = await cfg.option.find('dummy', first=True) + _is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) + ret = await cfg.option.find('float', first=True) + _is_same_opt(await ret.option.get(), await cfg.option('gc.float').option.get()) + #FIXME cannot find an option without name + #ret = await cfg.find(bytype=ChoiceOption) + #assert len(ret) == 2 + #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name')) + #_is_same_opt(ret[1], await cfg.unwrap_from_path('objspace')) + # + #_is_same_opt(await cfg.find_first(bytype=ChoiceOption), await cfg.unwrap_from_path('gc.name')) + #ret = await cfg.find(byvalue='ref') + #assert len(ret) == 1 + #_is_same_opt(ret[0], await cfg.unwrap_from_path('gc.name')) + #_is_same_opt(await cfg.find_first(byvalue='ref'), await cfg.unwrap_from_path('gc.name')) + # + ret = list(await cfg.option.find('prop')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) + # + ret = list(await cfg.option.find('prop', value=None)) + assert len(ret) == 1 + ret = list(await cfg.option.find('prop')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) + # + await cfg.property.read_write() + with pytest.raises(AttributeError): + ret = await cfg.option.find('prop') + assert await ret.option.get() + ret = list(await cfg.unrestraint.option.find(name='prop')) + assert len(ret) == 2 + _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) + _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) + # + ret = list(await cfg.forcepermissive.option.find('prop')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) + # + ret = await cfg.forcepermissive.option.find('prop', first=True) + _is_same_opt(await ret.option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) + # combinaison of filters + ret = list(await cfg.unrestraint.option.find('prop', type=BoolOption)) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) + ret = await cfg.unrestraint.option.find('prop', type=BoolOption, first=True) + _is_same_opt(await ret.option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) + # + ret = list(await cfg.option.find('dummy', value=False)) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) + # + ret = await cfg.option.find('dummy', value=False, first=True) + _is_same_opt(await ret.option.get(), await cfg.option('gc.dummy').option.get()) + #subcfgig + ret = list(await cfg.option('gc').find('dummy')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.dummy').option.get()) + # + ret = list(await cfg.option('gc').find('float')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.float').option.get()) + # + ret = list(await cfg.option('gc').find('bool')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.gc2.bool').option.get()) + ret = await cfg.option('gc').find('bool', value=False, first=True) + _is_same_opt(await ret.option.get(), await cfg.option('gc.gc2.bool').option.get()) + # + with pytest.raises(AttributeError): + ret = await cfg.option('gc').find('bool', value=True, first=True) + assert await ret.option.get() + # + with pytest.raises(AttributeError): + ret = await cfg.option('gc').find('wantref') + await ret.option.get() + # + ret = list(await cfg.unrestraint.option('gc').find('prop')) + assert len(ret) == 2 + _is_same_opt(await ret[0].option.get(), await cfg.unrestraint.option('gc.gc2.prop').option.get()) + _is_same_opt(await ret[1].option.get(), await cfg.forcepermissive.option('gc.prop').option.get()) + # + await cfg.property.read_only() + ret = list(await cfg.option('gc').find('prop')) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), await cfg.option('gc.prop').option.get()) + # not OptionDescription + with pytest.raises(AttributeError): + await cfg.option.find('gc', first=True) + with pytest.raises(AttributeError): + await cfg.option.find('gc2', first=True) + assert not await list_sessions() @pytest.mark.asyncio async def test_find_multi(): b = BoolOption('bool', '', multi=True, properties=('notunique',)) o = OptionDescription('od', '', [b]) - cfg = await Config(o) - # - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True)) - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True, first=True)) - await cfg.option('bool').value.set([False]) - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True)) - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True, first=True)) - await cfg.option('bool').value.set([False, False]) - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True)) - with pytest.raises(AttributeError): - list(await cfg.option.find('bool', value=True, first=True)) - await cfg.option('bool').value.set([False, False, True]) - ret = list(await cfg.option.find('bool', value=True)) - assert len(ret) == 1 - _is_same_opt(await ret[0].option.get(), b) - ret = await cfg.option.find('bool', value=True, first=True) - _is_same_opt(await ret.option.get(), b) + async with await Config(o) as cfg: + # + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True)) + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True, first=True)) + await cfg.option('bool').value.set([False]) + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True)) + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True, first=True)) + await cfg.option('bool').value.set([False, False]) + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True)) + with pytest.raises(AttributeError): + list(await cfg.option.find('bool', value=True, first=True)) + await cfg.option('bool').value.set([False, False, True]) + ret = list(await cfg.option.find('bool', value=True)) + assert len(ret) == 1 + _is_same_opt(await ret[0].option.get(), b) + ret = await cfg.option.find('bool', value=True, first=True) + _is_same_opt(await ret.option.get(), b) + assert not await list_sessions() @pytest.mark.asyncio async def test_does_not_find_in_config(): descr = make_description() - cfg = await Config(descr) - with pytest.raises(AttributeError): - list(await cfg.option.find('IDontExist')) + async with await Config(descr) as cfg: + with pytest.raises(AttributeError): + list(await cfg.option.find('IDontExist')) + assert not await list_sessions() @pytest.mark.asyncio async def test_filename(config_type): a = FilenameOption('a', '') o = OptionDescription('o', '', [a]) - cfg = await Config(o) - # FIXME cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('/') - await cfg.option('a').value.set('/tmp') - await cfg.option('a').value.set('/tmp/') - await cfg.option('a').value.set('/tmp/text.txt') - await cfg.option('a').value.set('tmp') - await cfg.option('a').value.set('tmp/') - await cfg.option('a').value.set('tmp/text.txt') - with pytest.raises(ValueError): - await cfg.option('a').value.set('/tmp/with space.txt') - with pytest.raises(ValueError): - await cfg.option('a').value.set('/tmp/with$.txt') + async with await Config(o) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('/') + await cfg.option('a').value.set('/tmp') + await cfg.option('a').value.set('/tmp/') + await cfg.option('a').value.set('/tmp/text.txt') + await cfg.option('a').value.set('tmp') + await cfg.option('a').value.set('tmp/') + await cfg.option('a').value.set('tmp/text.txt') + with pytest.raises(ValueError): + await cfg.option('a').value.set('/tmp/with space.txt') + with pytest.raises(ValueError): + await cfg.option('a').value.set('/tmp/with$.txt') + assert not await list_sessions() @pytest.mark.asyncio async def test_invalid_option(): ChoiceOption('a', '', ('1', '2')) - with pytest.raises(TypeError): + with pytest.raises(TypeError): ChoiceOption('a', '', [1, 2]) - with pytest.raises(TypeError): + with pytest.raises(TypeError): ChoiceOption('a', '', 1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): ChoiceOption('a', '', (1,), 3) FloatOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): FloatOption('a', '', 'string') StrOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): StrOption('a', '', 1) u = StrOption('a', '') SymLinkOption('a', u) - with pytest.raises(ValueError): + with pytest.raises(ValueError): SymLinkOption('a', 'string') IPOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): IPOption('a', '', 1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): IPOption('a', '', 'string') PortOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', 'string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', '11:12:13', allow_range=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', 11111111111111111111) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False) NetworkOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): NetworkOption('a', '', 'string') NetmaskOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): NetmaskOption('a', '', 'string') BroadcastOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): BroadcastOption('a', '', 'string') DomainnameOption('a', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', 'string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', type='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', allow_ip='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', allow_without_dot='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', 1) # ChoiceOption('a', '', (1,), multi=True, default_multi=1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): ChoiceOption('a', '', (1,), default_multi=1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2) - with pytest.raises(ValueError): + with pytest.raises(ValueError): FloatOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): StrOption('a', '', multi=True, default_multi=1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): IPOption('a', '', multi=True, default_multi=1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): IPOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): PortOption('a', '', multi=True, default_multi=11111111111111111111) - with pytest.raises(ValueError): + with pytest.raises(ValueError): NetworkOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): NetmaskOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): BroadcastOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', multi=True, default_multi='string') - with pytest.raises(ValueError): + with pytest.raises(ValueError): DomainnameOption('a', '', multi=True, default_multi=1) + assert not await list_sessions() @pytest.mark.asyncio @@ -421,38 +432,40 @@ async def test_help(): stro = StrOption('s', '', multi=True) od1 = OptionDescription('o', '', [stro]) od2 = OptionDescription('o', '', [od1]) - cfg = await Config(od2) - cfg.help(_display=False) - cfg.config.help(_display=False) - cfg.option.help(_display=False) - cfg.option('o').help(_display=False) - cfg.option('o.s').help(_display=False) + async with await Config(od2) as cfg: + cfg.help(_display=False) + cfg.config.help(_display=False) + cfg.option.help(_display=False) + cfg.option('o').help(_display=False) + cfg.option('o.s').help(_display=False) + assert not await list_sessions() @pytest.mark.asyncio async def test_config_reset(): descr = make_description() - cfg = await Config(descr) - await cfg.owner.set('test') - assert await cfg.owner.get() == 'test' - assert not await cfg.option('gc.gc2.bool').value.get() - assert not await cfg.option('boolop').property.get() - assert not await cfg.option('boolop').permissive.get() - assert not await cfg.option('wantref').information.get('info', None) - # - await cfg.option('gc.gc2.bool').value.set(True) - await cfg.option('boolop').property.add('test') - await cfg.option('float').permissive.set(frozenset(['test'])) - await cfg.option('wantref').information.set('info', 'info') - assert await cfg.option('gc.gc2.bool').value.get() - assert await cfg.option('boolop').property.get() - assert await cfg.option('float').permissive.get() - assert await cfg.option('wantref').information.get('info', None) - # - assert await cfg.owner.get() == 'test' - await cfg.config.reset() - assert await cfg.owner.get() == 'test' - assert not await cfg.option('gc.gc2.bool').value.get() - assert not await cfg.option('boolop').property.get() - assert not await cfg.option('float').permissive.get() - assert not await cfg.option('wantref').information.get('info', None) + async with await Config(descr) as cfg: + await cfg.owner.set('test') + assert await cfg.owner.get() == 'test' + assert not await cfg.option('gc.gc2.bool').value.get() + assert not await cfg.option('boolop').property.get() + assert not await cfg.option('boolop').permissive.get() + assert not await cfg.option('wantref').information.get('info', None) + # + await cfg.option('gc.gc2.bool').value.set(True) + await cfg.option('boolop').property.add('test') + await cfg.option('float').permissive.set(frozenset(['test'])) + await cfg.option('wantref').information.set('info', 'info') + assert await cfg.option('gc.gc2.bool').value.get() + assert await cfg.option('boolop').property.get() + assert await cfg.option('float').permissive.get() + assert await cfg.option('wantref').information.get('info', None) + # + assert await cfg.owner.get() == 'test' + await cfg.config.reset() + assert await cfg.owner.get() == 'test' + assert not await cfg.option('gc.gc2.bool').value.get() + assert not await cfg.option('boolop').property.get() + assert not await cfg.option('float').permissive.get() + assert not await cfg.option('wantref').information.get('info', None) + assert not await list_sessions() diff --git a/tests/test_config_domain.py b/tests/test_config_domain.py index 114afdd..fa256e6 100644 --- a/tests/test_config_domain.py +++ b/tests/test_config_domain.py @@ -9,10 +9,7 @@ from tiramisu import Config, DomainnameOption, EmailOption, URLOption, OptionDes from tiramisu.error import ValueWarning from tiramisu.i18n import _ from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop @pytest.mark.asyncio @@ -22,86 +19,88 @@ async def test_domainname(config_type): g = DomainnameOption('g', '', allow_ip=True) h = DomainnameOption('h', '', allow_cidr_network=True) od = OptionDescription('a', '', [d, f, g, h]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - # - await cfg.option('d').value.set('toto.com') - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto') - await cfg.option('d').value.set('toto3.com') - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto_super.com') - await cfg.option('d').value.set('toto-.com') - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto..com') - # - await cfg.option('f').value.set('toto.com') - await cfg.option('f').value.set('toto') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') - with pytest.raises(ValueError): - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') - with pytest.raises(ValueError): - await cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien') - await cfg.option('f').value.set('d') - await cfg.option('f').value.set('d.t') - # - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('f').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('f').value.set('192.168.1.0/24') - # - await cfg.option('g').value.set('toto.com') - await cfg.option('g').value.set('192.168.1.0') - await cfg.option('g').value.set('192.168.1.29') - with pytest.raises(ValueError): - await cfg.option('g').value.set('192.168.1.0/24') - # - await cfg.option('h').value.set('toto.com') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('h').value.set('192.168.1.0') - with pytest.raises(ValueError): - await cfg.option('h').value.set('192.168.1.29') - # it's a network address - await cfg.option('h').value.set('192.168.1.0/24') - # but not here - with pytest.raises(ValueError): - await cfg.option('h').value.set('192.168.1.1/24') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + # + await cfg.option('d').value.set('toto.com') + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto') + await cfg.option('d').value.set('toto3.com') + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto_super.com') + await cfg.option('d').value.set('toto-.com') + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto..com') + # + await cfg.option('f').value.set('toto.com') + await cfg.option('f').value.set('toto') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') + with pytest.raises(ValueError): + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') + with pytest.raises(ValueError): + await cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien') + await cfg.option('f').value.set('d') + await cfg.option('f').value.set('d.t') + # + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('f').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('f').value.set('192.168.1.0/24') + # + await cfg.option('g').value.set('toto.com') + await cfg.option('g').value.set('192.168.1.0') + await cfg.option('g').value.set('192.168.1.29') + with pytest.raises(ValueError): + await cfg.option('g').value.set('192.168.1.0/24') + # + await cfg.option('h').value.set('toto.com') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('h').value.set('192.168.1.0') + with pytest.raises(ValueError): + await cfg.option('h').value.set('192.168.1.29') + # it's a network address + await cfg.option('h').value.set('192.168.1.0/24') + # but not here + with pytest.raises(ValueError): + await cfg.option('h').value.set('192.168.1.1/24') + assert not await list_sessions() @pytest.mark.asyncio async def test_domainname_upper(config_type): d = DomainnameOption('d', '') od = OptionDescription('a', '', [d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('d').value.set('toto.com') - msg = _('some characters are uppercase') - has_error = False - try: - await cfg.option('d').value.set('TOTO.COM') - except ValueError as err: - if config_type != 'tiramisu-api': - # FIXME - assert msg in str(err) - has_error = True - assert has_error is True - has_error = False - try: - await cfg.option('d').value.set('toTo.com') - except ValueError as err: - if config_type != 'tiramisu-api': - # FIXME - assert msg in str(err) - has_error = True - assert has_error is True + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('d').value.set('toto.com') + msg = _('some characters are uppercase') + has_error = False + try: + await cfg.option('d').value.set('TOTO.COM') + except ValueError as err: + if config_type != 'tiramisu-api': + # FIXME + assert msg in str(err) + has_error = True + assert has_error is True + has_error = False + try: + await cfg.option('d').value.set('toTo.com') + except ValueError as err: + if config_type != 'tiramisu-api': + # FIXME + assert msg in str(err) + has_error = True + assert has_error is True + assert not await list_sessions() @pytest.mark.asyncio @@ -111,45 +110,46 @@ async def test_domainname_warning(config_type): g = DomainnameOption('g', '', allow_ip=True, warnings_only=True) od = OptionDescription('a', '', [d, f, g]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('d').value.set('toto.com') - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto') - await cfg.option('d').value.set('toto3.com') - if config_type != 'tiramisu-api': - # FIXME + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('d').value.set('toto.com') + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto') + await cfg.option('d').value.set('toto3.com') + if config_type != 'tiramisu-api': + # FIXME + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.set('toto_super.com') + assert len(w) == 1 with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set('toto_super.com') - assert len(w) == 1 - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set('toto-.com') - assert len(w) == 0 - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto..com') - # - await cfg.option('f').value.set('toto.com') - await cfg.option('f').value.set('toto') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') - with pytest.raises(ValueError): - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx') - await cfg.option('f').value.set('d') - await cfg.option('f').value.set('d.t') - # - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('f').value.set('192.168.1.1') - await cfg.option('g').value.set('toto.com') - await cfg.option('g').value.set('192.168.1.0') - await cfg.option('g').value.set('192.168.1.29') + await cfg.option('d').value.set('toto-.com') + assert len(w) == 0 + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto..com') + # + await cfg.option('f').value.set('toto.com') + await cfg.option('f').value.set('toto') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea') + with pytest.raises(ValueError): + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd') + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx') + await cfg.option('f').value.set('d') + await cfg.option('f').value.set('d.t') + # + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('f').value.set('192.168.1.1') + await cfg.option('g').value.set('toto.com') + await cfg.option('g').value.set('192.168.1.0') + await cfg.option('g').value.set('192.168.1.29') + assert not await list_sessions() @pytest.mark.asyncio @@ -159,13 +159,14 @@ async def test_special_domain_name(config_type): d = DomainnameOption('d', '') e = DomainnameOption('e', '', type='netbios') od = OptionDescription('a', '', [d, e]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('d').value.set('1toto.com') - await cfg.option('d').value.set('123toto.com') - await cfg.option('e').value.set('toto') - await cfg.option('e').value.set('1toto') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('d').value.set('1toto.com') + await cfg.option('d').value.set('123toto.com') + await cfg.option('e').value.set('toto') + await cfg.option('e').value.set('1toto') + assert not await list_sessions() @pytest.mark.asyncio @@ -173,14 +174,15 @@ async def test_domainname_netbios(config_type): d = DomainnameOption('d', '', type='netbios') e = DomainnameOption('e', '', "toto", type='netbios') od = OptionDescription('a', '', [d, e]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto.com') - await cfg.option('d').value.set('toto') - with pytest.raises(ValueError): - await cfg.option('d').value.set('domainnametoolong') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto.com') + await cfg.option('d').value.set('toto') + with pytest.raises(ValueError): + await cfg.option('d').value.set('domainnametoolong') + assert not await list_sessions() @pytest.mark.asyncio @@ -188,70 +190,73 @@ async def test_domainname_hostname(config_type): d = DomainnameOption('d', '', type='hostname') e = DomainnameOption('e', '', "toto", type='hostname') od = OptionDescription('a', '', [d, e]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('d').value.set('toto.com') - await cfg.option('d').value.set('toto') - await cfg.option('d').value.set('domainnametoolong') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('d').value.set('toto.com') + await cfg.option('d').value.set('toto') + await cfg.option('d').value.set('domainnametoolong') + assert not await list_sessions() @pytest.mark.asyncio async def test_email(config_type): e = EmailOption('e', '') od = OptionDescription('a', '', [e]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('e').value.set('foo-bar.baz@example.com') - await cfg.option('e').value.set('root@foo.com') - await cfg.option('e').value.set('root@domain') - with pytest.raises(ValueError): - await cfg.option('e').value.set(1) - with pytest.raises(ValueError): - await cfg.option('e').value.set('root') - with pytest.raises(ValueError): - await cfg.option('e').value.set('root[]@domain') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('e').value.set('foo-bar.baz@example.com') + await cfg.option('e').value.set('root@foo.com') + await cfg.option('e').value.set('root@domain') + with pytest.raises(ValueError): + await cfg.option('e').value.set(1) + with pytest.raises(ValueError): + await cfg.option('e').value.set('root') + with pytest.raises(ValueError): + await cfg.option('e').value.set('root[]@domain') + assert not await list_sessions() @pytest.mark.asyncio async def test_url(config_type): u = URLOption('u', '') od = OptionDescription('a', '', [u]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('u').value.set('http://foo.com') - await cfg.option('u').value.set('https://foo.com') - await cfg.option('u').value.set('https://foo.com/') - with pytest.raises(ValueError): - await cfg.option('u').value.set(1) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('u').value.set('ftp://foo.com') - with pytest.raises(ValueError): - await cfg.option('u').value.set('foo.com') - with pytest.raises(ValueError): - await cfg.option('u').value.set(':/foo.com') - with pytest.raises(ValueError): - await cfg.option('u').value.set('foo.com/http://') - await cfg.option('u').value.set('https://foo.com/index.html') - await cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('u').value.set('https://foo.com/index\\n.html') - await cfg.option('u').value.set('https://foo.com:8443') - await cfg.option('u').value.set('https://foo.com:8443/') - await cfg.option('u').value.set('https://foo.com:8443/index.html') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('u').value.set('https://foo.com:84438989') - await cfg.option('u').value.set('https://foo.com:8443/INDEX') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('u').value.set('https://FOO.COM:8443') + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('u').value.set('http://foo.com') + await cfg.option('u').value.set('https://foo.com') + await cfg.option('u').value.set('https://foo.com/') + with pytest.raises(ValueError): + await cfg.option('u').value.set(1) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('u').value.set('ftp://foo.com') + with pytest.raises(ValueError): + await cfg.option('u').value.set('foo.com') + with pytest.raises(ValueError): + await cfg.option('u').value.set(':/foo.com') + with pytest.raises(ValueError): + await cfg.option('u').value.set('foo.com/http://') + await cfg.option('u').value.set('https://foo.com/index.html') + await cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('u').value.set('https://foo.com/index\\n.html') + await cfg.option('u').value.set('https://foo.com:8443') + await cfg.option('u').value.set('https://foo.com:8443/') + await cfg.option('u').value.set('https://foo.com:8443/index.html') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('u').value.set('https://foo.com:84438989') + await cfg.option('u').value.set('https://foo.com:8443/INDEX') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('u').value.set('https://FOO.COM:8443') + assert not await list_sessions() diff --git a/tests/test_config_ip.py b/tests/test_config_ip.py index 8549111..947b5dc 100644 --- a/tests/test_config_ip.py +++ b/tests/test_config_ip.py @@ -1,6 +1,6 @@ from .autopath import do_autopath do_autopath() -from .config import config_type, get_config, value_list, global_owner +from .config import config_type, get_config, value_list, global_owner, event_loop import warnings import pytest @@ -10,10 +10,6 @@ from tiramisu.error import ValueWarning from tiramisu.storage import list_sessions -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - @pytest.mark.asyncio async def test_ip(config_type): a = IPOption('a', '') @@ -21,37 +17,38 @@ async def test_ip(config_type): d = IPOption('d', '', warnings_only=True, private_only=True) warnings.simplefilter("always", ValueWarning) od = OptionDescription('od', '', [a, b, d]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('192.168.1.1') - await cfg.option('a').value.set('192.168.1.0') - await cfg.option('a').value.set('88.88.88.88') - await cfg.option('a').value.set('0.0.0.0') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('a').value.set('255.255.255.0') - await cfg.option('b').value.set('192.168.1.1') - await cfg.option('b').value.set('192.168.1.0') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('b').value.set('88.88.88.88') - await cfg.option('b').value.set('0.0.0.0') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('b').value.set('255.255.255.0') - with pytest.raises(ValueError): - await cfg.option('a').value.set('333.0.1.20') + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('192.168.1.1') + await cfg.option('a').value.set('192.168.1.0') + await cfg.option('a').value.set('88.88.88.88') + await cfg.option('a').value.set('0.0.0.0') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('a').value.set('255.255.255.0') + await cfg.option('b').value.set('192.168.1.1') + await cfg.option('b').value.set('192.168.1.0') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('b').value.set('88.88.88.88') + await cfg.option('b').value.set('0.0.0.0') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('b').value.set('255.255.255.0') + with pytest.raises(ValueError): + await cfg.option('a').value.set('333.0.1.20') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - IPOption('a', 'ip', default='192.000.023.01') - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set('88.88.88.88') - assert len(w) == 1 + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + IPOption('a', 'ip', default='192.000.023.01') + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.set('88.88.88.88') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -60,26 +57,28 @@ async def test_ip_cidr(): c = IPOption('c', '', private_only=True) warnings.simplefilter("always", ValueWarning) od = OptionDescription('od', '', [b, c]) - cfg = await Config(od) - with pytest.raises(ValueError): - await cfg.option('b').value.set('192.168.1.1') - await cfg.option('b').value.set('192.168.1.1/24') - with pytest.raises(ValueError): - await cfg.option('b').value.set('192.168.1.1/32') - # - await cfg.option('c').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.1/24') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.1/32') + async with await Config(od) as cfg: + with pytest.raises(ValueError): + await cfg.option('b').value.set('192.168.1.1') + await cfg.option('b').value.set('192.168.1.1/24') + with pytest.raises(ValueError): + await cfg.option('b').value.set('192.168.1.1/32') + # + await cfg.option('c').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.1/24') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.1/32') + assert not await list_sessions() @pytest.mark.asyncio async def test_ip_default(): a = IPOption('a', '', '88.88.88.88') od = OptionDescription('od', '', [a]) - cfg = await Config(od) - await cfg.option('a').value.get() == '88.88.88.88' + async with await Config(od) as cfg: + await cfg.option('a').value.get() == '88.88.88.88' + assert not await list_sessions() @pytest.mark.asyncio @@ -89,18 +88,19 @@ async def test_ip_reserved(config_type): c = IPOption('c', '', warnings_only=True) od = OptionDescription('od', '', [a, b, c]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('a').value.set('240.94.1.1') - await cfg.option('b').value.set('240.94.1.1') - if config_type != 'tiramisu-api': - # FIXME - with warnings.catch_warnings(record=True) as w: - await cfg.option('c').value.set('240.94.1.1') - assert len(w) == 1 + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('a').value.set('240.94.1.1') + await cfg.option('b').value.set('240.94.1.1') + if config_type != 'tiramisu-api': + # FIXME + with warnings.catch_warnings(record=True) as w: + await cfg.option('c').value.set('240.94.1.1') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -109,52 +109,54 @@ async def test_network(config_type): b = NetworkOption('b', '', warnings_only=True) od = OptionDescription('od', '', [a, b]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('192.168.1.1') - await cfg.option('a').value.set('192.168.1.0') - await cfg.option('a').value.set('88.88.88.88') - await cfg.option('a').value.set('0.0.0.0') - with pytest.raises(ValueError): - await cfg.option('a').value.set(1) - with pytest.raises(ValueError): - await cfg.option('a').value.set('1.1.1.1.1') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('a').value.set('255.255.255.0') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.001.0') - with pytest.raises(ValueError): - await cfg.option('a').value.set('333.168.1.1') - if config_type != 'tiramisu-api': - # FIXME - with warnings.catch_warnings(record=True) as w: - await cfg.option('b').value.set('255.255.255.0') - assert len(w) == 1 + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('192.168.1.1') + await cfg.option('a').value.set('192.168.1.0') + await cfg.option('a').value.set('88.88.88.88') + await cfg.option('a').value.set('0.0.0.0') + with pytest.raises(ValueError): + await cfg.option('a').value.set(1) + with pytest.raises(ValueError): + await cfg.option('a').value.set('1.1.1.1.1') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('a').value.set('255.255.255.0') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.001.0') + with pytest.raises(ValueError): + await cfg.option('a').value.set('333.168.1.1') + if config_type != 'tiramisu-api': + # FIXME + with warnings.catch_warnings(record=True) as w: + await cfg.option('b').value.set('255.255.255.0') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_network_cidr(config_type): a = NetworkOption('a', '', cidr=True) od = OptionDescription('od', '', [a]) - cfg = await Config(od) - # FIXME cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('192.168.1.1/32') - await cfg.option('a').value.set('192.168.1.0/24') - await cfg.option('a').value.set('88.88.88.88/32') - await cfg.option('a').value.set('0.0.0.0/0') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.1/24') - with pytest.raises(ValueError): - await cfg.option('a').value.set('2001:db00::0/24') + async with await Config(od) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('192.168.1.1/32') + await cfg.option('a').value.set('192.168.1.0/24') + await cfg.option('a').value.set('88.88.88.88/32') + await cfg.option('a').value.set('0.0.0.0/0') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.1/24') + with pytest.raises(ValueError): + await cfg.option('a').value.set('2001:db00::0/24') + assert not await list_sessions() @pytest.mark.asyncio async def test_network_invalid(): - with pytest.raises(ValueError): + with pytest.raises(ValueError): NetworkOption('a', '', default='toto') @@ -162,46 +164,48 @@ async def test_network_invalid(): async def test_netmask(config_type): a = NetmaskOption('a', '') od = OptionDescription('od', '', [a]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.1.1') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.0') - with pytest.raises(ValueError): - await cfg.option('a').value.set('88.88.88.88') - with pytest.raises(ValueError): - await cfg.option('a').value.set('255.255.255.000') - with pytest.raises(ValueError): - await cfg.option('a').value.set(2) - await cfg.option('a').value.set('0.0.0.0') - await cfg.option('a').value.set('255.255.255.0') + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.1.1') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.0') + with pytest.raises(ValueError): + await cfg.option('a').value.set('88.88.88.88') + with pytest.raises(ValueError): + await cfg.option('a').value.set('255.255.255.000') + with pytest.raises(ValueError): + await cfg.option('a').value.set(2) + await cfg.option('a').value.set('0.0.0.0') + await cfg.option('a').value.set('255.255.255.0') + assert not await list_sessions() @pytest.mark.asyncio async def test_broadcast(config_type): a = BroadcastOption('a', '') od = OptionDescription('od', '', [a]) - cfg = await Config(od) - # FIXME cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.1.255.1') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.001.255') - with pytest.raises(ValueError): - await cfg.option('a').value.set('192.168.0.300') - with pytest.raises(ValueError): - await cfg.option('a').value.set(1) - with pytest.raises(ValueError): - await cfg.option('a').value.set(2) - with pytest.raises(ValueError): - await cfg.option('a').value.set('2001:db8::1') - await cfg.option('a').value.set('0.0.0.0') - await cfg.option('a').value.set('255.255.255.0') + async with await Config(od) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.1.255.1') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.001.255') + with pytest.raises(ValueError): + await cfg.option('a').value.set('192.168.0.300') + with pytest.raises(ValueError): + await cfg.option('a').value.set(1) + with pytest.raises(ValueError): + await cfg.option('a').value.set(2) + with pytest.raises(ValueError): + await cfg.option('a').value.set('2001:db8::1') + await cfg.option('a').value.set('0.0.0.0') + await cfg.option('a').value.set('255.255.255.0') + assert not await list_sessions() @pytest.mark.asyncio @@ -213,81 +217,82 @@ async def test_port(config_type): e = PortOption('e', '', allow_zero=True, allow_private=True) f = PortOption('f', '', allow_private=True) od = OptionDescription('od', '', [a, b, c, d, e, f]) - cfg = await Config(od) - # FIXME cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('a').value.set('0') - await cfg.option('a').value.set('1') - await cfg.option('a').value.set('1023') - await cfg.option('a').value.set('1024') - await cfg.option('a').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('a').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('a').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('a').value.set('65536') + async with await Config(od) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('a').value.set('0') + await cfg.option('a').value.set('1') + await cfg.option('a').value.set('1023') + await cfg.option('a').value.set('1024') + await cfg.option('a').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('a').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('a').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('a').value.set('65536') - await cfg.option('b').value.set('0') - await cfg.option('b').value.set('1') - await cfg.option('b').value.set('1023') - await cfg.option('b').value.set('1024') - await cfg.option('b').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('b').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('b').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('b').value.set('65536') + await cfg.option('b').value.set('0') + await cfg.option('b').value.set('1') + await cfg.option('b').value.set('1023') + await cfg.option('b').value.set('1024') + await cfg.option('b').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('b').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('b').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('b').value.set('65536') - await cfg.option('c').value.set('0') - await cfg.option('c').value.set('1') - await cfg.option('c').value.set('1023') - with pytest.raises(ValueError): - await cfg.option('c').value.set('1024') - with pytest.raises(ValueError): - await cfg.option('c').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('c').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('c').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('c').value.set('65536') + await cfg.option('c').value.set('0') + await cfg.option('c').value.set('1') + await cfg.option('c').value.set('1023') + with pytest.raises(ValueError): + await cfg.option('c').value.set('1024') + with pytest.raises(ValueError): + await cfg.option('c').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('c').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('c').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('c').value.set('65536') - await cfg.option('d').value.set('0') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1023') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1024') - with pytest.raises(ValueError): - await cfg.option('d').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('d').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('d').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('d').value.set('65536') + await cfg.option('d').value.set('0') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1023') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1024') + with pytest.raises(ValueError): + await cfg.option('d').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('d').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('d').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('d').value.set('65536') - await cfg.option('e').value.set('0') - await cfg.option('e').value.set('1') - await cfg.option('e').value.set('1023') - await cfg.option('e').value.set('1024') - await cfg.option('e').value.set('49151') - await cfg.option('e').value.set('49152') - await cfg.option('e').value.set('65535') + await cfg.option('e').value.set('0') + await cfg.option('e').value.set('1') + await cfg.option('e').value.set('1023') + await cfg.option('e').value.set('1024') + await cfg.option('e').value.set('49151') + await cfg.option('e').value.set('49152') + await cfg.option('e').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('f').value.set('0') - await cfg.option('f').value.set('1') - await cfg.option('f').value.set('1023') - await cfg.option('f').value.set('1024') - await cfg.option('f').value.set('49151') - await cfg.option('f').value.set('49152') - await cfg.option('f').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('f').value.set('65536') + with pytest.raises(ValueError): + await cfg.option('f').value.set('0') + await cfg.option('f').value.set('1') + await cfg.option('f').value.set('1023') + await cfg.option('f').value.set('1024') + await cfg.option('f').value.set('49151') + await cfg.option('f').value.set('49152') + await cfg.option('f').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('f').value.set('65536') + assert not await list_sessions() @pytest.mark.asyncio @@ -299,102 +304,103 @@ async def test_port_range(config_type): e = PortOption('e', '', allow_range=True, allow_zero=True, allow_private=True) f = PortOption('f', '', allow_range=True, allow_private=True) od = OptionDescription('od', '', [a, b, c, d, e, f]) - cfg = await Config(od) - # FIXME cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('a').value.set('0') - await cfg.option('a').value.set('1') - await cfg.option('a').value.set('1023') - await cfg.option('a').value.set('1024') - await cfg.option('a').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('a').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('a').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('a').value.set('65536') - await cfg.option('a').value.set('1:49151') - with pytest.raises(ValueError): - await cfg.option('a').value.set('0:49151') - with pytest.raises(ValueError): - await cfg.option('a').value.set('1:49152') + async with await Config(od) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('a').value.set('0') + await cfg.option('a').value.set('1') + await cfg.option('a').value.set('1023') + await cfg.option('a').value.set('1024') + await cfg.option('a').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('a').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('a').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('a').value.set('65536') + await cfg.option('a').value.set('1:49151') + with pytest.raises(ValueError): + await cfg.option('a').value.set('0:49151') + with pytest.raises(ValueError): + await cfg.option('a').value.set('1:49152') - await cfg.option('b').value.set('0') - await cfg.option('b').value.set('1') - await cfg.option('b').value.set('1023') - await cfg.option('b').value.set('1024') - await cfg.option('b').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('b').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('b').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('b').value.set('65536') - await cfg.option('b').value.set('0:49151') - with pytest.raises(ValueError): - await cfg.option('b').value.set('0:49152') + await cfg.option('b').value.set('0') + await cfg.option('b').value.set('1') + await cfg.option('b').value.set('1023') + await cfg.option('b').value.set('1024') + await cfg.option('b').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('b').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('b').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('b').value.set('65536') + await cfg.option('b').value.set('0:49151') + with pytest.raises(ValueError): + await cfg.option('b').value.set('0:49152') - await cfg.option('c').value.set('0') - await cfg.option('c').value.set('1') - await cfg.option('c').value.set('1023') - with pytest.raises(ValueError): - await cfg.option('c').value.set('1024') - with pytest.raises(ValueError): - await cfg.option('c').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('c').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('c').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('c').value.set('65536') - await cfg.option('c').value.set('0:1023') - with pytest.raises(ValueError): - await cfg.option('c').value.set('0:1024') + await cfg.option('c').value.set('0') + await cfg.option('c').value.set('1') + await cfg.option('c').value.set('1023') + with pytest.raises(ValueError): + await cfg.option('c').value.set('1024') + with pytest.raises(ValueError): + await cfg.option('c').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('c').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('c').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('c').value.set('65536') + await cfg.option('c').value.set('0:1023') + with pytest.raises(ValueError): + await cfg.option('c').value.set('0:1024') - await cfg.option('d').value.set('0') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1023') - with pytest.raises(ValueError): - await cfg.option('d').value.set('1024') - with pytest.raises(ValueError): - await cfg.option('d').value.set('49151') - with pytest.raises(ValueError): - await cfg.option('d').value.set('49152') - with pytest.raises(ValueError): - await cfg.option('d').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('d').value.set('65536') - with pytest.raises(ValueError): - await cfg.option('d').value.set('0:0') - with pytest.raises(ValueError): - await cfg.option('d').value.set('0:1') + await cfg.option('d').value.set('0') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1023') + with pytest.raises(ValueError): + await cfg.option('d').value.set('1024') + with pytest.raises(ValueError): + await cfg.option('d').value.set('49151') + with pytest.raises(ValueError): + await cfg.option('d').value.set('49152') + with pytest.raises(ValueError): + await cfg.option('d').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('d').value.set('65536') + with pytest.raises(ValueError): + await cfg.option('d').value.set('0:0') + with pytest.raises(ValueError): + await cfg.option('d').value.set('0:1') - await cfg.option('e').value.set('0') - await cfg.option('e').value.set('1') - await cfg.option('e').value.set('1023') - await cfg.option('e').value.set('1024') - await cfg.option('e').value.set('49151') - await cfg.option('e').value.set('49152') - await cfg.option('e').value.set('65535') - await cfg.option('e').value.set('0:65535') - with pytest.raises(ValueError): - await cfg.option('e').value.set('0:65536') + await cfg.option('e').value.set('0') + await cfg.option('e').value.set('1') + await cfg.option('e').value.set('1023') + await cfg.option('e').value.set('1024') + await cfg.option('e').value.set('49151') + await cfg.option('e').value.set('49152') + await cfg.option('e').value.set('65535') + await cfg.option('e').value.set('0:65535') + with pytest.raises(ValueError): + await cfg.option('e').value.set('0:65536') - with pytest.raises(ValueError): - await cfg.option('f').value.set('0') - await cfg.option('f').value.set('1') - await cfg.option('f').value.set('1023') - await cfg.option('f').value.set('1024') - await cfg.option('f').value.set('49151') - await cfg.option('f').value.set('49152') - await cfg.option('f').value.set('65535') - with pytest.raises(ValueError): - await cfg.option('f').value.set('65536') - await cfg.option('f').value.set('1:65535') - await cfg.option('f').value.set('3:4') - with pytest.raises(ValueError): - await cfg.option('f').value.set('0:65535') - with pytest.raises(ValueError): - await cfg.option('f').value.set('4:3') + with pytest.raises(ValueError): + await cfg.option('f').value.set('0') + await cfg.option('f').value.set('1') + await cfg.option('f').value.set('1023') + await cfg.option('f').value.set('1024') + await cfg.option('f').value.set('49151') + await cfg.option('f').value.set('49152') + await cfg.option('f').value.set('65535') + with pytest.raises(ValueError): + await cfg.option('f').value.set('65536') + await cfg.option('f').value.set('1:65535') + await cfg.option('f').value.set('3:4') + with pytest.raises(ValueError): + await cfg.option('f').value.set('0:65535') + with pytest.raises(ValueError): + await cfg.option('f').value.set('4:3') + assert not await list_sessions() diff --git a/tests/test_dereference.py b/tests/test_dereference.py index 573951c..515ef6d 100644 --- a/tests/test_dereference.py +++ b/tests/test_dereference.py @@ -8,10 +8,7 @@ from tiramisu import BoolOption, IntOption, StrOption, IPOption, NetmaskOption, SymLinkOption, OptionDescription, DynOptionDescription, submulti, \ Config, GroupConfig, MetaConfig, Params, ParamOption, Calculation from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop IS_DEREFABLE = True @@ -25,40 +22,44 @@ def funcname(*args, **kwargs): async def test_deref_storage(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(c._config_bag.context.cfgimpl_get_values()._p_) - del(c) + async with await Config(o) as cfg: + w = weakref.ref(cfg._config_bag.context.cfgimpl_get_values()._p_) + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio async def test_deref_value(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(c._config_bag.context.cfgimpl_get_values()) - del(c) + async with await Config(o) as cfg: + w = weakref.ref(cfg._config_bag.context.cfgimpl_get_values()) + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio async def test_deref_setting(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(c._config_bag.context.cfgimpl_get_settings()) - del(c) + async with await Config(o) as cfg: + w = weakref.ref(cfg._config_bag.context.cfgimpl_get_settings()) + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio async def test_deref_config(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(c) - del(c) + async with await Config(o) as cfg: + w = weakref.ref(cfg) + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -75,6 +76,7 @@ async def test_deref_option(): return del(o) assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -88,6 +90,7 @@ async def test_deref_optiondescription(): assert w() is not None del(o) assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -102,6 +105,7 @@ async def test_deref_option_cache(): assert w() is not None del(o) assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -116,6 +120,7 @@ async def test_deref_optiondescription_cache(): assert w() is not None del(o) assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -124,14 +129,15 @@ async def test_deref_option_config(): return b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(b) - del(b) - assert w() is not None - del(o) - assert w() is not None - del(c) + async with await Config(o) as cfg: + w = weakref.ref(b) + del(b) + assert w() is not None + del(o) + assert w() is not None + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -140,14 +146,15 @@ async def test_deref_optiondescription_config(): return b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - c = await Config(o) - w = weakref.ref(o) - del(b) - assert w() is not None - del(o) - assert w() is not None - del(c) + async with await Config(o) as cfg: + w = weakref.ref(o) + del(b) + assert w() is not None + del(o) + assert w() is not None + del cfg assert w() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -157,29 +164,30 @@ async def test_deref_validator(): a = StrOption('a', '', default='yes') b = StrOption('b', '', validators=[Calculation(funcname, Params(ParamOption(a)))], default='val') od = OptionDescription('root', '', [a, b]) - cfg = await Config(od) - w = weakref.ref(a) - x = weakref.ref(b) - y = weakref.ref(od) - z = weakref.ref(cfg) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(a) - del(b) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(od) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(cfg) + async with await Config(od) as cfg: + w = weakref.ref(a) + x = weakref.ref(b) + y = weakref.ref(od) + z = weakref.ref(cfg) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(a) + del(b) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(od) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del cfg assert y() is None assert z() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -189,29 +197,30 @@ async def test_deref_callback(): a = StrOption('a', "", 'val') b = StrOption('b', "", Calculation(funcname, Params((ParamOption(a),)))) od = OptionDescription('root', '', [a, b]) - cfg = await Config(od) - w = weakref.ref(a) - x = weakref.ref(b) - y = weakref.ref(od) - z = weakref.ref(cfg) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(a) - del(b) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(od) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(cfg) + async with await Config(od) as cfg: + w = weakref.ref(a) + x = weakref.ref(b) + y = weakref.ref(od) + z = weakref.ref(cfg) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(a) + del(b) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(od) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del cfg assert y() is None assert z() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -221,29 +230,30 @@ async def test_deref_symlink(): a = BoolOption("a", "", default=False) b = SymLinkOption("b", a) od = OptionDescription('root', '', [a, b]) - cfg = await Config(od) - w = weakref.ref(a) - x = weakref.ref(b) - y = weakref.ref(od) - z = weakref.ref(cfg) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(a) - del(b) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(od) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(cfg) + async with await Config(od) as cfg: + w = weakref.ref(a) + x = weakref.ref(b) + y = weakref.ref(od) + z = weakref.ref(cfg) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(a) + del(b) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(od) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del cfg assert y() is None assert z() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -254,27 +264,28 @@ async def test_deref_dyn(): b = StrOption('b', '') dod = DynOptionDescription('dod', '', [b], suffixes=Calculation(funcname, Params((ParamOption(a),)))) od = OptionDescription('od', '', [dod, a]) - cfg = await Config(od) - w = weakref.ref(a) - x = weakref.ref(b) - y = weakref.ref(od) - z = weakref.ref(cfg) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(a) - del(b) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(od) - del(dod) - assert w() is not None - assert x() is not None - assert w() is not None - assert x() is not None - del(cfg) + async with await Config(od) as cfg: + w = weakref.ref(a) + x = weakref.ref(b) + y = weakref.ref(od) + z = weakref.ref(cfg) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(a) + del(b) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del(od) + del(dod) + assert w() is not None + assert x() is not None + assert w() is not None + assert x() is not None + del cfg assert y() is None assert z() is None + assert not await list_sessions() diff --git a/tests/test_duplicate_config.py b/tests/test_duplicate_config.py index 0e4612b..c71be44 100644 --- a/tests/test_duplicate_config.py +++ b/tests/test_duplicate_config.py @@ -6,12 +6,8 @@ import pytest from tiramisu.setting import groups from tiramisu import Config, MetaConfig, ChoiceOption, BoolOption, IntOption, \ StrOption, OptionDescription, groups -from .test_state import _diff_opts, _diff_conf from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop def make_description(): @@ -47,52 +43,52 @@ def make_description(): return descr -@pytest.mark.asyncio -async def test_copy(): - cfg = await Config(make_description()) - ncfg = await cfg.config.copy() - assert await cfg.option('creole.general.numero_etab').value.get() == None - await cfg.option('creole.general.numero_etab').value.set('oui') - assert await cfg.option('creole.general.numero_etab').value.get() == 'oui' - assert await ncfg.option('creole.general.numero_etab').value.get() == None -# _diff_opts(await cfg.cfgimpl_get_description(), nawait cfg.cfgimpl_get_description()) -# _diff_conf(cfg, ncfg) -# await cfg.creole.general.numero_etab = 'oui' -# raises(AssertionError, "_diff_conf(cfg, ncfg)") -# nawait cfg.creole.general.numero_etab = 'oui' -# _diff_conf(cfg, ncfg) def to_tuple(val): return tuple([tuple(v) for v in val]) +@pytest.mark.asyncio +async def test_copy(): + od = make_description() + async with await Config(od) as cfg: + async with await cfg.config.copy() as ncfg: + assert await cfg.option('creole.general.numero_etab').value.get() == None + await cfg.option('creole.general.numero_etab').value.set('oui') + assert await cfg.option('creole.general.numero_etab').value.get() == 'oui' + assert await ncfg.option('creole.general.numero_etab').value.get() == None + assert not await list_sessions() + + @pytest.mark.asyncio async def test_copy_force_store_value(): - descr = make_description() - conf = await Config(descr) - conf2 = await Config(descr) - assert to_tuple(await conf.value.exportation()) == ((), (), (), ()) - assert to_tuple(await conf2.value.exportation()) == ((), (), (), ()) - # - await conf.property.read_write() - assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) - assert to_tuple(await conf2.value.exportation()) == ((), (), (), ()) - # - await conf2.property.read_only() - assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) - assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) - # - await conf.option('creole.general.wantref').value.set(True) - assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',)) - assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + od = make_description() + async with await Config(od) as conf: + async with await Config(od) as conf2: + assert to_tuple(await conf.value.exportation()) == ((), (), (), ()) + assert to_tuple(await conf2.value.exportation()) == ((), (), (), ()) + # + await conf.property.read_write() + assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + assert to_tuple(await conf2.value.exportation()) == ((), (), (), ()) + # + await conf2.property.read_only() + assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + # + await conf.option('creole.general.wantref').value.set(True) + assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',)) + assert to_tuple(await conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + assert not await list_sessions() @pytest.mark.asyncio async def test_copy_force_store_value_metaconfig(): descr = make_description() - meta = await MetaConfig([], optiondescription=descr) - conf = await meta.config.new(session_id='conf') - assert await meta.property.get() == await conf.property.get() - assert await meta.permissive.get() == await conf.permissive.get() - await conf.property.read_write() - assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) - assert to_tuple(await meta.value.exportation()) == ((), (), (), ()) + async with await MetaConfig([], optiondescription=descr) as meta: + async with await meta.config.new(session_id='conf') as conf: + assert await meta.property.get() == await conf.property.get() + assert await meta.permissive.get() == await conf.permissive.get() + await conf.property.read_write() + assert to_tuple(await conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',)) + assert to_tuple(await meta.value.exportation()) == ((), (), (), ()) + assert not await list_sessions() diff --git a/tests/test_dyn_optiondescription.py b/tests/test_dyn_optiondescription.py index df25c90..66865c1 100644 --- a/tests/test_dyn_optiondescription.py +++ b/tests/test_dyn_optiondescription.py @@ -9,9 +9,11 @@ from tiramisu import BoolOption, StrOption, ChoiceOption, IPOption, \ StrOption, PortOption, BroadcastOption, DomainnameOption, \ EmailOption, URLOption, UsernameOption, FilenameOption, SymLinkOption, \ OptionDescription, DynOptionDescription, SynDynOption, submulti, Leadership, \ - Config, Params, ParamOption, ParamValue, ParamSuffix, ParamSelfOption, ParamIndex, Calculation, calc_value + Config, Params, ParamOption, ParamValue, ParamSuffix, ParamSelfOption, ParamIndex, Calculation, calc_value, \ + delete_session from tiramisu.error import PropertiesOptionError, ConfigError, ConflictError from tiramisu.storage import list_sessions +from .config import event_loop class ConvertDynOptionDescription(DynOptionDescription): @@ -20,10 +22,6 @@ class ConvertDynOptionDescription(DynOptionDescription): return suffix.replace('.', '') -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def return_true(value, param=None, suffix=None): if value == 'val' and param in [None, 'yes']: return @@ -70,8 +68,9 @@ async def test_build_dyndescription(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [dod]) - cfg = await Config(od1) - assert await cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None} + async with await Config(od1) as cfg: + assert await cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None} + assert not await list_sessions() @pytest.mark.asyncio @@ -79,9 +78,10 @@ async def test_build_dyndescription_raise(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_raise)) od1 = OptionDescription('od', '', [dod]) - cfg = await Config(od1) - with pytest.raises(ConfigError): - await cfg.value.dict() + async with await Config(od1) as cfg: + with pytest.raises(ConfigError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -89,9 +89,10 @@ async def test_build_dyndescription_not_list(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_str)) od1 = OptionDescription('od', '', [dod]) - cfg = await Config(od1) - with pytest.raises(ValueError): - await cfg.value.dict() + async with await Config(od1) as cfg: + with pytest.raises(ValueError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -100,8 +101,9 @@ async def test_subpath_dyndescription(): dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - assert await cfg.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None} + async with await Config(od2) as cfg: + assert await cfg.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None} + assert not await list_sessions() @pytest.mark.asyncio @@ -110,9 +112,10 @@ async def test_list_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None + async with await Config(od2) as cfg: + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -121,13 +124,14 @@ async def test_unknown_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - with pytest.raises(AttributeError): - await cfg.option('od.dodval3').value.get() - with pytest.raises(AttributeError): - await cfg.option('od.dodval1.novalue').value.get() - with pytest.raises(AttributeError): - await cfg.option('od.dodval1.stnoval1').value.get() + async with await Config(od2) as cfg: + with pytest.raises(AttributeError): + await cfg.option('od.dodval3').value.get() + with pytest.raises(AttributeError): + await cfg.option('od.dodval1.novalue').value.get() + with pytest.raises(AttributeError): + await cfg.option('od.dodval1.stnoval1').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -136,15 +140,16 @@ async def test_getdoc_dyndescription(): dod = DynOptionDescription('dod', 'doc2', [st1], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - assert await cfg.option('od.dodval1.stval1').option.name() == 'stval1' - assert await cfg.option('od.dodval2.stval2').option.name() == 'stval2' - assert await cfg.option('od.dodval1').option.name() == 'dodval1' - assert await cfg.option('od.dodval2').option.name() == 'dodval2' - assert await cfg.option('od.dodval1.stval1').option.doc() == 'doc1' - assert await cfg.option('od.dodval2.stval2').option.doc() == 'doc1' - assert await cfg.option('od.dodval1').option.doc() == 'doc2val1' - assert await cfg.option('od.dodval2').option.doc() == 'doc2val2' + async with await Config(od2) as cfg: + assert await cfg.option('od.dodval1.stval1').option.name() == 'stval1' + assert await cfg.option('od.dodval2.stval2').option.name() == 'stval2' + assert await cfg.option('od.dodval1').option.name() == 'dodval1' + assert await cfg.option('od.dodval2').option.name() == 'dodval2' + assert await cfg.option('od.dodval1.stval1').option.doc() == 'doc1' + assert await cfg.option('od.dodval2.stval2').option.doc() == 'doc1' + assert await cfg.option('od.dodval1').option.doc() == 'doc2val1' + assert await cfg.option('od.dodval2').option.doc() == 'doc2val2' + assert not await list_sessions() @pytest.mark.asyncio @@ -153,25 +158,26 @@ async def test_mod_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - # - await cfg.option('od.dodval1.stval1').value.set('yes') - assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' - assert await cfg.option('od.dodval2.stval2').value.get() is None - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - # - await cfg.option('od.dodval2.stval2').value.set('no') - assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' - assert await cfg.option('od.dodval2.stval2').value.get() == 'no' - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.get() == owner + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + # + await cfg.option('od.dodval1.stval1').value.set('yes') + assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + # + await cfg.option('od.dodval2.stval2').value.set('no') + assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' + assert await cfg.option('od.dodval2.stval2').value.get() == 'no' + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.get() == owner + assert not await list_sessions() @pytest.mark.asyncio @@ -180,14 +186,15 @@ async def test_del_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - await cfg.option('od.dodval1.stval1').value.set('yes') - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - await cfg.option('od.dodval1.stval1').value.reset() - assert await cfg.option('od.dodval1.stval1').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + await cfg.option('od.dodval1.stval1').value.set('yes') + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + await cfg.option('od.dodval1.stval1').value.reset() + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -196,26 +203,27 @@ async def test_multi_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() == [] - assert await cfg.option('od.dodval2.stval2').value.get() == [] - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set(['yes']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] - assert await cfg.option('od.dodval2.stval2').value.get() == [] - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval2.stval2').value.set(['no']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] - assert await cfg.option('od.dodval2.stval2').value.get() == ['no'] - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.get() == owner - await cfg.option('od.dodval1.stval1').value.set(['yes', 'no']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes', 'no'] - await cfg.option('od.dodval1.stval1').value.set(['yes']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() == [] + assert await cfg.option('od.dodval2.stval2').value.get() == [] + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set(['yes']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert await cfg.option('od.dodval2.stval2').value.get() == [] + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval2.stval2').value.set(['no']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert await cfg.option('od.dodval2.stval2').value.get() == ['no'] + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.get() == owner + await cfg.option('od.dodval1.stval1').value.set(['yes', 'no']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes', 'no'] + await cfg.option('od.dodval1.stval1').value.set(['yes']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert not await list_sessions() @pytest.mark.asyncio @@ -224,23 +232,24 @@ async def test_prop_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) - assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test']) - await cfg.option('od.dodval2.stval2').property.add('test2') - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) - assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) - await cfg.option('od.dodval1.stval1').property.pop('test') - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set([]) - # - assert set(await cfg.option('od.dodval1').property.get()) == set([]) - assert set(await cfg.option('od.dodval2').property.get()) == set([]) - await cfg.option('od.dodval1').property.add('test1') - assert set(await cfg.option('od.dodval1').property.get()) == set(['test1']) - assert set(await cfg.option('od.dodval2').property.get()) == set([]) - await cfg.option('od.dodval1').property.pop('test1') - assert set(await cfg.option('od.dodval1').property.get()) == set([]) - assert set(await cfg.option('od.dodval2').property.get()) == set([]) + async with await Config(od2) as cfg: + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) + assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test']) + await cfg.option('od.dodval2.stval2').property.add('test2') + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) + assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) + await cfg.option('od.dodval1.stval1').property.pop('test') + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set([]) + # + assert set(await cfg.option('od.dodval1').property.get()) == set([]) + assert set(await cfg.option('od.dodval2').property.get()) == set([]) + await cfg.option('od.dodval1').property.add('test1') + assert set(await cfg.option('od.dodval1').property.get()) == set(['test1']) + assert set(await cfg.option('od.dodval2').property.get()) == set([]) + await cfg.option('od.dodval1').property.pop('test1') + assert set(await cfg.option('od.dodval1').property.get()) == set([]) + assert set(await cfg.option('od.dodval2').property.get()) == set([]) + assert not await list_sessions() @pytest.mark.asyncio @@ -249,8 +258,10 @@ async def test_prop_dyndescription_force_store_value(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - with pytest.raises(ConfigError): - await Config(od2) + with pytest.raises(ConfigError): + await Config(od2, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio @@ -259,22 +270,23 @@ async def test_callback_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set('val2') - assert await cfg.option('od.dodval1.stval1').value.get() == 'val2' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.reset() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set('val2') + assert await cfg.option('od.dodval1.stval1').value.get() == 'val2' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.reset() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -283,17 +295,18 @@ async def test_callback_list_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() == ['val1', 'val2'] - assert await cfg.option('od.dodval2.stval2').value.get() == ['val2', 'val2'] - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set(['val3', 'val2']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['val3', 'val2'] - assert await cfg.option('od.dodval2.stval2').value.get() == ['val2', 'val2'] - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() == ['val1', 'val2'] + assert await cfg.option('od.dodval2.stval2').value.get() == ['val2', 'val2'] + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set(['val3', 'val2']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['val3', 'val2'] + assert await cfg.option('od.dodval2.stval2').value.get() == ['val2', 'val2'] + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -302,24 +315,25 @@ async def test_mandatory_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval1.stval1').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval2.stval2').value.get() - await cfg.property.read_write() - await cfg.option('od.dodval1.stval1').value.set('val') - await cfg.property.read_only() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval2.stval2').value.get() - await cfg.property.read_write() - await cfg.option('od.dodval1.stval1').value.reset() - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval1.stval1').value.get() - assert list(await cfg.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2'] + async with await Config(od2) as cfg: + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval1.stval1').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval2.stval2').value.get() + await cfg.property.read_write() + await cfg.option('od.dodval1.stval1').value.set('val') + await cfg.property.read_only() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval2.stval2').value.get() + await cfg.property.read_write() + await cfg.option('od.dodval1.stval1').value.reset() + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval1.stval1').value.get() + assert list(await cfg.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2'] + assert not await list_sessions() @pytest.mark.asyncio @@ -328,8 +342,9 @@ async def test_build_dyndescription_context(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od1 = OptionDescription('od', '', [dod, val1]) - cfg = await Config(od1) - assert await cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None, 'val1': ['val1', 'val2']} + async with await Config(od1) as cfg: + assert await cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None, 'val1': ['val1', 'val2']} + assert not await list_sessions() @pytest.mark.asyncio @@ -339,8 +354,9 @@ async def test_subpath_dyndescription_context(): dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od1 = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - assert await cfg.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None, 'od.val1': ['val1', 'val2']} + async with await Config(od2) as cfg: + assert await cfg.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None, 'od.val1': ['val1', 'val2']} + assert not await list_sessions() @pytest.mark.asyncio @@ -350,11 +366,12 @@ async def test_list_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - with pytest.raises(AttributeError): - await cfg.option('od.dodval3').value.get() + async with await Config(od2) as cfg: + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + with pytest.raises(AttributeError): + await cfg.option('od.dodval3').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -364,22 +381,23 @@ async def test_mod_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set('yes') - assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' - assert await cfg.option('od.dodval2.stval2').value.get() is None - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval2.stval2').value.set('no') - assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' - assert await cfg.option('od.dodval2.stval2').value.get() == 'no' - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.get() == owner + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set('yes') + assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval2.stval2').value.set('no') + assert await cfg.option('od.dodval1.stval1').value.get() == 'yes' + assert await cfg.option('od.dodval2.stval2').value.get() == 'no' + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.get() == owner + assert not await list_sessions() @pytest.mark.asyncio @@ -389,14 +407,15 @@ async def test_del_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - await cfg.option('od.dodval1.stval1').value.set('yes') - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - await cfg.option('od.dodval1.stval1').value.reset() - assert await cfg.option('od.dodval1.stval1').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + await cfg.option('od.dodval1.stval1').value.set('yes') + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + await cfg.option('od.dodval1.stval1').value.reset() + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -406,26 +425,27 @@ async def test_multi_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() == [] - assert await cfg.option('od.dodval2.stval2').value.get() == [] - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set(['yes']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] - assert await cfg.option('od.dodval2.stval2').value.get() == [] - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval2.stval2').value.set(['no']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] - assert await cfg.option('od.dodval2.stval2').value.get() == ['no'] - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.get() == owner - await cfg.option('od.dodval1.stval1').value.set(['yes', 'yes']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes', 'yes'] - await cfg.option('od.dodval1.stval1').value.set(['yes']) - assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() == [] + assert await cfg.option('od.dodval2.stval2').value.get() == [] + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set(['yes']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert await cfg.option('od.dodval2.stval2').value.get() == [] + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval2.stval2').value.set(['no']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert await cfg.option('od.dodval2.stval2').value.get() == ['no'] + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.get() == owner + await cfg.option('od.dodval1.stval1').value.set(['yes', 'yes']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes', 'yes'] + await cfg.option('od.dodval1.stval1').value.set(['yes']) + assert await cfg.option('od.dodval1.stval1').value.get() == ['yes'] + assert not await list_sessions() @pytest.mark.asyncio @@ -435,15 +455,16 @@ async def test_prop_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) - assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test']) - await cfg.option('od.dodval2.stval2').property.add('test2') - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) - assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) - await cfg.option('od.dodval1.stval1').property.pop('test') - assert set(await cfg.option('od.dodval1.stval1').property.get()) == set([]) - assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) + async with await Config(od2) as cfg: + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) + assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test']) + await cfg.option('od.dodval2.stval2').property.add('test2') + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set(['test']) + assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) + await cfg.option('od.dodval1.stval1').property.pop('test') + assert set(await cfg.option('od.dodval1.stval1').property.get()) == set([]) + assert set(await cfg.option('od.dodval2.stval2').property.get()) == set(['test', 'test2']) + assert not await list_sessions() @pytest.mark.asyncio @@ -453,22 +474,23 @@ async def test_callback_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.set('val2') - assert await cfg.option('od.dodval1.stval1').value.get() == 'val2' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.get() == owner - assert await cfg.option('od.dodval2.stval2').owner.isdefault() - await cfg.option('od.dodval1.stval1').value.reset() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - assert await cfg.option('od.dodval2.stval2').value.get() == 'val' - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.set('val2') + assert await cfg.option('od.dodval1.stval1').value.get() == 'val2' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.get() == owner + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + await cfg.option('od.dodval1.stval1').value.reset() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + assert await cfg.option('od.dodval2.stval2').value.get() == 'val' + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -478,24 +500,25 @@ async def test_mandatory_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval1.stval1').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval2.stval2').value.get() - await cfg.property.read_write() - await cfg.option('od.dodval1.stval1').value.set('val') - await cfg.property.read_only() - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval2.stval2').value.get() - await cfg.property.read_write() - await cfg.option('od.dodval1.stval1').value.reset() - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('od.dodval1.stval1').value.get() - assert list(await cfg.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2'] + async with await Config(od2) as cfg: + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval1.stval1').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval2.stval2').value.get() + await cfg.property.read_write() + await cfg.option('od.dodval1.stval1').value.set('val') + await cfg.property.read_only() + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval2.stval2').value.get() + await cfg.property.read_write() + await cfg.option('od.dodval1.stval1').value.reset() + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('od.dodval1.stval1').value.get() + assert list(await cfg.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2'] + assert not await list_sessions() @pytest.mark.asyncio @@ -505,16 +528,17 @@ async def test_increase_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.property.read_write() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - with pytest.raises(AttributeError): - await cfg.option('od.dodval3.stval3').value.get() - await cfg.option('od.val1').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - assert await cfg.option('od.dodval3.stval3').value.get() is None + async with await Config(od2) as cfg: + await cfg.property.read_write() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + with pytest.raises(AttributeError): + await cfg.option('od.dodval3.stval3').value.get() + await cfg.option('od.val1').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert await cfg.option('od.dodval3.stval3').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -524,29 +548,30 @@ async def test_decrease_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - await cfg.property.read_write() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - await cfg.option('od.dodval2.stval2').value.set('yes') - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() == 'yes' - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - assert await cfg.option('od.dodval2.stval2').owner.get() == owner - with pytest.raises(AttributeError): - await cfg.option('od.dodval3').value.get() - await cfg.option('od.val1').value.set(['val1']) - assert await cfg.option('od.dodval1.stval1').value.get() is None - with pytest.raises(AttributeError): - await cfg.option('od.dodval2').value.get() - with pytest.raises(AttributeError): - await cfg.option('od.dodval3').value.get() - assert await cfg.option('od.dodval1.stval1').owner.isdefault() - with pytest.raises(AttributeError): - await cfg.option('od.dodval2.stval2').owner.get() - with pytest.raises(AttributeError): - await cfg.option('od.dodval2.stval2').value.get() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + await cfg.property.read_write() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + await cfg.option('od.dodval2.stval2').value.set('yes') + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() == 'yes' + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + assert await cfg.option('od.dodval2.stval2').owner.get() == owner + with pytest.raises(AttributeError): + await cfg.option('od.dodval3').value.get() + await cfg.option('od.val1').value.set(['val1']) + assert await cfg.option('od.dodval1.stval1').value.get() is None + with pytest.raises(AttributeError): + await cfg.option('od.dodval2').value.get() + with pytest.raises(AttributeError): + await cfg.option('od.dodval3').value.get() + assert await cfg.option('od.dodval1.stval1').owner.isdefault() + with pytest.raises(AttributeError): + await cfg.option('od.dodval2.stval2').owner.get() + with pytest.raises(AttributeError): + await cfg.option('od.dodval2.stval2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -559,8 +584,10 @@ async def test_dyndescription_root(): 'default': ParamValue(None)})) st1 = StrOption('st', '', properties=(disabled_property,)) dod = DynOptionDescription('dod', '', [boolean, st1], suffixes=Calculation(return_list)) - with pytest.raises(ConfigError): - await Config(dod) + with pytest.raises(ConfigError): + await Config(dod, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio @@ -575,42 +602,43 @@ async def test_requires_dyndescription(): dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od1, boolean]) - cfg = await Config(od2) - await cfg.property.read_write() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - # - await cfg.option('boolean').value.set(False) - props = [] - try: - await cfg.option('od.dodval1.stval1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - props = [] - try: - await cfg.option('od.dodval2.stval2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - await cfg.option('boolean').value.set(True) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - #transitive - await cfg.option('boolean').property.add('disabled') - props = [] - try: - await cfg.option('od.dodval1.stval1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - props = [] - try: - await cfg.option('od.dodval2.stval2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + async with await Config(od2) as cfg: + await cfg.property.read_write() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + # + await cfg.option('boolean').value.set(False) + props = [] + try: + await cfg.option('od.dodval1.stval1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + props = [] + try: + await cfg.option('od.dodval2.stval2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + await cfg.option('boolean').value.set(True) + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + #transitive + await cfg.option('boolean').property.add('disabled') + props = [] + try: + await cfg.option('od.dodval1.stval1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + props = [] + try: + await cfg.option('od.dodval2.stval2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -631,25 +659,26 @@ async def test_requires_dyndescription_boolean(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od, boolean1, boolean]) - cfg = await Config(od2) - await cfg.property.read_write() - assert await cfg.value.dict() == {'boolean1': True, - 'boolean': True, - 'od.dodval1.stval1': None, - 'od.dodval2.stval2': None} - # - await cfg.option('boolean').value.set(False) - assert await cfg.value.dict() == {'boolean1': True, - 'boolean': False} - # - await cfg.option('boolean').value.set(True) - assert await cfg.value.dict() == {'boolean1': True, - 'boolean': True, - 'od.dodval1.stval1': None, - 'od.dodval2.stval2': None} - # - await cfg.option('boolean1').value.set(False) - assert await cfg.value.dict() == {'boolean1': False} + async with await Config(od2) as cfg: + await cfg.property.read_write() + assert await cfg.value.dict() == {'boolean1': True, + 'boolean': True, + 'od.dodval1.stval1': None, + 'od.dodval2.stval2': None} + # + await cfg.option('boolean').value.set(False) + assert await cfg.value.dict() == {'boolean1': True, + 'boolean': False} + # + await cfg.option('boolean').value.set(True) + assert await cfg.value.dict() == {'boolean1': True, + 'boolean': True, + 'od.dodval1.stval1': None, + 'od.dodval2.stval2': None} + # + await cfg.option('boolean1').value.set(False) + assert await cfg.value.dict() == {'boolean1': False} + assert not await list_sessions() @pytest.mark.asyncio @@ -664,26 +693,27 @@ async def test_requires_dyndescription_in_dyn(): dod = DynOptionDescription('dod', '', [boolean, st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.property.read_write() + async with await Config(od2) as cfg: + await cfg.property.read_write() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - # - await cfg.option('od.dodval1.booleanval1').value.set(False) + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + # + await cfg.option('od.dodval1.booleanval1').value.set(False) - props = [] - try: - await cfg.option('od.dodval1.stval1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert props == frozenset(['disabled']) - props = [] - await cfg.option('od.dodval2.stval2').value.get() - # - await cfg.option('od.dodval1.booleanval1').value.set(True) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None + props = [] + try: + await cfg.option('od.dodval1.stval1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert props == frozenset(['disabled']) + props = [] + await cfg.option('od.dodval2.stval2').value.get() + # + await cfg.option('od.dodval1.booleanval1').value.set(True) + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -698,42 +728,43 @@ async def test_requires_dyndescription2(): dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_list), properties=(disabled_property,)) od1 = OptionDescription('od', '', [dod]) od2 = OptionDescription('od', '', [od1, boolean]) - cfg = await Config(od2) - await cfg.property.read_write() - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - # - await cfg.option('boolean').value.set(False) - props = [] - try: - await cfg.option('od.dodval1.stval1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - props = [] - try: - await cfg.option('od.dodval2.stval2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - await cfg.option('boolean').value.set(True) - assert await cfg.option('od.dodval1.stval1').value.get() is None - assert await cfg.option('od.dodval2.stval2').value.get() is None - #transitive - await cfg.option('boolean').property.add('disabled') - props = [] - try: - await cfg.option('od.dodval1.stval1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - props = [] - try: - await cfg.option('od.dodval2.stval2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + async with await Config(od2) as cfg: + await cfg.property.read_write() + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + # + await cfg.option('boolean').value.set(False) + props = [] + try: + await cfg.option('od.dodval1.stval1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + props = [] + try: + await cfg.option('od.dodval2.stval2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + await cfg.option('boolean').value.set(True) + assert await cfg.option('od.dodval1.stval1').value.get() is None + assert await cfg.option('od.dodval2.stval2').value.get() is None + #transitive + await cfg.option('boolean').property.add('disabled') + props = [] + try: + await cfg.option('od.dodval1.stval1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + props = [] + try: + await cfg.option('od.dodval2.stval2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -743,11 +774,12 @@ async def test_validator_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert await cfg.option('od.dodval1.stval1').value.get() == 'val' - with pytest.raises(ValueError): - await cfg.option('od.dodval1.stval1').value.set('no') - await cfg.option('od.dodval1.stval1').value.set('val') + async with await Config(od2) as cfg: + assert await cfg.option('od.dodval1.stval1').value.get() == 'val' + with pytest.raises(ValueError): + await cfg.option('od.dodval1.stval1').value.set('no') + await cfg.option('od.dodval1.stval1').value.set('val') + assert not await list_sessions() @pytest.mark.asyncio @@ -757,10 +789,11 @@ async def test_makedict_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.option('od.dodval1.stval1').value.set('yes') - assert await cfg.value.dict() == {'od.val1': ['val1', 'val2'], 'od.dodval1.stval1': 'yes', 'od.dodval2.stval2': None} - assert await cfg.value.dict(flatten=True) == {'val1': ['val1', 'val2'], 'stval1': 'yes', 'stval2': None} + async with await Config(od2) as cfg: + await cfg.option('od.dodval1.stval1').value.set('yes') + assert await cfg.value.dict() == {'od.val1': ['val1', 'val2'], 'od.dodval1.stval1': 'yes', 'od.dodval2.stval2': None} + assert await cfg.value.dict(flatten=True) == {'val1': ['val1', 'val2'], 'stval1': 'yes', 'stval2': None} + assert not await list_sessions() @pytest.mark.asyncio @@ -770,19 +803,20 @@ async def test_find_dyndescription_context(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod, val1]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await cfg.option('od.dodval1.stval1').value.set('yes') - ret = await cfg.option.find('stval1', first=True) - assert await ret.value.get() == "yes" - ret = await cfg.option.find('stval1', first=True) - assert isinstance(await ret.option.get(), SynDynOption) - #assert await cfg.option.find(bytype=StrOption, type='path') == ['od.dodval1.stval1', 'od.dodval2.stval2', 'od.val1'] - #opts = await cfg.option.find(byvalue='yes') - #assert len(opts) == 1 - #assert isinstance(opts[0], SynDynOption) - #assert opts[0].impl_getname() == 'stval1' - with pytest.raises(AttributeError): - list(await cfg.option.find('strnotexists')) + async with await Config(od2) as cfg: + await cfg.option('od.dodval1.stval1').value.set('yes') + ret = await cfg.option.find('stval1', first=True) + assert await ret.value.get() == "yes" + ret = await cfg.option.find('stval1', first=True) + assert isinstance(await ret.option.get(), SynDynOption) + #assert await cfg.option.find(bytype=StrOption, type='path') == ['od.dodval1.stval1', 'od.dodval2.stval2', 'od.val1'] + #opts = await cfg.option.find(byvalue='yes') + #assert len(opts) == 1 + #assert isinstance(opts[0], SynDynOption) + #assert opts[0].impl_getname() == 'stval1' + with pytest.raises(AttributeError): + list(await cfg.option.find('strnotexists')) + assert not await list_sessions() @pytest.mark.asyncio @@ -794,13 +828,14 @@ async def test_information_dyndescription_context(): od2 = OptionDescription('od', '', [od]) dod.impl_set_information('testod', 'val1') st.impl_set_information('testst', 'val2') - cfg = await Config(od2) - await cfg.information.set('testcfgod', 'val3') - assert await cfg.option('od.dodval1').information.get('testod') == 'val1' - assert await cfg.option('od.dodval2').information.get('testod') == 'val1' - assert await cfg.option('od.dodval1.stval1').information.get('testst') == 'val2' - assert await cfg.option('od.dodval2.stval2').information.get('testst') == 'val2' - assert await cfg.information.get('testcfgod') == 'val3' + async with await Config(od2) as cfg: + await cfg.information.set('testcfgod', 'val3') + assert await cfg.option('od.dodval1').information.get('testod') == 'val1' + assert await cfg.option('od.dodval2').information.get('testod') == 'val1' + assert await cfg.option('od.dodval1.stval1').information.get('testst') == 'val2' + assert await cfg.option('od.dodval2.stval2').information.get('testst') == 'val2' + assert await cfg.information.get('testcfgod') == 'val3' + assert not await list_sessions() @pytest.mark.asyncio @@ -827,76 +862,77 @@ async def test_all_dyndescription(): domain, email, url, username, filename], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [dod]) - cfg = await Config(od) - assert await cfg.option('dodval1.stval1').value.get() is None - assert await cfg.option('dodval1.ipval1').value.get() is None - assert await cfg.option('dodval1.networkval1').value.get() is None - assert await cfg.option('dodval1.netmaskval1').value.get() is None - assert await cfg.option('dodval1.chval1').value.get() is None - assert await cfg.option('dodval1.ch1val1').value.get() is None - assert await cfg.option('dodval1.booval1').value.get() is None - assert await cfg.option('dodval1.intrval1').value.get() is None - assert await cfg.option('dodval1.floaval1').value.get() is None - assert await cfg.option('dodval1.unival1').value.get() is None - assert await cfg.option('dodval1.portval1').value.get() is None - assert await cfg.option('dodval1.broadval1').value.get() is None - assert await cfg.option('dodval1.domainval1').value.get() is None - assert await cfg.option('dodval1.emailval1').value.get() is None - assert await cfg.option('dodval1.urlval1').value.get() is None - assert await cfg.option('dodval1.usernameval1').value.get() is None - assert await cfg.option('dodval1.filenameval1').value.get() is None - # - await cfg.option('dodval1.stval1').value.set("no") - await cfg.option('dodval1.ipval1').value.set("1.1.1.1") - await cfg.option('dodval1.networkval1').value.set("1.1.1.0") - await cfg.option('dodval1.netmaskval1').value.set("255.255.255.0") - await cfg.option('dodval1.chval1').value.set("val1") - await cfg.option('dodval1.ch1val1').value.set("val2") - await cfg.option('dodval1.booval1').value.set(True) - await cfg.option('dodval1.intrval1').value.set(1) - await cfg.option('dodval1.floaval1').value.set(0.1) - await cfg.option('dodval1.unival1').value.set(u"no") - await cfg.option('dodval1.portval1').value.set('80') - await cfg.option('dodval1.broadval1').value.set("1.1.1.255") - await cfg.option('dodval1.domainval1').value.set("test.com") - await cfg.option('dodval1.emailval1').value.set("test@test.com") - await cfg.option('dodval1.urlval1').value.set("http://test.com") - await cfg.option('dodval1.usernameval1').value.set("user1") - await cfg.option('dodval1.filenameval1').value.set("/tmp") - assert await cfg.option('dodval1.stval1').value.get() == "no" - assert await cfg.option('dodval1.ipval1').value.get() == "1.1.1.1" - assert await cfg.option('dodval1.networkval1').value.get() == "1.1.1.0" - assert await cfg.option('dodval1.netmaskval1').value.get() == "255.255.255.0" - assert await cfg.option('dodval1.chval1').value.get() == "val1" - assert await cfg.option('dodval1.ch1val1').value.get() == "val2" - assert await cfg.option('dodval1.booval1').value.get() is True - assert await cfg.option('dodval1.intrval1').value.get() == 1 - assert await cfg.option('dodval1.floaval1').value.get() == 0.1 - assert await cfg.option('dodval1.unival1').value.get() == u"no" - assert await cfg.option('dodval1.portval1').value.get() == '80' - assert await cfg.option('dodval1.broadval1').value.get() == "1.1.1.255" - assert await cfg.option('dodval1.domainval1').value.get() == "test.com" - assert await cfg.option('dodval1.emailval1').value.get() == "test@test.com" - assert await cfg.option('dodval1.urlval1').value.get() == "http://test.com" - assert await cfg.option('dodval1.usernameval1').value.get() == "user1" - assert await cfg.option('dodval1.filenameval1').value.get() == "/tmp" - assert await cfg.option('dodval2.stval2').value.get() is None - assert await cfg.option('dodval2.ipval2').value.get() is None - assert await cfg.option('dodval2.networkval2').value.get() is None - assert await cfg.option('dodval2.netmaskval2').value.get() is None - assert await cfg.option('dodval2.chval2').value.get() is None - assert await cfg.option('dodval2.ch1val2').value.get() is None - assert await cfg.option('dodval2.booval2').value.get() is None - assert await cfg.option('dodval2.intrval2').value.get() is None - assert await cfg.option('dodval2.floaval2').value.get() is None - assert await cfg.option('dodval2.unival2').value.get() is None - assert await cfg.option('dodval2.portval2').value.get() is None - assert await cfg.option('dodval2.broadval2').value.get() is None - assert await cfg.option('dodval2.domainval2').value.get() is None - assert await cfg.option('dodval2.emailval2').value.get() is None - assert await cfg.option('dodval2.urlval2').value.get() is None - assert await cfg.option('dodval2.usernameval2').value.get() is None - assert await cfg.option('dodval2.filenameval2').value.get() is None + async with await Config(od) as cfg: + assert await cfg.option('dodval1.stval1').value.get() is None + assert await cfg.option('dodval1.ipval1').value.get() is None + assert await cfg.option('dodval1.networkval1').value.get() is None + assert await cfg.option('dodval1.netmaskval1').value.get() is None + assert await cfg.option('dodval1.chval1').value.get() is None + assert await cfg.option('dodval1.ch1val1').value.get() is None + assert await cfg.option('dodval1.booval1').value.get() is None + assert await cfg.option('dodval1.intrval1').value.get() is None + assert await cfg.option('dodval1.floaval1').value.get() is None + assert await cfg.option('dodval1.unival1').value.get() is None + assert await cfg.option('dodval1.portval1').value.get() is None + assert await cfg.option('dodval1.broadval1').value.get() is None + assert await cfg.option('dodval1.domainval1').value.get() is None + assert await cfg.option('dodval1.emailval1').value.get() is None + assert await cfg.option('dodval1.urlval1').value.get() is None + assert await cfg.option('dodval1.usernameval1').value.get() is None + assert await cfg.option('dodval1.filenameval1').value.get() is None + # + await cfg.option('dodval1.stval1').value.set("no") + await cfg.option('dodval1.ipval1').value.set("1.1.1.1") + await cfg.option('dodval1.networkval1').value.set("1.1.1.0") + await cfg.option('dodval1.netmaskval1').value.set("255.255.255.0") + await cfg.option('dodval1.chval1').value.set("val1") + await cfg.option('dodval1.ch1val1').value.set("val2") + await cfg.option('dodval1.booval1').value.set(True) + await cfg.option('dodval1.intrval1').value.set(1) + await cfg.option('dodval1.floaval1').value.set(0.1) + await cfg.option('dodval1.unival1').value.set(u"no") + await cfg.option('dodval1.portval1').value.set('80') + await cfg.option('dodval1.broadval1').value.set("1.1.1.255") + await cfg.option('dodval1.domainval1').value.set("test.com") + await cfg.option('dodval1.emailval1').value.set("test@test.com") + await cfg.option('dodval1.urlval1').value.set("http://test.com") + await cfg.option('dodval1.usernameval1').value.set("user1") + await cfg.option('dodval1.filenameval1').value.set("/tmp") + assert await cfg.option('dodval1.stval1').value.get() == "no" + assert await cfg.option('dodval1.ipval1').value.get() == "1.1.1.1" + assert await cfg.option('dodval1.networkval1').value.get() == "1.1.1.0" + assert await cfg.option('dodval1.netmaskval1').value.get() == "255.255.255.0" + assert await cfg.option('dodval1.chval1').value.get() == "val1" + assert await cfg.option('dodval1.ch1val1').value.get() == "val2" + assert await cfg.option('dodval1.booval1').value.get() is True + assert await cfg.option('dodval1.intrval1').value.get() == 1 + assert await cfg.option('dodval1.floaval1').value.get() == 0.1 + assert await cfg.option('dodval1.unival1').value.get() == u"no" + assert await cfg.option('dodval1.portval1').value.get() == '80' + assert await cfg.option('dodval1.broadval1').value.get() == "1.1.1.255" + assert await cfg.option('dodval1.domainval1').value.get() == "test.com" + assert await cfg.option('dodval1.emailval1').value.get() == "test@test.com" + assert await cfg.option('dodval1.urlval1').value.get() == "http://test.com" + assert await cfg.option('dodval1.usernameval1').value.get() == "user1" + assert await cfg.option('dodval1.filenameval1').value.get() == "/tmp" + assert await cfg.option('dodval2.stval2').value.get() is None + assert await cfg.option('dodval2.ipval2').value.get() is None + assert await cfg.option('dodval2.networkval2').value.get() is None + assert await cfg.option('dodval2.netmaskval2').value.get() is None + assert await cfg.option('dodval2.chval2').value.get() is None + assert await cfg.option('dodval2.ch1val2').value.get() is None + assert await cfg.option('dodval2.booval2').value.get() is None + assert await cfg.option('dodval2.intrval2').value.get() is None + assert await cfg.option('dodval2.floaval2').value.get() is None + assert await cfg.option('dodval2.unival2').value.get() is None + assert await cfg.option('dodval2.portval2').value.get() is None + assert await cfg.option('dodval2.broadval2').value.get() is None + assert await cfg.option('dodval2.domainval2').value.get() is None + assert await cfg.option('dodval2.emailval2').value.get() is None + assert await cfg.option('dodval2.urlval2').value.get() is None + assert await cfg.option('dodval2.usernameval2').value.get() is None + assert await cfg.option('dodval2.filenameval2').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -907,55 +943,56 @@ async def test_leadership_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - await cfg.option('od.stval1.st1val1.st1val1').value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + await cfg.option('od.stval1.st1val1.st1val1').value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -966,21 +1003,23 @@ async def test_leadership_default_multi_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() + @pytest.mark.asyncio async def test_leadership_dyndescription_param(): @@ -992,55 +1031,56 @@ async def test_leadership_dyndescription_param(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [st, odval]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': [], 'od.odval1.val1': ['val1', 'val2']} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes'], 'od.odval1.val1': ['val1', 'val2']} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - await cfg.option('od.stval1.st1val1.st1val1').value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default - assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': [], 'od.odval1.val1': ['val1', 'val2']} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes'], 'od.odval1.val1': ['val1', 'val2']} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + await cfg.option('od.stval1.st1val1.st1val1').value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default + assert await cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio @@ -1051,21 +1091,22 @@ async def test_leadership_default_multi_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() async def _test_leadership(cfg): @@ -1133,8 +1174,9 @@ async def test_leadership_dyndescription_param_leader(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list, Params(ParamOption(val1)))) od = OptionDescription('od', '', [st, odval]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await _test_leadership(cfg) + async with await Config(od2) as cfg: + await _test_leadership(cfg) + assert not await list_sessions() @pytest.mark.asyncio @@ -1145,21 +1187,22 @@ async def test_leadership_default_multi_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1173,8 +1216,9 @@ async def test_leadership_dyndescription_param_follower(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list, Params(ParamOption(val2)))) od = OptionDescription('od', '', [st, odval]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - await _test_leadership(cfg) + async with await Config(od2) as cfg: + await _test_leadership(cfg) + assert not await list_sessions() @pytest.mark.asyncio @@ -1185,21 +1229,22 @@ async def test_leadership_default_multi_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1210,29 +1255,30 @@ async def test_leadership_submulti_dyndescription(): std = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [std]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set(['no']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == ['no'] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set(['no']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == ['no'] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1243,58 +1289,59 @@ async def test_leadership_callback_dyndescription(): st1 = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [st1]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() ==[] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': ['yes'], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - await cfg.option('od.stval1.st1val1.st1val1').value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes' + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() ==[] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': ['yes'], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + await cfg.option('od.stval1.st1val1.st1val1').value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes' + assert not await list_sessions() @pytest.mark.asyncio @@ -1305,12 +1352,13 @@ async def test_leadership_callback_value_dyndescription(): st = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('val') - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val' + async with await Config(od2) as cfg: + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('val') + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio @@ -1322,11 +1370,12 @@ async def test_leadership_callback_nomulti_dyndescription(): stt = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [stt]) od2 = OptionDescription('od', '', [od1, v11]) - cfg = await Config(od2) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val' + async with await Config(od2) as cfg: + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio @@ -1338,42 +1387,43 @@ async def test_leadership_callback_samegroup_dyndescription(): stt = DynOptionDescription('st', '', [stm], suffixes=Calculation(return_list)) od1 = OptionDescription('od', '', [stt]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': [], - 'od.stval1.st1val1.st2val1': [], - 'od.stval1.st1val1.st3val1': [], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], - 'od.stval1.st1val1.st2val1': [None], - 'od.stval1.st1val1.st3val1': [None], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], - 'od.stval1.st1val1.st2val1': ['yes'], - 'od.stval1.st1val1.st3val1': ['yes'], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': [], + 'od.stval1.st1val1.st2val1': [], + 'od.stval1.st1val1.st3val1': [], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], + 'od.stval1.st1val1.st2val1': [None], + 'od.stval1.st1val1.st3val1': [None], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], + 'od.stval1.st1val1.st2val1': ['yes'], + 'od.stval1.st1val1.st3val1': ['yes'], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1382,8 +1432,9 @@ async def test_invalid_conflict_dyndescription(): dod = DynOptionDescription('dod', '', [st], suffixes=Calculation(return_list)) dodinvalid = StrOption('dodinvalid', '') dod, dodinvalid - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): OptionDescription('od', '', [dod, dodinvalid]) + assert not await list_sessions() @pytest.mark.asyncio @@ -1391,8 +1442,9 @@ async def test_invalid_subod_dyndescription(): st2 = StrOption('st2', '') od1 = OptionDescription('od1', '', [st2]) od1 - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): DynOptionDescription('dod', '', [od1], suffixes=Calculation(return_list)) + assert not await list_sessions() @pytest.mark.asyncio @@ -1400,8 +1452,9 @@ async def test_invalid_subdynod_dyndescription(): st2 = StrOption('st2', '') od1 = DynOptionDescription('od1', '', [st2], suffixes=Calculation(return_list)) od1 - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): DynOptionDescription('dod', '', [od1], suffixes=Calculation(return_list)) + assert not await list_sessions() @pytest.mark.asyncio @@ -1409,8 +1462,9 @@ async def test_invalid_symlink_dyndescription(): st = StrOption('st', '') st2 = SymLinkOption('st2', st) st2 - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): DynOptionDescription('dod', '', [st, st2], suffixes=Calculation(return_list)) + assert not await list_sessions() @pytest.mark.asyncio @@ -1418,8 +1472,9 @@ async def test_nocallback_dyndescription(): st = StrOption('st', '') st2 = StrOption('st2', '') st, st2 - with pytest.raises(TypeError): + with pytest.raises(TypeError): DynOptionDescription('dod', '', [st, st2]) + assert not await list_sessions() @pytest.mark.asyncio @@ -1427,9 +1482,10 @@ async def test_invalid_samevalue_dyndescription(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_same_list)) od1 = OptionDescription('od', '', [dod]) - cfg = await Config(od1) - with pytest.raises(ValueError): - await cfg.value.dict() + async with await Config(od1) as cfg: + with pytest.raises(ValueError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -1437,9 +1493,10 @@ async def test_invalid_name_dyndescription(): st1 = StrOption('st', '') dod = DynOptionDescription('dod', '', [st1], suffixes=Calculation(return_wrong_list)) od1 = OptionDescription('od', '', [dod]) - cfg = await Config(od1) - with pytest.raises(ValueError): - await cfg.value.dict() + async with await Config(od1) as cfg: + with pytest.raises(ValueError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -1450,55 +1507,56 @@ async def test_leadership_dyndescription_convert(): st = ConvertDynOptionDescription('st', '', [stm], suffixes=Calculation(return_list_dot)) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - owner = await cfg.owner.get() - # - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] - assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - await cfg.option('od.stval1.st1val1.st1val1').value.reset() - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + # + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no') + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes'] + assert await cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no' + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.pop(0) + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + await cfg.option('od.stval1.st1val1.st2val1', 0).value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + await cfg.option('od.stval1.st1val1.st1val1').value.reset() + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1510,42 +1568,43 @@ async def test_leadership_callback_samegroup_dyndescription_convert(): stt = ConvertDynOptionDescription('st', '', [stm], suffixes=Calculation(return_list_dot)) od1 = OptionDescription('od', '', [stt]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - owner = await cfg.owner.get() - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': [], - 'od.stval1.st1val1.st2val1': [], - 'od.stval1.st1val1.st3val1': [], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] - assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] - assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], - 'od.stval1.st1val1.st2val1': [None], - 'od.stval1.st1val1.st3val1': [None], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() - assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() - # - await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') - assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], - 'od.stval1.st1val1.st2val1': ['yes'], - 'od.stval1.st1val1.st3val1': ['yes'], - 'od.stval2.st1val2.st1val2': [], - 'od.stval2.st1val2.st2val2': [], - 'od.stval2.st1val2.st3val2': []} - assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner - assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() - assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + async with await Config(od2) as cfg: + owner = await cfg.owner.get() + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': [], + 'od.stval1.st1val1.st2val1': [], + 'od.stval1.st1val1.st3val1': [], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').value.get() == [] + assert await cfg.option('od.stval2.st1val2.st1val2').value.get() == [] + assert await cfg.option('od.stval1.st1val1.st1val1').owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st1val1').value.set(['yes']) + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], + 'od.stval1.st1val1.st2val1': [None], + 'od.stval1.st1val1.st3val1': [None], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.isdefault() + assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + # + await cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes') + assert await cfg.value.dict() == {'od.stval1.st1val1.st1val1': ['yes'], + 'od.stval1.st1val1.st2val1': ['yes'], + 'od.stval1.st1val1.st3val1': ['yes'], + 'od.stval2.st1val2.st1val2': [], + 'od.stval2.st1val2.st2val2': [], + 'od.stval2.st1val2.st3val2': []} + assert await cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner + assert await cfg.option('od.stval1.st1val1.st3val1', 0).owner.isdefault() + assert await cfg.option('od.stval2.st1val2.st1val2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1555,18 +1614,19 @@ async def test_dyn_with_leader_hidden_in_config(): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('hidden',)) dyn = DynOptionDescription('leader', '', [interface1], suffixes=Calculation(return_list)) od = OptionDescription('root', '', [dyn]) - cfg = await Config(od) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - assert await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == [] - await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.1']) - assert await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() - await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], - 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': [{'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': '192.168.1.1'}]} + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + assert await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == [] + await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.1']) + assert await cfg.forcepermissive.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() + await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], + 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': [{'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': '192.168.1.1'}]} + assert not await list_sessions() @pytest.mark.asyncio @@ -1582,53 +1642,54 @@ async def test_dyn_leadership_requires(): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) dyn = DynOptionDescription('leader', '', [interface1], suffixes=Calculation(return_list)) od = OptionDescription('toto', '', [dyn]) - cfg = await Config(od) - await cfg.property.read_write() - assert await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == [] - await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2']) - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None - assert await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == ['192.168.1.2'] - # - await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.1']) - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() - # - await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.2']) - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() is None - await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.set('255.255.255.255') - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() == '255.255.255.255' - assert await cfg.value.dict() == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': ['192.168.1.2', '192.168.1.2'], - 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': [None, '255.255.255.255'], - 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': [], - 'leaderval2.ip_admin_eth0val2.netmask_admin_eth0val2': []} + async with await Config(od) as cfg: + await cfg.property.read_write() + assert await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == [] + await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2']) + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None + assert await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.get() == ['192.168.1.2'] + # + await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.1']) + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() + # + await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.2']) + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() is None + await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.set('255.255.255.255') + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() == '255.255.255.255' + assert await cfg.value.dict() == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': ['192.168.1.2', '192.168.1.2'], + 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': [None, '255.255.255.255'], + 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': [], + 'leaderval2.ip_admin_eth0val2.netmask_admin_eth0val2': []} - ret = await cfg.value.dict(leader_to_list=True) - assert ret == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, - {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': '255.255.255.255'}], - 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} + ret = await cfg.value.dict(leader_to_list=True) + assert ret == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, + {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': '255.255.255.255'}], + 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} - # - await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.1']) - assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() - ret = await cfg.value.dict() - assert set(ret.keys()) == set(['leaderval1.ip_admin_eth0val1.ip_admin_eth0val1', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2', 'leaderval2.ip_admin_eth0val2.netmask_admin_eth0val2']) - assert ret['leaderval1.ip_admin_eth0val1.ip_admin_eth0val1'] == ['192.168.1.2', '192.168.1.1'] - assert len(ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1']) == 2 - assert ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][0] is None - assert isinstance(ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][1], PropertiesOptionError) - del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][1] - del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][0] - del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'] - assert await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', - 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, - {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], - 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} - # - assert await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', - 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, - {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], - 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} + # + await cfg.option('leaderval1.ip_admin_eth0val1.ip_admin_eth0val1').value.set(['192.168.1.2', '192.168.1.1']) + assert await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 1).value.get() + ret = await cfg.value.dict() + assert set(ret.keys()) == set(['leaderval1.ip_admin_eth0val1.ip_admin_eth0val1', 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1', 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2', 'leaderval2.ip_admin_eth0val2.netmask_admin_eth0val2']) + assert ret['leaderval1.ip_admin_eth0val1.ip_admin_eth0val1'] == ['192.168.1.2', '192.168.1.1'] + assert len(ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1']) == 2 + assert ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][0] is None + assert isinstance(ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][1], PropertiesOptionError) + del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][1] + del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'][0] + del ret['leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1'] + assert await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', + 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, + {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], + 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} + # + assert await cfg.value.dict(leader_to_list=True) == {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': [{'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.2', + 'leaderval1.ip_admin_eth0val1.netmask_admin_eth0val1': None}, + {'leaderval1.ip_admin_eth0val1.ip_admin_eth0val1': '192.168.1.1'}], + 'leaderval2.ip_admin_eth0val2.ip_admin_eth0val2': []} + assert not await list_sessions() diff --git a/tests/test_freeze.py b/tests/test_freeze.py index 0710c9c..edd2ab0 100644 --- a/tests/test_freeze.py +++ b/tests/test_freeze.py @@ -8,13 +8,10 @@ import pytest from tiramisu.setting import owners, groups from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ StrOption, OptionDescription, SymLinkOption, Leadership, Config, \ - Calculation, Params, ParamOption, ParamValue, calc_value + Calculation, Params, ParamOption, ParamValue, calc_value, delete_session from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop def compare(calculated, expected): @@ -82,47 +79,49 @@ def return_val3(context, value): @pytest.mark.asyncio async def test_freeze_whole_config(): descr = make_description_freeze() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.property.add('everything_frozen') - assert await cfg.option('gc.dummy').value.get() is False - prop = [] - try: + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.property.add('everything_frozen') + assert await cfg.option('gc.dummy').value.get() is False + prop = [] + try: + await cfg.option('gc.dummy').value.set(True) + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert await cfg.option('gc.dummy').value.get() is False + # + await cfg.property.pop('everything_frozen') await cfg.option('gc.dummy').value.set(True) - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop - assert await cfg.option('gc.dummy').value.get() is False - # - await cfg.property.pop('everything_frozen') - await cfg.option('gc.dummy').value.set(True) - assert await cfg.option('gc.dummy').value.get() is True - # - await cfg.property.add('everything_frozen') - owners.addowner("everythingfrozen2") - prop = [] - try: - await cfg.option('gc.dummy').owner.set('everythingfrozen2') - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop + assert await cfg.option('gc.dummy').value.get() is True + # + await cfg.property.add('everything_frozen') + owners.addowner("everythingfrozen2") + prop = [] + try: + await cfg.option('gc.dummy').owner.set('everythingfrozen2') + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_freeze_one_option(): "freeze an option " descr = make_description_freeze() - cfg = await Config(descr) - await cfg.property.read_write() - #freeze only one option - await cfg.option('gc.dummy').property.add('frozen') - assert await cfg.option('gc.dummy').value.get() is False - prop = [] - try: - await cfg.option('gc.dummy').value.set(True) - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop + async with await Config(descr) as cfg: + await cfg.property.read_write() + #freeze only one option + await cfg.option('gc.dummy').property.add('frozen') + assert await cfg.option('gc.dummy').value.get() is False + prop = [] + try: + await cfg.option('gc.dummy').value.set(True) + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert not await list_sessions() @pytest.mark.asyncio @@ -130,58 +129,62 @@ async def test_frozen_value(): "setattr a frozen value at the config level" s = StrOption("string", "", default="string") descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.property.add('frozen') - await cfg.option('string').property.add('frozen') - prop = [] - try: - await cfg.option('string').value.set('egg') - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.property.add('frozen') + await cfg.option('string').property.add('frozen') + prop = [] + try: + await cfg.option('string').value.set('egg') + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_freeze(): "freeze a whole configuration object" descr = make_description_freeze() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.property.add('frozen') - await cfg.option('gc.name').property.add('frozen') - prop = [] - try: - await cfg.option('gc.name').value.set('framework') - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.property.add('frozen') + await cfg.option('gc.name').property.add('frozen') + prop = [] + try: + await cfg.option('gc.name').value.set('framework') + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_freeze_multi(): descr = make_description_freeze() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.property.add('frozen') - await cfg.option('boolop').property.add('frozen') - prop = [] - try: - await cfg.option('boolop').value.set([True]) - except PropertiesOptionError as err: - prop = err.proptype - assert 'frozen' in prop + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.property.add('frozen') + await cfg.option('boolop').property.add('frozen') + prop = [] + try: + await cfg.option('boolop').value.set([True]) + except PropertiesOptionError as err: + prop = err.proptype + assert 'frozen' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_force_store_value(): descr = make_description_freeze() - cfg = await Config(descr) - compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) - await cfg.option('wantref').value.set(True) - compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced'))) - await cfg.option('wantref').value.reset() - compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) + async with await Config(descr) as cfg: + compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) + await cfg.option('wantref').value.set(True) + compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced'))) + await cfg.option('wantref').value.reset() + compare(await cfg.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced'))) + assert not await list_sessions() @pytest.mark.asyncio @@ -189,8 +192,10 @@ async def test_force_store_value_leadership_follower(): b = IntOption('int', 'Test int option', multi=True) c = StrOption('str', 'Test string option', multi=True, properties=('force_store_value',)) descr = Leadership("int", "", [b, c]) - with pytest.raises(ConfigError): - cfg = await Config(descr) + with pytest.raises(ConfigError): + cfg = await Config(descr, session_id='error') + await delete_session('error') + assert not await list_sessions() #@pytest.mark.asyncio @@ -208,24 +213,27 @@ async def test_force_store_value_leadership_sub(): c = StrOption('str', 'Test string option', multi=True) descr = Leadership("int", "", [b, c]) odr = OptionDescription('odr', '', [descr]) - cfg = await Config(odr) - compare(await cfg.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',))) + async with await Config(odr) as cfg: + compare(await cfg.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',))) + assert not await list_sessions() @pytest.mark.asyncio async def test_force_store_value_callback(): b = IntOption('int', 'Test int option', Calculation(return_val), properties=('force_store_value',)) descr = OptionDescription("int", "", [b]) - cfg = await Config(descr) - compare(await cfg.value.exportation(), (('int',), (None,), (1,), ('forced',))) + async with await Config(descr) as cfg: + compare(await cfg.value.exportation(), (('int',), (None,), (1,), ('forced',))) + assert not await list_sessions() @pytest.mark.asyncio async def test_force_store_value_callback_params(): b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamValue(2)})), properties=('force_store_value',)) descr = OptionDescription("int", "", [b]) - cfg = await Config(descr) - compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) + async with await Config(descr) as cfg: + compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) + assert not await list_sessions() @pytest.mark.asyncio @@ -233,5 +241,6 @@ async def test_force_store_value_callback_params_with_opt(): a = IntOption('val1', "", 2) b = IntOption('int', 'Test int option', Calculation(return_val2, Params(kwargs={'value': ParamOption(a)})), properties=('force_store_value',)) descr = OptionDescription("int", "", [a, b]) - cfg = await Config(descr) - compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) + async with await Config(descr) as cfg: + compare(await cfg.value.exportation(), (('int',), (None,), (2,), ('forced',))) + assert not await list_sessions() diff --git a/tests/test_leadership.py b/tests/test_leadership.py index 5808c99..467bd4d 100644 --- a/tests/test_leadership.py +++ b/tests/test_leadership.py @@ -1,12 +1,12 @@ # coding: utf-8 from .autopath import do_autopath do_autopath() -from .config import config_type, get_config, value_list, global_owner +from .config import config_type, get_config, value_list, global_owner, event_loop import pytest from tiramisu.setting import groups, owners from tiramisu import ChoiceOption, BoolOption, IntOption, IPOption, NetworkOption, NetmaskOption, \ - StrOption, OptionDescription, Leadership, Config + StrOption, OptionDescription, Leadership, Config, delete_session from tiramisu.error import LeadershipError, PropertiesOptionError, APIError, ConfigError from tiramisu.storage import list_sessions @@ -14,10 +14,6 @@ from tiramisu.storage import list_sessions groups.family = groups.GroupType('family') -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def compare(calculated, expected): def convert_list(val): if isinstance(val, list): @@ -68,141 +64,150 @@ def make_description(): @pytest.mark.asyncio async def test_base_config(config_type): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('creole.general.activer_proxy_client').value.get() is False - assert await cfg.option('creole.general.nom_machine').value.get() == "eoleng" - if config_type != 'tiramisu-api': - ret = await cfg.option.find('nom_machine', first=True) - assert await ret.value.get() == "eoleng" - result = {'general.numero_etab': None, 'general.nombre_interfaces': 1, - 'general.serveur_ntp': [], 'interface1.ip_admin_eth0.ip_admin_eth0': None, - 'general.mode_conteneur_actif': False, 'general.time_zone': 'Paris', - 'interface1.ip_admin_eth0.netmask_admin_eth0': None, 'general.nom_machine': - 'eoleng', 'general.activer_proxy_client': False} - assert await cfg.option('creole').value.dict() == result - result = {'serveur_ntp': [], 'mode_conteneur_actif': False, - 'ip_admin_eth0': None, 'time_zone': 'Paris', 'numero_etab': None, - 'netmask_admin_eth0': None, 'nom_machine': 'eoleng', 'activer_proxy_client': - False, 'nombre_interfaces': 1} - assert await cfg.option('creole').value.dict(flatten=True) == result - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(descr) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('creole.general.activer_proxy_client').value.get() is False + assert await cfg.option('creole.general.nom_machine').value.get() == "eoleng" + if config_type != 'tiramisu-api': + ret = await cfg.option.find('nom_machine', first=True) + assert await ret.value.get() == "eoleng" + result = {'general.numero_etab': None, 'general.nombre_interfaces': 1, + 'general.serveur_ntp': [], 'interface1.ip_admin_eth0.ip_admin_eth0': None, + 'general.mode_conteneur_actif': False, 'general.time_zone': 'Paris', + 'interface1.ip_admin_eth0.netmask_admin_eth0': None, 'general.nom_machine': + 'eoleng', 'general.activer_proxy_client': False} + assert await cfg.option('creole').value.dict() == result + result = {'serveur_ntp': [], 'mode_conteneur_actif': False, + 'ip_admin_eth0': None, 'time_zone': 'Paris', 'numero_etab': None, + 'netmask_admin_eth0': None, 'nom_machine': 'eoleng', 'activer_proxy_client': + False, 'nombre_interfaces': 1} + assert await cfg.option('creole').value.dict(flatten=True) == result + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio async def test_get_group_type(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - grp = cfg.option('creole.general') - assert await grp.group_type() == groups.family - assert await grp.group_type() == 'family' - assert isinstance(await grp.group_type(), groups.GroupType) + async with await Config(descr) as cfg: + await cfg.property.read_write() + grp = cfg.option('creole.general') + assert await grp.group_type() == groups.family + assert await grp.group_type() == 'family' + assert isinstance(await grp.group_type(), groups.GroupType) + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_on_groups(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - result = await cfg.option('creole').list('optiondescription', - group_type=groups.family) - group_names = [await res.option.name() for res in result] - assert group_names == ['general', 'interface1'] - for i in await cfg.option('creole').list('optiondescription', - group_type=groups.family): - #test StopIteration - break - result = await cfg.option('creole').list('option', - group_type=groups.family) - assert list(result) == [] - result = await cfg.option('creole.general').list('optiondescription', - group_type=groups.family) - assert list(result) == [] + async with await Config(descr) as cfg: + await cfg.property.read_write() + result = await cfg.option('creole').list('optiondescription', + group_type=groups.family) + group_names = [await res.option.name() for res in result] + assert group_names == ['general', 'interface1'] + for i in await cfg.option('creole').list('optiondescription', + group_type=groups.family): + #test StopIteration + break + result = await cfg.option('creole').list('option', + group_type=groups.family) + assert list(result) == [] + result = await cfg.option('creole.general').list('optiondescription', + group_type=groups.family) + assert list(result) == [] + assert not await list_sessions() @pytest.mark.asyncio async def test_list_recursive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - result = await cfg.option('creole').list('all') - group_names = [await res.option.name() for res in result] - assert group_names == ['general', 'interface1'] - # - result = await cfg.option.list(recursive=True) - group_names = [await res.option.name() for res in result] - assert group_names == ['numero_etab', 'nom_machine', 'nombre_interfaces', - 'activer_proxy_client', 'mode_conteneur_actif', - 'serveur_ntp', 'time_zone', 'ip_admin_eth0', - 'netmask_admin_eth0'] - result = list(await cfg.option.list(recursive=True, type='optiondescription')) - group_names = [await res.option.name() for res in result] - assert group_names == ['general', 'ip_admin_eth0', 'interface1', 'creole'] + async with await Config(descr) as cfg: + await cfg.property.read_write() + result = await cfg.option('creole').list('all') + group_names = [await res.option.name() for res in result] + assert group_names == ['general', 'interface1'] + # + result = await cfg.option.list(recursive=True) + group_names = [await res.option.name() for res in result] + assert group_names == ['numero_etab', 'nom_machine', 'nombre_interfaces', + 'activer_proxy_client', 'mode_conteneur_actif', + 'serveur_ntp', 'time_zone', 'ip_admin_eth0', + 'netmask_admin_eth0'] + result = list(await cfg.option.list(recursive=True, type='optiondescription')) + group_names = [await res.option.name() for res in result] + assert group_names == ['general', 'ip_admin_eth0', 'interface1', 'creole'] + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_on_groups_force_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - result = await cfg.forcepermissive.option('creole.general').list() - group_names = [await res.option.name() for res in result] - ass = ['numero_etab', 'nom_machine', 'nombre_interfaces', - 'activer_proxy_client', 'mode_conteneur_actif', - 'mode_conteneur_actif2', 'serveur_ntp', 'time_zone'] - assert group_names == ass - # mode_conteneur_actif2 is not visible is not forcepermissive - result = await cfg.option('creole.general').list() - group_names = [await res.option.name() for res in result] - ass.remove('mode_conteneur_actif2') - assert group_names == ass + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + result = await cfg.forcepermissive.option('creole.general').list() + group_names = [await res.option.name() for res in result] + ass = ['numero_etab', 'nom_machine', 'nombre_interfaces', + 'activer_proxy_client', 'mode_conteneur_actif', + 'mode_conteneur_actif2', 'serveur_ntp', 'time_zone'] + assert group_names == ass + # mode_conteneur_actif2 is not visible is not forcepermissive + result = await cfg.option('creole.general').list() + group_names = [await res.option.name() for res in result] + ass.remove('mode_conteneur_actif2') + assert group_names == ass + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_group_on_groups_force_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - result = await cfg.forcepermissive.option('creole').list(type='optiondescription', - group_type=groups.family) - group_names = [await res.option.name() for res in result] - assert group_names == ['general', 'interface1', 'new'] + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + result = await cfg.forcepermissive.option('creole').list(type='optiondescription', + group_type=groups.family) + group_names = [await res.option.name() for res in result] + assert group_names == ['general', 'interface1', 'new'] + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_on_groups_props(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('creole.interface1').property.add('disabled') - result = await cfg.option('creole').list(type='optiondescription', - group_type=groups.family) - group_names = [await res.option.name() for res in result] - assert group_names == ['general'] + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('creole.interface1').property.add('disabled') + result = await cfg.option('creole').list(type='optiondescription', + group_type=groups.family) + group_names = [await res.option.name() for res in result] + assert group_names == ['general'] + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_on_empty_group(): - cfg = await Config(OptionDescription("name", "descr", [])) - await cfg.property.read_write() - result = list(await cfg.option.list(type='optiondescription')) - assert result == [] + async with await Config(OptionDescription("name", "descr", [])) as cfg: + await cfg.property.read_write() + result = list(await cfg.option.list(type='optiondescription')) + assert result == [] + assert not await list_sessions() @pytest.mark.asyncio async def test_iter_not_group(): - cfg = await Config(OptionDescription("name", "descr", [])) - await cfg.property.read_write() - try: - list(await cfg.option.list(type='optiondescription', group_type='family')) - except AssertionError: - pass - else: - raise Exception('must raise') + async with await Config(OptionDescription("name", "descr", [])) as cfg: + await cfg.property.read_write() + try: + list(await cfg.option.list(type='optiondescription', group_type='family')) + except AssertionError: + pass + else: + raise Exception('must raise') + assert not await list_sessions() @pytest.mark.asyncio @@ -211,6 +216,7 @@ async def test_groups_with_leader(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) assert interface1.impl_get_group_type() == groups.leadership + assert not await list_sessions() @pytest.mark.asyncio @@ -221,24 +227,25 @@ async def test_groups_is_leader(config_type): var = StrOption('var', "ip rĂ©seau autorisĂ©", multi=True) od2 = OptionDescription('od2', '', [var]) od1 = OptionDescription('od', '', [interface1, od2]) - cfg = await Config(od1) - cfg = await get_config(cfg, config_type) - assert not await cfg.option('od2').option.isleadership() - assert await cfg.option('leadership').option.isleadership() - assert not await cfg.option('od2.var').option.isleader() - assert not await cfg.option('od2.var').option.isfollower() - assert await cfg.option('leadership.ip_admin_eth0').option.ismulti() - assert await cfg.option('leadership.netmask_admin_eth0').option.ismulti() - assert not await cfg.option('leadership.ip_admin_eth0').option.issubmulti() - assert not await cfg.option('leadership.netmask_admin_eth0').option.issubmulti() - assert await cfg.option('leadership.ip_admin_eth0').option.isleader() - assert not await cfg.option('leadership.ip_admin_eth0').option.isfollower() - assert not await cfg.option('leadership.netmask_admin_eth0').option.isleader() - assert await cfg.option('leadership.netmask_admin_eth0').option.isfollower() - assert await cfg.option('leadership.netmask_admin_eth0').option.path() == 'leadership.netmask_admin_eth0' - assert await cfg.option('leadership.netmask_admin_eth0').option.defaultmulti() == 'value' - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od1) as cfg: + cfg = await get_config(cfg, config_type) + assert not await cfg.option('od2').option.isleadership() + assert await cfg.option('leadership').option.isleadership() + assert not await cfg.option('od2.var').option.isleader() + assert not await cfg.option('od2.var').option.isfollower() + assert await cfg.option('leadership.ip_admin_eth0').option.ismulti() + assert await cfg.option('leadership.netmask_admin_eth0').option.ismulti() + assert not await cfg.option('leadership.ip_admin_eth0').option.issubmulti() + assert not await cfg.option('leadership.netmask_admin_eth0').option.issubmulti() + assert await cfg.option('leadership.ip_admin_eth0').option.isleader() + assert not await cfg.option('leadership.ip_admin_eth0').option.isfollower() + assert not await cfg.option('leadership.netmask_admin_eth0').option.isleader() + assert await cfg.option('leadership.netmask_admin_eth0').option.isfollower() + assert await cfg.option('leadership.netmask_admin_eth0').option.path() == 'leadership.netmask_admin_eth0' + assert await cfg.option('leadership.netmask_admin_eth0').option.defaultmulti() == 'value' + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -247,8 +254,10 @@ async def test_groups_with_leader_in_root(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) interface1 - with pytest.raises(ConfigError): - await Config(interface1) + with pytest.raises(ConfigError): + await Config(interface1, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio @@ -257,8 +266,10 @@ async def test_groups_with_leader_in_config(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - await Config(od) + async with await Config(od) as cfg: + pass assert interface1.impl_get_group_type() == groups.leadership + assert not await list_sessions() @pytest.mark.asyncio @@ -267,23 +278,24 @@ async def test_groups_with_leader_make_dict(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': []} - assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': []} - if config_type != 'tiramisu-api': - # FIXME useful? already in leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.len() == 0 - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 0 - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2']) - if config_type != 'tiramisu-api': - # FIXME - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.len() == 2 - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 2 - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip1', 'ip2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None]} - assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': 'ip1', 'ip_admin_eth0.netmask_admin_eth0': None}, {'ip_admin_eth0.ip_admin_eth0': 'ip2', 'ip_admin_eth0.netmask_admin_eth0': None}]} - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': []} + assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': []} + if config_type != 'tiramisu-api': + # FIXME useful? already in leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.len() == 0 + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 0 + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2']) + if config_type != 'tiramisu-api': + # FIXME + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.len() == 2 + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 2 + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip1', 'ip2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None]} + assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': 'ip1', 'ip_admin_eth0.netmask_admin_eth0': None}, {'ip_admin_eth0.ip_admin_eth0': 'ip2', 'ip_admin_eth0.netmask_admin_eth0': None}]} + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -292,15 +304,16 @@ async def test_groups_with_leader_default_value(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2'] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == [] - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2'] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == [] + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -309,27 +322,28 @@ async def test_groups_with_leader_default_value_2(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", default_multi='netmask1', multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2'] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2'] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip3', 'ip4']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip3', 'ip4'] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2'] - # - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('netmask2') - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask2' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1'] - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2'] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2'] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip3', 'ip4']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip3', 'ip4'] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2'] + # + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('netmask2') + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask2' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1'] + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -338,17 +352,18 @@ async def test_groups_with_leader_hidden_in_config(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True, properties=('hidden',)) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('hidden',)) od = OptionDescription('root', '', [interface1]) - cfg = await Config(od) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} + assert not await list_sessions() @pytest.mark.asyncio @@ -357,27 +372,28 @@ async def test_groups_with_leader_hidden_in_config2(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True, properties=('hidden',)) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - cfg = await Config(od) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - #del - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - await cfg.property.pop('hidden') - assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' - await cfg.property.add('hidden') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - await cfg.property.pop('hidden') - assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + #del + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + await cfg.property.pop('hidden') + assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' + await cfg.property.add('hidden') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + await cfg.property.pop('hidden') + assert await cfg.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -386,19 +402,20 @@ async def test_groups_with_leader_reset_empty(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od_ = OptionDescription('root', '', [interface1]) - cfg = await Config(od_) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - if config_type != 'tiramisu-api': - with pytest.raises(LeadershipError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od_) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + if config_type != 'tiramisu-api': + with pytest.raises(LeadershipError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -407,23 +424,24 @@ async def test_groups_with_leader_reset_out_of_range(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od_ = OptionDescription('root', '', [interface1]) - cfg_ori = await Config(od_) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(LeadershipError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.reset() - with pytest.raises(IndexError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(od_) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(LeadershipError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.reset() + with pytest.raises(IndexError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -432,8 +450,9 @@ async def test_allowed_groups(): 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 - with pytest.raises(ValueError): + with pytest.raises(ValueError): interface1.impl_set_group_type('toto') + assert not await list_sessions() @pytest.mark.asyncio @@ -442,24 +461,25 @@ async def test_values_with_leader_disabled_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - with pytest.raises(LeadershipError): - await cfg_ori.option('ip_admin_eth0.ip_admin_eth0').property.add('disabled') - await cfg_ori.option('ip_admin_eth0').property.add('disabled') - cfg = await get_config(cfg_ori, config_type) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('192.168.230.145') - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + with pytest.raises(LeadershipError): + await cfg_ori.option('ip_admin_eth0.ip_admin_eth0').property.add('disabled') + await cfg_ori.option('ip_admin_eth0').property.add('disabled') + cfg = await get_config(cfg_ori, config_type) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('192.168.230.145') + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -467,16 +487,18 @@ async def test_sub_group_in_leader_group(): 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) subgroup = OptionDescription("subgroup", '', []) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [subgroup, ip_admin_eth0, netmask_admin_eth0]) + assert not await list_sessions() @pytest.mark.asyncio async def test_group_always_has_multis(): 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") - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) + assert not await list_sessions() #____________________________________________________________ @@ -486,27 +508,28 @@ async def test_values_with_leader_and_followers1(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await global_owner(cfg, config_type) - cfg = await get_config(cfg, config_type) - assert interface1.impl_get_group_type() == groups.leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(APIError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.set([None]) - with pytest.raises(APIError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.pop(0) - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await global_owner(cfg, config_type) + cfg = await get_config(cfg, config_type) + assert interface1.impl_get_group_type() == groups.leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(APIError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.set([None]) + with pytest.raises(APIError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0').value.pop(0) + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -515,31 +538,33 @@ async def test_reset_values_with_leader_and_followers(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await global_owner(cfg, config_type) - cfg = await Config(maconfig) - assert interface1.impl_get_group_type() == groups.leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - #reset - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await global_owner(cfg, config_type) + async with await Config(maconfig) as cfg: + assert interface1.impl_get_group_type() == groups.leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + #reset + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio async def test_reset_values_with_leader_and_followers_default_value(): ip_admin_eth0 = StrOption('ip_admin_eth0', "ip rĂ©seau autorisĂ©", multi=True, default=['192.168.230.145']) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True, default=['255.255.255.0']) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) + assert not await list_sessions() @pytest.mark.asyncio @@ -548,42 +573,43 @@ async def test_reset_values_with_leader_and_followers_default(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await global_owner(cfg, config_type) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await global_owner(cfg, config_type) + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) - if config_type == 'tiramisu-api': - await cfg.send() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None) + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -592,34 +618,35 @@ async def test_values_with_leader_and_followers_follower(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - if config_type != 'tiramisu-api': - with pytest.raises(LeadershipError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0') - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(APIError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.pop(1) - #reset - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', - '192.168.230.145', - '192.168.230.145']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + if config_type != 'tiramisu-api': + with pytest.raises(LeadershipError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0') + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(APIError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.pop(1) + #reset + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', + '192.168.230.145', + '192.168.230.145']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -628,21 +655,22 @@ async def test_values_with_leader_and_followers_pop(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.146']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0') - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145', '192.168.230.146'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0' - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.146'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.146']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0') + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145', '192.168.230.146'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0' + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.146'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -651,26 +679,27 @@ async def test_values_with_leader_and_followers_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0') - if config_type != 'tiramisu-api': - with pytest.raises(LeadershipError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0' - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0') + if config_type != 'tiramisu-api': + with pytest.raises(LeadershipError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0' + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0' + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -679,30 +708,31 @@ async def test_values_with_leader_and_followers_leader_pop(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.146"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0') - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145", "192.168.230.146"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0' - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (1,)), (('192.168.230.145', '192.168.230.146'), ('255.255.0.0',)), ('user', ('user',)))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0,)), (('192.168.230.146',), ('255.255.0.0',)), ('user', ('user',)))) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.146"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148", "192.168.230.149"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 3).value.set('255.255.0.0') - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 4).value.set('255.255.0.0') - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 3, 4)), (('192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148", "192.168.230.149"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(5) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 3, 4)), (('192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 2, 3)), (('192.168.230.146', "192.168.230.145", "192.168.230.147", "192.168.230.148"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 2)), (('192.168.230.146', "192.168.230.145", "192.168.230.148"), ('255.255.0.0', '255.255.0.0')), ('user', ('user', 'user')))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0,)), (('192.168.230.146', "192.168.230.145"), ('255.255.0.0',)), ('user', ('user',)))) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.146"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0') + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145", "192.168.230.146"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0' + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (1,)), (('192.168.230.145', '192.168.230.146'), ('255.255.0.0',)), ('user', ('user',)))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0,)), (('192.168.230.146',), ('255.255.0.0',)), ('user', ('user',)))) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.146"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148", "192.168.230.149"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 3).value.set('255.255.0.0') + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 4).value.set('255.255.0.0') + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 3, 4)), (('192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148", "192.168.230.149"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(5) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 3, 4)), (('192.168.230.146', "192.168.230.145", "192.168.230.146", "192.168.230.147", "192.168.230.148"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 2, 3)), (('192.168.230.146', "192.168.230.145", "192.168.230.147", "192.168.230.148"), ('255.255.0.0', '255.255.0.0', '255.255.0.0')), ('user', ('user', 'user', 'user')))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0, 2)), (('192.168.230.146', "192.168.230.145", "192.168.230.148"), ('255.255.0.0', '255.255.0.0')), ('user', ('user', 'user')))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(2) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'), (None, (0,)), (('192.168.230.146', "192.168.230.145"), ('255.255.0.0',)), ('user', ('user',)))) + assert not await list_sessions() @pytest.mark.asyncio @@ -711,16 +741,17 @@ async def test_values_with_leader_owner(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await cfg.owner.get() - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert not await list_sessions() @pytest.mark.asyncio @@ -729,62 +760,64 @@ async def test_values_with_leader_disabled(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - if config_type == 'tiramisu-api': - await cfg.send() - #delete with value in disabled var - await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + if config_type == 'tiramisu-api': + await cfg.send() + #delete with value in disabled var + await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - ##append with value in disabled var - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", '192.168.230.43']) - if config_type == 'tiramisu-api': - await cfg.send() + ##append with value in disabled var + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145") + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", '192.168.230.43']) + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio async def test_multi_non_valid_value(config_type): ip_admin_eth0 = StrOption('ip_admin_eth0', "ip rĂ©seau autorisĂ©", multi=True) maconfig = OptionDescription('toto', '', [ip_admin_eth0]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0').value.set(['a']) - with pytest.raises(ValueError): - await cfg.option('ip_admin_eth0').value.set([1]) - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0').value.set(['a']) + with pytest.raises(ValueError): + await cfg.option('ip_admin_eth0').value.set([1]) + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -793,13 +826,14 @@ async def test_multi_leader_default_follower(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", default_multi="255.255.255.0", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -808,16 +842,17 @@ async def test_groups_with_leader_get_modified_value(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - compare(await cfg.value.exportation(), ((), (), (), ())) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0',), (None,), (('192.168.1.1',),), ('user',))) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255') - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0',), (None, (0,)), (('192.168.1.1',), ('255.255.255.255',)), ('user', ('user',)))) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') - compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0',), (None, (0, 1)), (('192.168.1.1', '192.168.1.1'), ('255.255.255.255', '255.255.255.255')), ('user', ('user', 'user')))) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + compare(await cfg.value.exportation(), ((), (), (), ())) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0',), (None,), (('192.168.1.1',),), ('user',))) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255') + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0',), (None, (0,)), (('192.168.1.1',), ('255.255.255.255',)), ('user', ('user',)))) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') + compare(await cfg.value.exportation(), (('ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0',), (None, (0, 1)), (('192.168.1.1', '192.168.1.1'), ('255.255.255.255', '255.255.255.255')), ('user', ('user', 'user')))) + assert not await list_sessions() @pytest.mark.asyncio @@ -826,18 +861,19 @@ async def test_groups_with_leader_importation(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.value.importation([['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'], [None, [0, 1]], [['192.168.1.1', '192.168.1.0'], ['255.255.255.255', '255.255.255.0']], ['user', ['user', 'user']]]) - cfg = await get_config(cfg, config_type) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1', '192.168.1.0'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.255' - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0' - await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == 'user' - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'user' - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'user' - if config_type == 'tiramisu-api': - await cfg.send() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.value.importation([['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'], [None, [0, 1]], [['192.168.1.1', '192.168.1.0'], ['255.255.255.255', '255.255.255.0']], ['user', ['user', 'user']]]) + cfg = await get_config(cfg, config_type) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1', '192.168.1.0'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.255' + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0' + await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == 'user' + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'user' + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'user' + if config_type == 'tiramisu-api': + await cfg.send() + assert not await list_sessions() @pytest.mark.asyncio @@ -847,45 +883,49 @@ async def test_wrong_index(): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od1 = OptionDescription('od', '', [interface1]) maconfig = OptionDescription('toto', '', [od1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - assert await cfg.option('od.ip_admin_eth0.ip_admin_eth0').option.get() - with pytest.raises(APIError): - await cfg.option('od.ip_admin_eth0.ip_admin_eth0', 0).option.get() - assert await cfg.option('od.ip_admin_eth0.netmask_admin_eth0', 0).option.get() - assert await cfg.option('od.ip_admin_eth0').option.get() - with pytest.raises(APIError): - await cfg.option('od.ip_admin_eth0', 0).option.get() - assert await cfg.option('od').option.get() - with pytest.raises(APIError): - await cfg.option('od', 0).option.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + assert await cfg.option('od.ip_admin_eth0.ip_admin_eth0').option.get() + with pytest.raises(APIError): + await cfg.option('od.ip_admin_eth0.ip_admin_eth0', 0).option.get() + assert await cfg.option('od.ip_admin_eth0.netmask_admin_eth0', 0).option.get() + assert await cfg.option('od.ip_admin_eth0').option.get() + with pytest.raises(APIError): + await cfg.option('od.ip_admin_eth0', 0).option.get() + assert await cfg.option('od').option.get() + with pytest.raises(APIError): + await cfg.option('od', 0).option.get() + assert not await list_sessions() @pytest.mark.asyncio async def test_without_leader_or_follower(): - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', []) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip rĂ©seau autorisĂ©", multi=True, default=['1.1.1.1']) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0]) #empty optiondescription is allowed OptionDescription('ip_admin_eth0', '', []) + assert not await list_sessions() @pytest.mark.asyncio async def test_leader_not_multi(): ip_admin_eth0 = StrOption('ip_admin_eth0', "ip rĂ©seau autorisĂ©") netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) + assert not await list_sessions() @pytest.mark.asyncio async def test_follower_not_multi(): 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") - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) + assert not await list_sessions() @pytest.mark.asyncio @@ -895,9 +935,10 @@ async def test_follower_force_store_value(): interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0]) od1 = OptionDescription('od', '', [interface0]) od2 = OptionDescription('toto', '', [od1]) - cfg = await Config(od2) - await cfg.property.read_write() - assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + async with await Config(od2) as cfg: + await cfg.property.read_write() + assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -907,9 +948,10 @@ async def test_follower_force_store_value_read_only(): interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0]) od1 = OptionDescription('od', '', [interface0]) od2 = OptionDescription('toto', '', [od1]) - cfg = await Config(od2) - await cfg.property.read_only() - assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + async with await Config(od2) as cfg: + await cfg.property.read_only() + assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -919,17 +961,18 @@ async def test_follower_force_store_value_reset(): interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0]) od1 = OptionDescription('od', '', [interface0]) od2 = OptionDescription('toto', '', [od1]) - cfg = await Config(od2) - await cfg.property.read_write() - await cfg.option('od.interface0.ip_admin_eth0').value.set(['1.1.1.1', '192.168.0.0']) - assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() - assert not await cfg.option('od.interface0.netmask_admin_eth0', 1).owner.isdefault() - # - await cfg.option('od.interface0.netmask_admin_eth0', 1).value.reset() - assert not await cfg.option('od.interface0.netmask_admin_eth0', 1).owner.isdefault() - # - await cfg.option('od.interface0.ip_admin_eth0').value.pop(0) - await cfg.option('od.interface0.ip_admin_eth0').value.pop(0) - assert await cfg.option('od.interface0.ip_admin_eth0').value.get() == [] - await cfg.option('od.interface0.ip_admin_eth0').value.reset() - assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + async with await Config(od2) as cfg: + await cfg.property.read_write() + await cfg.option('od.interface0.ip_admin_eth0').value.set(['1.1.1.1', '192.168.0.0']) + assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + assert not await cfg.option('od.interface0.netmask_admin_eth0', 1).owner.isdefault() + # + await cfg.option('od.interface0.netmask_admin_eth0', 1).value.reset() + assert not await cfg.option('od.interface0.netmask_admin_eth0', 1).owner.isdefault() + # + await cfg.option('od.interface0.ip_admin_eth0').value.pop(0) + await cfg.option('od.interface0.ip_admin_eth0').value.pop(0) + assert await cfg.option('od.interface0.ip_admin_eth0').value.get() == [] + await cfg.option('od.interface0.ip_admin_eth0').value.reset() + assert not await cfg.option('od.interface0.netmask_admin_eth0', 0).owner.isdefault() + assert not await list_sessions() diff --git a/tests/test_mandatory.py b/tests/test_mandatory.py index 2f4fdb0..67862df 100644 --- a/tests/test_mandatory.py +++ b/tests/test_mandatory.py @@ -11,10 +11,11 @@ from tiramisu import IntOption, StrOption, OptionDescription, \ from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.setting import groups from tiramisu.storage import list_sessions +from .config import event_loop -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +#def teardown_function(function): +# assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) def make_description(): @@ -78,315 +79,332 @@ def make_description3(): @pytest.mark.asyncio async def test_mandatory_ro(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str1').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('str1').value.set('yes') - await cfg.property.read_only() - assert await cfg.option('str1').value.get() == 'yes' + async with await Config(descr) as cfg: + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str1').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str1').value.set('yes') + await cfg.property.read_only() + assert await cfg.option('str1').value.get() == 'yes' + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_ro_dict(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - prop = [] - try: - await cfg.value.dict() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('str1').value.set('yes') - await cfg.option('unicode2').value.set('yes') - await cfg.property.read_only() - try: - await cfg.value.dict() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('str3').value.set(['yes']) - await cfg.property.read_only() - assert await cfg.value.dict() == {'str': 'abc', 'str1': 'yes', 'str3': ['yes'], 'unicode2': 'yes'} + async with await Config(descr) as cfg: + await cfg.property.read_only() + prop = [] + try: + await cfg.value.dict() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str1').value.set('yes') + await cfg.option('unicode2').value.set('yes') + await cfg.property.read_only() + try: + await cfg.value.dict() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str3').value.set(['yes']) + await cfg.property.read_only() + assert await cfg.value.dict() == {'str': 'abc', 'str1': 'yes', 'str3': ['yes'], 'unicode2': 'yes'} + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_rw(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - # not mandatory in rw - await cfg.option('str1').value.get() - await cfg.option('str1').value.set('yes') - assert await cfg.option('str1').value.get() == 'yes' + async with await Config(descr) as cfg: + await cfg.property.read_write() + # not mandatory in rw + await cfg.option('str1').value.get() + await cfg.option('str1').value.set('yes') + assert await cfg.option('str1').value.get() == 'yes' + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_default(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - #not mandatory in rw - await cfg.option('str').value.get() - await cfg.property.read_write() - await cfg.option('str').value.set('yes') - await cfg.property.read_only() - await cfg.option('str').value.get() - await cfg.property.read_write() - await cfg.option('str').value.set(None) - await cfg.property.read_only() - prop = [] - try: + async with await Config(descr) as cfg: + await cfg.property.read_only() + #not mandatory in rw await cfg.option('str').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str').value.set('yes') + await cfg.property.read_only() + await cfg.option('str').value.get() + await cfg.property.read_write() + await cfg.option('str').value.set(None) + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_delete(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - await cfg.option('str').value.get() - try: - await cfg.option('str1').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('str1').value.set('yes') - await cfg.property.read_only() - assert await cfg.option('str1').value.get() == 'yes' - await cfg.property.pop('everything_frozen') - prop = [] - try: - await cfg.option('str1').value.reset() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.option('str').value.reset() + async with await Config(descr) as cfg: + await cfg.property.read_only() + await cfg.option('str').value.get() + try: + await cfg.option('str1').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str1').value.set('yes') + await cfg.property.read_only() + assert await cfg.option('str1').value.get() == 'yes' + await cfg.property.pop('everything_frozen') + prop = [] + try: + await cfg.option('str1').value.reset() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.option('str').value.reset() - assert await cfg.option('str1').value.get() == 'yes' + assert await cfg.option('str1').value.get() == 'yes' + assert not await list_sessions() #valeur vide : None, '', u'', ... @pytest.mark.asyncio async def test_mandatory_none(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str1').value.set(None) - assert await cfg.option('str1').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str1').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + async with await Config(descr) as cfg: + await cfg.option('str1').value.set(None) + assert await cfg.option('str1').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str1').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_empty(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str1').value.set('') - assert await cfg.option('str1').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str1').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + async with await Config(descr) as cfg: + await cfg.option('str1').value.set('') + assert await cfg.option('str1').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str1').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_multi_none(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str3').value.set([None]) - assert await cfg.option('str3').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str3').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('str3').value.set(['yes', None]) - assert await cfg.option('str3').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str3').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + async with await Config(descr) as cfg: + await cfg.option('str3').value.set([None]) + assert await cfg.option('str3').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str3').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('str3').value.set(['yes', None]) + assert await cfg.option('str3').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str3').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_multi_empty(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str3').value.set([]) - assert await cfg.option('str3').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str3').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - # - await cfg.property.read_write() - await cfg.option('str3').value.set(['']) - assert await cfg.option('str3').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str3').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - # - await cfg.property.read_write() - await cfg.option('str3').value.set(['yes', '']) - assert await cfg.option('str3').owner.get() == 'user' - await cfg.property.read_only() - prop = [] - try: - await cfg.option('str3').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + async with await Config(descr) as cfg: + await cfg.option('str3').value.set([]) + assert await cfg.option('str3').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str3').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + # + await cfg.property.read_write() + await cfg.option('str3').value.set(['']) + assert await cfg.option('str3').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str3').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + # + await cfg.property.read_write() + await cfg.option('str3').value.set(['yes', '']) + assert await cfg.option('str3').owner.get() == 'user' + await cfg.property.read_only() + prop = [] + try: + await cfg.option('str3').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_multi_append(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str3').value.set(['yes']) - await cfg.property.read_write() - ret = await cfg.option('str3').value.get() - ret.append(None) + async with await Config(descr) as cfg: + await cfg.option('str3').value.set(['yes']) + await cfg.property.read_write() + ret = await cfg.option('str3').value.get() + ret.append(None) + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_disabled(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str1').value.get() - await cfg.option('str1').property.add('disabled') - await cfg.property.read_only() - pop = [] - try: + async with await Config(descr) as cfg: await cfg.option('str1').value.get() - except PropertiesOptionError as err: - prop = err.proptype - search_prop = {'disabled'} - assert set(prop) == search_prop + await cfg.option('str1').property.add('disabled') + await cfg.property.read_only() + pop = [] + try: + await cfg.option('str1').value.get() + except PropertiesOptionError as err: + prop = err.proptype + search_prop = {'disabled'} + assert set(prop) == search_prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_unicode(): descr = make_description() - cfg = await Config(descr) - await cfg.option('unicode2').value.get() - await cfg.property.read_only() - prop = [] - try: + async with await Config(descr) as cfg: await cfg.option('unicode2').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - await cfg.property.read_write() - await cfg.option('unicode2').value.set(u'') - await cfg.property.read_only() - prop = [] - try: - await cfg.option('unicode2').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop + await cfg.property.read_only() + prop = [] + try: + await cfg.option('unicode2').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + await cfg.property.read_write() + await cfg.option('unicode2').value.set(u'') + await cfg.property.read_only() + prop = [] + try: + await cfg.option('unicode2').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_ro(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_only() - proc = [] - try: - await cfg.option('str').value.get() - except PropertiesOptionError as err: - prop = err.proptype - assert 'mandatory' in prop - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] - await cfg.property.read_write() - await cfg.option('str').value.set('a') - await cfg.property.read_only() - assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_only() + proc = [] + try: + await cfg.option('str').value.get() + except PropertiesOptionError as err: + prop = err.proptype + assert 'mandatory' in prop + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] + await cfg.property.read_write() + await cfg.option('str').value.set('a') + await cfg.property.read_only() + assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_rw(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.option('str').value.get() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] - await cfg.option('str').value.set('a') - assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.option('str').value.get() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3'] + await cfg.option('str').value.set('a') + assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_disabled(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.option('str').value.get() - assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} - await cfg.option('str').property.add('disabled') - assert set(await cfg.value.mandatory()) == {'str1', 'unicode2', 'str3'} + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.option('str').value.get() + assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + await cfg.option('str').property.add('disabled') + assert set(await cfg.value.mandatory()) == {'str1', 'unicode2', 'str3'} + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_hidden(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.permissive.add('hidden') - await cfg.option('str').value.get() - assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} - await cfg.option('str').property.add('hidden') - assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.permissive.add('hidden') + await cfg.option('str').value.get() + assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + await cfg.option('str').property.add('hidden') + assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_frozen(): descr = make_description() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.option('str').value.get() - assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} - await cfg.option('str').property.add('frozen') - await cfg.property.read_only() - assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.option('str').value.get() + assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + await cfg.option('str').property.add('frozen') + await cfg.property.read_only() + assert set(await cfg.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'} + assert not await list_sessions() @pytest.mark.asyncio @@ -397,12 +415,13 @@ async def test_mandatory_leader(): multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.value.dict() + async with await Config(descr) as cfg: + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -413,8 +432,9 @@ async def test_mandatory_warnings_leader(): multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] + async with await Config(descr) as cfg: + assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] + assert not await list_sessions() @pytest.mark.asyncio @@ -424,45 +444,46 @@ async def test_mandatory_leader_empty(): multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - await cfg.property.read_write() - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip2']) - await cfg.property.read_only() - with pytest.raises(PropertiesOptionError): + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + await cfg.property.read_write() await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + await cfg.property.read_write() + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip2']) + await cfg.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert not await list_sessions() @pytest.mark.asyncio @@ -472,22 +493,23 @@ async def test_mandatory_warnings_leader_empty(): multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) - assert list(await cfg.value.mandatory()) == [] + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [''] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0'] + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) + assert list(await cfg.value.mandatory()) == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -497,33 +519,34 @@ async def test_mandatory_follower(): multi=True, properties=('mandatory', )) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], - 'ip_admin_eth0.netmask_admin_eth0': []} - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('') - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - # - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('ip') - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'ip' - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip'], - 'ip_admin_eth0.netmask_admin_eth0': ['ip']} + async with await Config(descr) as cfg: + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], + 'ip_admin_eth0.netmask_admin_eth0': []} + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('') + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + # + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('ip') + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'ip' + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip'], + 'ip_admin_eth0.netmask_admin_eth0': ['ip']} + assert not await list_sessions() @pytest.mark.asyncio @@ -533,27 +556,29 @@ async def test_mandatory_warnings_follower(): multi=True, properties=('mandatory', )) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) descr = OptionDescription('o', '', [interface1]) - cfg = await Config(descr) - await cfg.property.read_only() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - # - await cfg.property.read_write() - assert list(await cfg.value.mandatory()) == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) - assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.netmask_admin_eth0'] + async with await Config(descr) as cfg: + await cfg.property.read_only() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + # + await cfg.property.read_write() + assert list(await cfg.value.mandatory()) == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip']) + assert list(await cfg.value.mandatory()) == ['ip_admin_eth0.netmask_admin_eth0'] + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_warnings_symlink(): descr = make_description_sym() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.option('str').value.get() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] - await cfg.option('str').property.add('frozen') - await cfg.property.read_only() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.option('str').value.get() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] + await cfg.option('str').property.add('frozen') + await cfg.property.read_only() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] + assert not await list_sessions() #@pytest.mark.asyncio @@ -569,10 +594,11 @@ async def test_mandatory_warnings_symlink(): @pytest.mark.asyncio async def test_mandatory_warnings_validate_empty(): descr = make_description2() - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_only() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_only() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'str3'] + assert not await list_sessions() @pytest.mark.asyncio @@ -590,16 +616,17 @@ async def test_mandatory_warnings_requires(): 'no_condition_is_invalid': ParamValue(True)})) stroption3 = StrOption('str3', 'Test string option', multi=True, properties=(mandatory_property,)) descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3]) - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.property.read_write() - await cfg.option('str').value.get() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] - await cfg.property.read_only() - assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] - await cfg.property.read_write() - await cfg.option('str').value.set('yes') - assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.property.read_write() + await cfg.option('str').value.get() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] + await cfg.property.read_only() + assert list(await cfg.value.mandatory()) == ['str', 'str1', 'unicode2'] + await cfg.property.read_write() + await cfg.option('str').value.set('yes') + assert list(await cfg.value.mandatory()) == ['str1', 'unicode2', 'str3'] + assert not await list_sessions() @pytest.mark.asyncio @@ -616,12 +643,13 @@ async def test_mandatory_warnings_requires_leadership(): stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,)) leadership = Leadership('leader', 'leadership', [stroption1, stroption2]) descr = OptionDescription('tiram', '', [stroption, leadership]) - cfg = await Config(descr) - await cfg.option('str').value.set('') - await cfg.option('leader.str1').value.set(['str']) - assert list(await cfg.value.mandatory()) == ['str'] - await cfg.option('str').value.set('yes') - assert list(await cfg.value.mandatory()) == ['leader.str2'] + async with await Config(descr) as cfg: + await cfg.option('str').value.set('') + await cfg.option('leader.str1').value.set(['str']) + assert list(await cfg.value.mandatory()) == ['str'] + await cfg.option('str').value.set('yes') + assert list(await cfg.value.mandatory()) == ['leader.str2'] + assert not await list_sessions() @pytest.mark.asyncio @@ -637,19 +665,21 @@ async def test_mandatory_warnings_requires_leadership_follower(): stroption2 = StrOption('str2', 'Test string option', multi=True, properties=(mandatory_property,)) leadership = Leadership('leader', 'leadership', [stroption, stroption1, stroption2]) descr = OptionDescription('tiram', '', [leadership]) - cfg = await Config(descr) - await cfg.option('leader.str').value.set(['str']) - assert list(await cfg.value.mandatory()) == [] - await cfg.option('leader.str1', 0).value.set('yes') - assert list(await cfg.value.mandatory()) == ['leader.str2'] + async with await Config(descr) as cfg: + await cfg.option('leader.str').value.set(['str']) + assert list(await cfg.value.mandatory()) == [] + await cfg.option('leader.str1', 0).value.set('yes') + assert list(await cfg.value.mandatory()) == ['leader.str2'] + assert not await list_sessions() @pytest.mark.asyncio async def test_mandatory_od_disabled(): descr = make_description() descr = OptionDescription('od', '', [descr]) - cfg = await Config(descr) - await cfg.property.read_only() - assert list(await cfg.value.mandatory()) == ['tiram.str1', 'tiram.unicode2', 'tiram.str3'] - await cfg.option('tiram').property.add('disabled') - assert list(await cfg.value.mandatory()) == [] + async with await Config(descr) as cfg: + await cfg.property.read_only() + assert list(await cfg.value.mandatory()) == ['tiram.str1', 'tiram.unicode2', 'tiram.str3'] + await cfg.option('tiram').property.add('disabled') + assert list(await cfg.value.mandatory()) == [] + assert not await list_sessions() diff --git a/tests/test_metaconfig.py b/tests/test_metaconfig.py index 51c35e9..ceb54f7 100644 --- a/tests/test_metaconfig.py +++ b/tests/test_metaconfig.py @@ -9,11 +9,7 @@ from tiramisu import IntOption, StrOption, NetworkOption, NetmaskOption, BoolOpt valid_network_netmask, valid_not_equal from tiramisu.error import ConfigError, ConflictError, PropertiesOptionError, LeadershipError, APIError from tiramisu.storage import list_sessions -from .config import config_type, get_config - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, delete_sessions, event_loop owners.addowner('config') @@ -49,14 +45,14 @@ def make_description(): async def make_metaconfig(double=False): od2 = make_description() - conf1 = await Config(od2, session_id='conf1') + conf1 = await Config(od2, session_id='conf1', delete_old_session=True) await conf1.property.read_write() - conf2 = await Config(od2, session_id='conf2') + conf2 = await Config(od2, session_id='conf2', delete_old_session=True) await conf2.property.read_write() - meta = await MetaConfig([conf1, conf2], session_id='meta') + meta = await MetaConfig([conf1, conf2], session_id='meta', delete_old_session=True) if double: await meta.owner.set(owners.meta2) - meta = await MetaConfig([meta], session_id='doublemeta') + meta = await MetaConfig([meta], session_id='doublemeta', delete_old_session=True) await meta.property.read_write() await meta.owner.set(owners.meta1) return meta @@ -65,16 +61,18 @@ async def make_metaconfig(double=False): @pytest.mark.asyncio async def test_unknown_config(): meta = await make_metaconfig() - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await meta.config('unknown') + await delete_sessions(meta) @pytest.mark.asyncio async def test_error_metaconfig(): od2 = make_description() conf1 = await Config(od2, session_id='conf1') - with pytest.raises(TypeError): + with pytest.raises(TypeError): await MetaConfig([await GroupConfig([conf1])], session_id='meta') + await delete_sessions(conf1) @pytest.mark.asyncio @@ -85,6 +83,7 @@ async def test_path(): assert await ret.config.path() == 'meta.conf1' ret = await meta.config('conf2') assert await ret.config.path() == 'meta.conf2' + await delete_sessions(meta) @pytest.mark.asyncio @@ -120,6 +119,7 @@ async def test_none(): await conf1.option('od1.i3').value.reset() assert await meta.option('od1.i3').value.get() is await conf1.option('od1.i3').value.get() is await conf2.option('od1.i3').value.get() is None assert await meta.option('od1.i3').owner.get() is await conf1.option('od1.i3').owner.get() is await conf2.option('od1.i3').owner.get() is owners.default + await delete_sessions(meta) @pytest.mark.asyncio @@ -140,6 +140,7 @@ async def test_metaconfig_reset(config_type): assert await meta.option('od1.i2').value.get() == 1 assert await conf1.option('od1.i2').value.get() == 3 assert await conf2.option('od1.i2').value.get() == 1 + await delete_sessions(meta) @pytest.mark.asyncio @@ -175,6 +176,7 @@ async def test_default(): await conf1.option('od1.i2').value.reset() assert await meta.option('od1.i2').value.get() == await conf1.option('od1.i2').value.get() == await conf2.option('od1.i2').value.get() == 1 assert await meta.option('od1.i2').owner.get() is await conf1.option('od1.i2').owner.get() is await conf2.option('od1.i2').owner.get() is owners.default + await delete_sessions(meta) @pytest.mark.asyncio @@ -187,6 +189,7 @@ async def test_contexts(): assert await meta.option('od1.i2').owner.get() == owners.default assert await conf1.option('od1.i2').value.get() == await conf1.option('od1.i2').value.get() == 6 assert await conf1.option('od1.i2').owner.get() == await conf1.option('od1.i2').owner.get() is owners.user + await delete_sessions(meta) @pytest.mark.asyncio @@ -199,6 +202,7 @@ async def test_find(): assert 1 == await ret.value.get() assert await meta.value.dict() == {'od1.i4': 2, 'od1.i1': None, 'od1.i3': None, 'od1.i2': 1, 'od1.i5': [2]} + await delete_sessions(meta) @pytest.mark.asyncio @@ -243,6 +247,7 @@ async def test_meta_meta(): await conf1.option('od1.i2').value.reset() assert await meta.option('od1.i2').value.get() == await meta1.option('od1.i2').value.get() == await conf1.option('od1.i2').value.get() == await conf2.option('od1.i2').value.get() == 1 assert await meta.option('od1.i2').owner.get() is await meta1.option('od1.i2').owner.get() is await conf1.option('od1.i2').owner.get() is await conf2.option('od1.i2').owner.get() is owners.default + await delete_sessions(meta) @pytest.mark.asyncio @@ -252,6 +257,7 @@ async def test_meta_new_config(): assert len(list(await meta.config.list())) == 2 await meta.config.new('newconf1') assert len(list(await meta.config.list())) == 3 + await delete_sessions(meta) @pytest.mark.asyncio @@ -261,6 +267,7 @@ async def test_meta_new_config_owner(): await meta.owner.set('meta') await meta.config.new('newconf1') assert await meta.owner.get() == 'meta' + await delete_sessions(meta) @pytest.mark.asyncio @@ -273,7 +280,8 @@ async def test_meta_new_metaconfig(): newconf2 = await newconf1.config('newconf2') await newconf2.config.new('newconf3') newconf3 = await newconf2.config('newconf3') - assert await newconf3.config.name() == 'newconf3' + assert await newconf3.session.id() == 'newconf3' + await delete_sessions(meta) @pytest.mark.asyncio @@ -298,29 +306,32 @@ async def test_meta_pop_config(): assert await newconf1.value.dict() == {'od1.i1': None, 'od1.i2': 1, 'od1.i3': None, 'od1.i4': 2, 'od1.i5': [2], 'od1.i6': None} # assert len(list(await meta.config.list())) == 2 - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await meta.config.pop('newconf1') + await delete_sessions([meta, newconf1]) @pytest.mark.asyncio async def test_meta_add_config(): od = make_description() od2 = make_description() - meta = await MetaConfig(['name1', 'name2'], optiondescription=od) + meta = await MetaConfig(['name1', 'name2'], optiondescription=od, delete_old_session=True) await meta.option('od1.i1').value.set(2) # assert len(list(await meta.config.list())) == 2 - config = await Config(od, session_id='new') + config = await Config(od, session_id='new', delete_old_session=True) assert await config.value.dict() == {'od1.i1': None, 'od1.i2': 1, 'od1.i3': None, 'od1.i4': 2, 'od1.i5': [2], 'od1.i6': None} await meta.config.add(config) # assert len(list(await meta.config.list())) == 3 assert await config.value.dict() == {'od1.i1': 2, 'od1.i2': 1, 'od1.i3': None, 'od1.i4': 2, 'od1.i5': [2], 'od1.i6': None} # - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): await meta.config.add(config) - with pytest.raises(ValueError): - await meta.config.add(await Config(od2)) + newconfig = await Config(od2) + with pytest.raises(ValueError): + await meta.config.add(newconfig) + await delete_sessions([meta, newconfig]) @pytest.mark.asyncio @@ -333,6 +344,7 @@ async def test_meta_add_config_readd(): await meta.config.add(config) await meta2.config.add(config) assert len(list(await config.config.parents())) == 2 + await delete_sessions([meta, meta2]) @pytest.mark.asyncio @@ -340,9 +352,10 @@ async def test_meta_new_config_wrong_name(): od = make_description() meta = await MetaConfig(['name1', 'name2'], optiondescription=od) assert len(list(await meta.config.list())) == 2 - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): await meta.config.new('name1') assert len(list(await meta.config.list())) == 2 + await delete_sessions(meta) @pytest.mark.asyncio @@ -382,18 +395,19 @@ async def test_meta_meta_set(): dconfigs.append(conf._config_bag.context) assert [conf1._config_bag.context, conf2._config_bag.context] == dconfigs # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await meta.config.find('i1', value=10) - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await meta.config.find('not', value=10) - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await meta.config.find('i6') - with pytest.raises(ValueError): + with pytest.raises(ValueError): await meta.value.set('od1.i6', 7, only_config=True, force_default=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): await meta.value.set('od1.i6', 7, only_config=True, force_default_if_same=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): await meta.value.set('od1.i6', 7, only_config=True, force_dont_change_value=True) + await delete_sessions(meta) @pytest.mark.asyncio @@ -405,15 +419,15 @@ async def test_not_meta(): conf2 = await Config(od2, session_id='conf2') conf3 = await Config(od2) conf4 = await Config(od2, session_id='conf4') - with pytest.raises(TypeError): + with pytest.raises(TypeError): await GroupConfig(conf1) #same name - #with pytest.raises(ConflictError): + #with pytest.raises(ConflictError): # GroupConfig([conf2, conf4], session_id='conf2')") - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): await GroupConfig([conf2, conf2], session_id='conf8') grp = await GroupConfig([conf1, conf2]) - with pytest.raises(APIError): + with pytest.raises(APIError): await grp.option('od1.i1').value.get() conf1, conf2 = await grp.config.list() errors = await grp.value.set('od1.i1', 7) @@ -424,6 +438,7 @@ async def test_not_meta(): assert await conf1.option('od1.i1').owner.get() is await conf2.option('od1.i1').owner.get() is owners.user await grp.option('od1.i1').value.reset() assert await conf1.option('od1.i1').owner.get() is await conf2.option('od1.i1').owner.get() is owners.default + await delete_sessions([conf1, conf2, conf3, conf4]) @pytest.mark.asyncio @@ -438,6 +453,7 @@ async def test_group_find_firsts(): newconf1, newconf2 = await grp.config.list() conf1._config_bag.context == newconf1._config_bag.context conf2._config_bag.context == newconf2._config_bag.context + await delete_sessions([conf1, conf2]) @pytest.mark.asyncio @@ -454,6 +470,7 @@ async def test_group_group(): conf9 = await grp2.config('grp.conf9') assert await conf9.option('od1.i1').value.get() == 2 assert await conf9.option('od1.i1').owner.get() is owners.user + await delete_sessions([conf1, conf2, conf9]) @pytest.mark.asyncio @@ -472,6 +489,7 @@ async def test_group_group_path(): assert await newgrp.config.path() == 'conf9' newgrp = await grp2.config('grp.conf10') assert await newgrp.config.path() == 'conf10' + await delete_sessions([conf1, conf2]) @pytest.mark.asyncio @@ -490,7 +508,7 @@ async def test_meta_unconsistent(): conf4 = await Config(od3, session_id='conf4') meta = await MetaConfig([conf1, conf2]) await meta.owner.set(owners.meta1) - with pytest.raises(TypeError): + with pytest.raises(TypeError): await MetaConfig("string") #same descr but conf1 already in meta assert len(list(await conf1.config.parents())) == 1 @@ -499,8 +517,9 @@ async def test_meta_unconsistent(): assert len(list(await conf1.config.parents())) == 2 assert len(list(await conf3.config.parents())) == 1 #not same descr - with pytest.raises(ValueError): + with pytest.raises(ValueError): await MetaConfig([conf3, conf4]) + await delete_sessions([meta, new_meta, conf4]) @pytest.mark.asyncio @@ -524,7 +543,7 @@ async def test_meta_leadership(): assert conf1._config_bag.context == configs[0]._config_bag.context assert conf2._config_bag.context == configs[1]._config_bag.context await meta.property.read_write() - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await meta.config.find('netmask_admin_eth0') ret = await meta.unrestraint.config.find('netmask_admin_eth0') configs = await ret.config.list() @@ -535,6 +554,7 @@ async def test_meta_leadership(): configs = await ret.config.list() assert conf1._config_bag.context == configs[0]._config_bag.context assert conf2._config_bag.context == configs[1]._config_bag.context + await delete_sessions(meta) @pytest.mark.asyncio @@ -548,7 +568,7 @@ async def test_meta_leadership_value(): meta = await MetaConfig([conf1, conf2], session_id="meta") await conf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.8']) assert await conf1.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - with pytest.raises(APIError): + with pytest.raises(APIError): await conf1.option('ip_admin_eth0.ip_admin_eth0', 0).value.get() # await conf1.option('ip_admin_eth0.ip_admin_eth0').value.reset() @@ -568,7 +588,7 @@ async def test_meta_leadership_value(): # assert await conf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] assert await conf1.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' - + await delete_sessions(meta) @pytest.mark.asyncio @@ -594,6 +614,7 @@ async def test_meta_leadership_value_default(): # await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) assert await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' + await delete_sessions(meta) @pytest.mark.asyncio @@ -608,7 +629,7 @@ async def test_meta_leadership_owners(): await meta.owner.set(owners.meta1) newconf1 = await meta.config('conf1') assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - with pytest.raises(LeadershipError): + with pytest.raises(LeadershipError): await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() # await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) @@ -633,6 +654,7 @@ async def test_meta_leadership_owners(): await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user assert await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.meta1 + await delete_sessions(meta) @pytest.mark.asyncio @@ -674,6 +696,7 @@ async def test_meta_force_default(): assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] + await delete_sessions(meta) @pytest.mark.asyncio @@ -704,6 +727,7 @@ async def test_meta_force_dont_change_value(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user + await delete_sessions(meta) @pytest.mark.asyncio @@ -749,6 +773,7 @@ async def test_meta_force_default_if_same(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1 + await delete_sessions(meta) @pytest.mark.asyncio @@ -794,6 +819,7 @@ async def test_meta_force_default_if_same_and_dont_change(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user + await delete_sessions(meta) @pytest.mark.asyncio @@ -807,8 +833,9 @@ async def test_meta_force_default_and_dont_change(): meta = await MetaConfig([conf1, conf2]) await meta.property.read_write() await meta.owner.set('meta1') - with pytest.raises(ValueError): + with pytest.raises(ValueError): await meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True, force_dont_change_value=True) + await delete_sessions(meta) @pytest.mark.asyncio @@ -825,6 +852,7 @@ async def test_meta_properties_meta(): await meta.property.read_write() ret = await meta.config('conf1') assert await ret.value.dict() == {} + await delete_sessions(meta) @pytest.mark.asyncio @@ -837,8 +865,9 @@ async def test_meta_exception_meta(): conf2 = await Config(od, session_id='conf2') meta = await MetaConfig([conf1, conf2]) await meta.property.read_write() - with pytest.raises(Exception): + with pytest.raises(Exception): await conf1.make_dict() + await delete_sessions(meta) @pytest.mark.asyncio @@ -859,6 +888,7 @@ async def test_meta_properties_requires1(): await meta.option('opt1').value.set(True) # await conf1.option('od2.opt2').value.set(False) + await delete_sessions(meta) @pytest.mark.asyncio @@ -884,6 +914,7 @@ async def test_meta_properties_requires_mandatory(): await conf1.option('eth0_method').value.set('dhcp') await conf1.property.read_only() assert await conf1.value.dict(fullpath=True) == {'probes': True, 'eth0_method': 'dhcp', 'ip_address': '1.1.1.1', 'ip_eth0': '1.1.1.1', 'ip_gw': '1.1.1.2'} + await delete_sessions(meta) @pytest.mark.asyncio @@ -910,6 +941,7 @@ async def test_meta_callback(): await meta.option('val4').value.set('new1') assert await newcfg.value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'} await meta.option('val4').value.reset() + await delete_sessions(meta) @pytest.mark.asyncio @@ -969,6 +1001,7 @@ async def test_meta_callback_follower(): await meta.option('val1.val1').value.pop(1) await meta.option('val1.val1').value.set(['val4']) assert await conf1.value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val4'], 'val1.val3': ['val4'], 'val': 'val'} + await delete_sessions(meta) @pytest.mark.asyncio @@ -1000,6 +1033,7 @@ async def test_meta_reset(): assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await delete_sessions(meta) @pytest.mark.asyncio @@ -1019,11 +1053,11 @@ async def test_meta_properties_meta_copy(): conf3 = await newconf1.config.copy(session_id='conf3') # old fashion meta2 = await conf3.config.metaconfig() - assert await meta.config.name() == await meta2.config.name() + assert await meta.session.id() == await meta2.session.id() # new method meta2 = list(await conf3.config.parents()) assert len(meta2) == 1 - assert await meta.config.name() == await meta2[0].config.name() + assert await meta.session.id() == await meta2[0].session.id() assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} assert await newconf2.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} @@ -1037,6 +1071,7 @@ async def test_meta_properties_meta_copy(): assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf2.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf3.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} + await delete_sessions(meta) @pytest.mark.asyncio @@ -1071,6 +1106,7 @@ async def test_meta_properties_meta_deepcopy(): assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf2.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf3.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} + await delete_sessions([meta, meta2]) @pytest.mark.asyncio @@ -1085,11 +1121,12 @@ async def test_meta_properties_submeta_deepcopy(): meta2 = await MetaConfig([meta1], session_id='meta2') meta_copy = await conf1.config.deepcopy(session_id='conf2', metaconfig_prefix='copy_') - assert await meta_copy.config.name() == 'copy_meta2' + assert await meta_copy.session.id() == 'copy_meta2' newcopy = await meta_copy.config('copy_meta1') - assert await newcopy.config.name() == 'copy_meta1' + assert await newcopy.session.id() == 'copy_meta1' newcopy = await newcopy.config('conf2') - assert await newcopy.config.name() == 'conf2' + assert await newcopy.session.id() == 'conf2' + await delete_sessions([meta2, meta_copy]) @pytest.mark.asyncio @@ -1104,10 +1141,11 @@ async def test_meta_properties_deepcopy_meta(): meta2 = await MetaConfig([meta1], session_id='meta2') meta_copy = await meta1.config.deepcopy(session_id='meta3', metaconfig_prefix='copy_') - assert await meta_copy.config.name() == 'copy_meta2' + assert await meta_copy.session.id() == 'copy_meta2' newcopy = await meta_copy.config('meta3') - assert await newcopy.config.name() == 'meta3' + assert await newcopy.session.id() == 'meta3' assert list(await newcopy.config.list()) == [] + await delete_sessions([meta2, meta_copy]) @pytest.mark.asyncio @@ -1149,6 +1187,7 @@ async def test_meta_properties_submeta_deepcopy_owner(): assert await conf2.option('netmask_admin_eth0').owner.get() == 'conf2_user' assert await conf2.option('ip_admin_eth0').value.get() == '192.168.0.1' assert await conf2.option('ip_admin_eth0').owner.get() == 'conf1_user' + await delete_sessions([meta1, meta2, conf2, meta2_copy]) @pytest.mark.asyncio @@ -1212,6 +1251,7 @@ async def test_meta_properties_meta_set_value(): assert isinstance(ret[0], ValueError) del ret[0] del ret + await delete_sessions(meta) @pytest.mark.asyncio @@ -1251,6 +1291,7 @@ async def test_metaconfig_force_metaconfig_on_freeze(): await cfg.option('dummy1').property.pop('frozen') assert await cfg.option('dummy1').value.get() == 'cfg' assert await cfg.option('dummy1').owner.get() == 'config' + await delete_sessions([meta1, meta2]) @pytest.mark.asyncio @@ -1318,6 +1359,7 @@ async def test_metaconfig_force_metaconfig_on_freeze_option(): await cfg.option('dummy1').property.pop('frozen') assert await cfg.option('dummy1').value.get() == 'cfg' assert await cfg.option('dummy1').owner.get() == 'config' + await delete_sessions([meta1, meta2]) @pytest.mark.asyncio @@ -1327,5 +1369,6 @@ async def test_meta_get_config(): await meta.config.new('meta1', type='metaconfig') assert isinstance(await meta.config.get('meta1'), MetaConfig) assert isinstance(await meta.config.get('name1'), Config) - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await meta.config.get('unknown') + await delete_sessions(meta) diff --git a/tests/test_mixconfig.py b/tests/test_mixconfig.py index 720a3a1..ec30ad4 100644 --- a/tests/test_mixconfig.py +++ b/tests/test_mixconfig.py @@ -7,18 +7,15 @@ from tiramisu.setting import groups, owners from tiramisu import IntOption, StrOption, NetworkOption, NetmaskOption, \ OptionDescription, Leadership, Config, GroupConfig, MixConfig, \ MetaConfig, Params, ParamOption, ParamValue, ParamSelfOption, Calculation, \ - valid_network_netmask + valid_network_netmask, delete_session from tiramisu.error import ConfigError, ConflictError, PropertiesOptionError, LeadershipError, APIError from tiramisu.storage import list_sessions +from .config import delete_sessions, event_loop owners.addowner('mix1') owners.addowner('mix2') -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def return_value(value=None): return value @@ -79,11 +76,11 @@ async def make_mixconfig(double=False): od1 = make_description() od2 = make_description1() od3 = make_description2() - conf1 = await Config(od1, session_id='conf1') + conf1 = await Config(od1, session_id='conf1', delete_old_session=True) await conf1.property.read_write() - conf2 = await Config(od2, session_id='conf2') + conf2 = await Config(od2, session_id='conf2', delete_old_session=True) await conf2.property.read_write() - mix = await MixConfig(od3, [conf1, conf2], session_id='mix') + mix = await MixConfig(od3, [conf1, conf2], session_id='mix', delete_old_session=True) if double: od4 = make_description3() await mix.owner.set(owners.mix2) @@ -103,6 +100,7 @@ async def test_mix_name(): assert await ret.config.path() == 'doublemix.mix.conf1' ret = await mix.config('mix.conf2') assert await ret.config.path() == 'doublemix.mix.conf2' + await delete_sessions(mix) @pytest.mark.asyncio @@ -110,17 +108,20 @@ async def test_mix_not_group(): i1 = IntOption('i1', '') od1 = OptionDescription('od1', '', [i1]) od2 = OptionDescription('od2', '', [od1]) - conf1 = await Config(od2, session_id='conf1') - grp = await GroupConfig([conf1]) - with pytest.raises(TypeError): - await MixConfig(od2, [grp]) + async with await Config(od2, session_id='conf1') as conf1: + grp = await GroupConfig([conf1]) + with pytest.raises(TypeError): + await MixConfig(od2, [grp], session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio async def test_unknown_config(): mix = await make_mixconfig() - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await mix.config('unknown') + await delete_sessions(mix) @pytest.mark.asyncio @@ -157,7 +158,8 @@ async def test_none(): assert await mix.option('od1.i3').value.get() is await newconf1.option('od1.i3').value.get() is await newconf2.option('od1.i3').value.get() is None assert await mix.option('od1.i3').owner.get() is await newconf1.option('od1.i3').owner.get() is await newconf2.option('od1.i3').owner.get() is owners.default # - assert await mix.config.name() == await mix.config.name() + assert await mix.session.id() == await mix.session.id() + await delete_sessions(mix) @pytest.mark.asyncio @@ -175,6 +177,7 @@ async def test_reset(): assert await mix.option('od1.i2').value.get() == 1 assert await newconf1.option('od1.i2').value.get() == 3 assert await newconf2.option('od1.i2').value.get() == 1 + await delete_sessions(mix) @pytest.mark.asyncio @@ -210,6 +213,7 @@ async def test_default(): await newconf1.option('od1.i2').value.reset() assert await mix.option('od1.i2').value.get() == await newconf1.option('od1.i2').value.get() == await newconf2.option('od1.i2').value.get() == 1 assert await mix.option('od1.i2').owner.get() is await newconf1.option('od1.i2').owner.get() is await newconf2.option('od1.i2').owner.get() is owners.default + await delete_sessions(mix) @pytest.mark.asyncio @@ -222,6 +226,8 @@ async def test_contexts(): assert await newconf1.option('od1.i2').value.get() == await newconf1.option('od1.i2').value.get() == 6 assert await newconf1.option('od1.i2').owner.get() == await newconf1.option('od1.i2').owner.get() is owners.user assert len(errors) == 0 + await delete_sessions(mix) + @pytest.mark.asyncio @@ -234,6 +240,7 @@ async def test_find(): assert 1 == await ret.value.get() assert await mix.value.dict() == {'od1.i4': 2, 'od1.i1': None, 'od1.i3': None, 'od1.i2': 1, 'od1.i5': [2]} + await delete_sessions(mix) @pytest.mark.asyncio @@ -278,6 +285,7 @@ async def test_mix_mix(): await newconf1.option('od1.i2').value.reset() assert await mix.option('od1.i2').value.get() == await newmix.option('od1.i2').value.get() == await newconf1.option('od1.i2').value.get() == await newconf2.option('od1.i2').value.get() == 1 assert await mix.option('od1.i2').owner.get() is await newmix.option('od1.i2').owner.get() is await newconf1.option('od1.i2').owner.get() is await newconf2.option('od1.i2').owner.get() is owners.default + await delete_sessions(mix) @pytest.mark.asyncio @@ -318,18 +326,19 @@ async def test_mix_mix_set(): dconfigs.append(conf._config_bag.context) assert [conf1, conf2] == dconfigs # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await mix.config.find('i1', value=10) - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await mix.config.find('not', value=10) - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await mix.config.find('i6') - with pytest.raises(ValueError): + with pytest.raises(ValueError): await mix.value.set('od1.i6', 7, only_config=True, force_default=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): await mix.value.set('od1.i6', 7, only_config=True, force_default_if_same=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): await mix.value.set('od1.i6', 7, only_config=True, force_dont_change_value=True) + await delete_sessions(mix) @pytest.mark.asyncio @@ -349,8 +358,9 @@ async def test_mix_unconsistent(): conf4 = await Config(od4, session_id='conf4') mix = await MixConfig(od2, [conf1, conf2]) await mix.owner.set(owners.mix1) - with pytest.raises(TypeError): - await MixConfig(od2, "string") + with pytest.raises(TypeError): + await MixConfig(od2, "string", session_id='error') + await delete_session('error') # same descr but conf1 already in mix assert len(list(await conf1.config.parents())) == 1 assert len(list(await conf3.config.parents())) == 0 @@ -358,7 +368,8 @@ async def test_mix_unconsistent(): assert len(list(await conf1.config.parents())) == 2 assert len(list(await conf3.config.parents())) == 1 # not same descr - await MixConfig(od2, [conf3, conf4]) + tmix = await MixConfig(od2, [conf3, conf4]) + await delete_sessions([mix, conf3, conf4, tmix, new_mix]) @pytest.mark.asyncio @@ -382,7 +393,7 @@ async def test_mix_leadership(): assert conf1._config_bag.context == configs[0]._config_bag.context assert conf2._config_bag.context == configs[1]._config_bag.context await mix.property.read_write() - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await mix.config.find('netmask_admin_eth0') ret = await mix.unrestraint.config.find('netmask_admin_eth0') configs = await ret.config.list() @@ -395,6 +406,7 @@ async def test_mix_leadership(): assert len(configs) == 2 assert conf1._config_bag.context == configs[0]._config_bag.context assert conf2._config_bag.context == configs[1]._config_bag.context + await delete_sessions(mix) @pytest.mark.asyncio @@ -422,6 +434,7 @@ async def test_mix_leadership_value2(): # await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) assert await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' + await delete_sessions(mix) @pytest.mark.asyncio @@ -447,6 +460,7 @@ async def test_mix_leadership_value_default(): # await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) assert await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0' + await delete_sessions(mix) @pytest.mark.asyncio @@ -461,7 +475,7 @@ async def test_mix_leadership_owners(): await mix.owner.set(owners.mix1) newconf1 = await mix.config('conf1') assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - with pytest.raises(LeadershipError): + with pytest.raises(LeadershipError): await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() # await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) @@ -486,6 +500,7 @@ async def test_mix_leadership_owners(): await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1']) assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user assert await newconf1.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.mix1 + await delete_sessions(mix) @pytest.mark.asyncio @@ -527,6 +542,7 @@ async def test_mix_force_default(): assert await mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4'] + await delete_sessions(mix) @pytest.mark.asyncio @@ -557,6 +573,7 @@ async def test_mix_force_dont_change_value(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user + await delete_sessions(mix) @pytest.mark.asyncio @@ -602,6 +619,7 @@ async def test_mix_force_default_if_same(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1 + await delete_sessions(mix) @pytest.mark.asyncio @@ -647,6 +665,8 @@ async def test_mix_force_default_if_same_and_dont_change(): assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user + await delete_sessions(mix) + @pytest.mark.asyncio @@ -660,8 +680,9 @@ async def test_mix_force_default_and_dont_change(): mix = await MixConfig(od, [conf1, conf2]) await mix.property.read_write() await mix.owner.set('mix1') - with pytest.raises(ValueError): + with pytest.raises(ValueError): await mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True, force_dont_change_value=True) + await delete_sessions(mix) @pytest.mark.asyncio @@ -678,6 +699,7 @@ async def test_mix_properties_mix(): await mix.property.read_write() newconf1 = await mix.config('conf1') assert await newconf1.value.dict() == {} + await delete_sessions(mix) @pytest.mark.asyncio @@ -692,6 +714,8 @@ async def test_mix_exception_mix(): await mix.property.read_write() with pytest.raises(ConfigError): await conf1.value.dict() + await delete_sessions(mix) + @pytest.mark.asyncio @@ -718,6 +742,7 @@ async def test_mix_callback(): await mix.option('val4').value.set('new1') assert await newcfg.value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'} await mix.option('val4').value.reset() + await delete_sessions(mix) @pytest.mark.asyncio @@ -778,6 +803,7 @@ async def test_mix_callback_follower(): await mix.option('val1.val1').value.pop(1) await mix.option('val1.val1').value.set(['val4']) assert await newcfg1.value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val4'], 'val1.val3': ['val4'], 'val': 'val'} + await delete_sessions(mix) @pytest.mark.asyncio @@ -796,27 +822,28 @@ async def test_meta_reset(): od2 = OptionDescription('root', '', [interface1]) conf1 = await Config(od0, session_id='conf1') conf2 = await Config(od1, session_id='conf2') - meta = await MixConfig(od2, [conf1, conf2]) - await meta.property.read_write() - await meta.owner.set('mix1') - assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - newconf1 = await meta.config('conf1') - newconf2 = await meta.config('conf2') + mix = await MixConfig(od2, [conf1, conf2]) + await mix.property.read_write() + await mix.owner.set('mix1') + assert await mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + newconf1 = await mix.config('conf1') + newconf2 = await mix.config('conf2') assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - errors = await meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1']) + errors = await mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1']) assert len(errors) == 0 - assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] + assert await mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] + assert await mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1'] - await meta.value.reset('ip_admin_eth0.ip_admin_eth0') - assert await meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await mix.value.reset('ip_admin_eth0.ip_admin_eth0') + assert await mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf1.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] assert await newconf2.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await delete_sessions(mix) @pytest.mark.asyncio @@ -842,11 +869,11 @@ async def test_mix_properties_mix_copy(): newconf3 = await mix.config('conf3') # old fashion mix2 = await conf3.config.metaconfig() - assert await mix.config.name() == await mix2.config.name() + assert await mix.session.id() == await mix2.session.id() # new method mix2 = list(await conf3.config.parents()) assert len(mix2) == 1 - assert await mix.config.name() == await mix2[0].config.name() + assert await mix.session.id() == await mix2[0].session.id() newconf2 = await mix.config('conf2') assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} @@ -860,6 +887,7 @@ async def test_mix_properties_mix_copy(): assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await conf2.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf3.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} + await delete_sessions(mix) @pytest.mark.asyncio @@ -902,6 +930,7 @@ async def test_mix_properties_mix_deepcopy(): assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf2.value.dict() == {'ip_admin_eth0': ['192.168.1.3']} assert await newconf3.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} + await delete_sessions([mix, mix2]) @pytest.mark.asyncio @@ -924,11 +953,12 @@ async def test_mix_properties_submix_deepcopy(): mix2 = await MixConfig(interface2, [mix1], session_id='mix2') mix_copy = await conf1.config.deepcopy(session_id='conf2', metaconfig_prefix='copy_') - assert await mix_copy.config.name() == 'copy_mix2' - ret = await mix_copy.config('copy_mix1') - assert await ret.config.name() == 'copy_mix1' - ret = await mix_copy.config('copy_mix1.conf2') - assert await ret.config.name() == 'conf2' + assert await mix_copy.session.id() == 'copy_mix2' + ret1 = await mix_copy.config('copy_mix1') + assert await ret1.session.id() == 'copy_mix1' + ret2 = await mix_copy.config('copy_mix1.conf2') + assert await ret2.session.id() == 'conf2' + await delete_sessions([mix1, mix2, mix_copy, ret1, ret2]) @pytest.mark.asyncio @@ -971,6 +1001,7 @@ async def test_mix_properties_submix_deepcopy_owner(): assert await conf2.option('netmask_admin_eth1').owner.get() == 'conf2_user' assert await conf2.option('ip_admin_eth0').value.get() == '192.168.0.1' assert await conf2.option('ip_admin_eth0').owner.get() == 'conf1_user' + await delete_sessions([mix1, mix2, mix1_copy, mix2_copy]) @pytest.mark.asyncio @@ -1050,6 +1081,7 @@ async def test_mix_properties_mix_set_value(): del ret[1] del ret[0] del ret + await delete_sessions(mix) @pytest.mark.asyncio @@ -1098,7 +1130,7 @@ async def test_mix_different_default(): assert await newconf2.value.dict() == {'ip_admin_eth1': ['192.168.1.2']} assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.8']} # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await newsubmix1.option('ip_admin_eth0').value.set(['192.168.1.9']) assert await mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']} assert await newsubmix2.value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']} @@ -1106,7 +1138,7 @@ async def test_mix_different_default(): assert await newconf2.value.dict() == {'ip_admin_eth1': ['192.168.1.2']} assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.8']} # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await newconf2.option('ip_admin_eth0').value.set(['192.168.1.9']) assert await mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']} assert await newsubmix2.value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']} @@ -1121,7 +1153,7 @@ async def test_mix_different_default(): assert await newconf2.value.dict() == {'ip_admin_eth1': ['192.168.1.2']} assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.9']} # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await mix.option('ip_admin_eth1').value.set(['192.168.1.10']) assert await mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']} assert await newsubmix2.value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']} @@ -1150,13 +1182,14 @@ async def test_mix_different_default(): assert await newconf2.value.dict() == {'ip_admin_eth1': ['192.168.1.12']} assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.9']} # - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): await newconf1.option('ip_admin_eth1').value.set(['192.168.1.13']) assert await mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']} assert await newsubmix2.value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']} assert await newsubmix1.value.dict() == {'ip_admin_eth1': ['192.168.1.11']} assert await newconf2.value.dict() == {'ip_admin_eth1': ['192.168.1.12']} assert await newconf1.value.dict() == {'ip_admin_eth0': ['192.168.1.9']} + await delete_sessions(mix) @pytest.mark.asyncio @@ -1210,6 +1243,7 @@ async def test_mix_different_default_reset(): assert await submix1.value.dict() == {'ip_admin_eth1': ['192.168.1.3']} assert await conf2.value.dict() == {'ip_admin_eth1': ['192.168.1.2']} assert await conf1.value.dict() == {'ip_admin_eth0': ['192.168.1.1']} + await delete_sessions(mix) @pytest.mark.asyncio @@ -1233,8 +1267,9 @@ async def test_mix_pop_config(): assert await newconf1.value.dict() == {'od1.i1': None, 'od1.i2': 1, 'od1.i3': None, 'od1.i4': 2, 'od1.i5': [2], 'od1.i6': None} # assert len(list(await mix.config.list())) == 1 - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await mix.config.pop('newconf1') + await delete_sessions([mix, newconf1]) @pytest.mark.asyncio @@ -1253,8 +1288,9 @@ async def test_mix_add_config(): assert len(list(await mix.config.list())) == 3 assert await config.value.dict() == {'od1.i1': 2, 'od1.i2': 1, 'od1.i3': None, 'od1.i4': 2, 'od1.i5': [2], 'od1.i6': None} # - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): await mix.config.add(config) + await delete_sessions(mix) @pytest.mark.asyncio @@ -1267,6 +1303,7 @@ async def test_mix_add_config_readd(): await mix.config.add(config) await mix2.config.add(config) assert len(list(await config.config.parents())) == 2 + await delete_sessions([mix, mix2]) @pytest.mark.asyncio @@ -1274,7 +1311,9 @@ async def test_meta_new_mixconfig(): od = make_description() cfg = await Config(od, session_id='cfg1') meta = await MetaConfig([cfg]) - assert isinstance(await meta.config.new('mixconfig', type="mixconfig"), MixConfig) + mix = await meta.config.new('mixconfig', type="mixconfig") + assert isinstance(mix, MixConfig) + await delete_sessions(meta) @pytest.mark.asyncio @@ -1284,8 +1323,9 @@ async def test_meta_get_mixconfig(): meta = await MetaConfig([cfg]) await meta.config.new('mixconfig', type="mixconfig") assert isinstance(await meta.config.get('mixconfig'), MixConfig) - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): await meta.config.get('unknown') newmix = await meta.config.get('mixconfig') await newmix.config.add(await MixConfig(od, [], session_id='mixconfig2')) assert isinstance(await newmix.config.get('mixconfig2'), MixConfig) + await delete_sessions(meta) diff --git a/tests/test_multi_parents.py b/tests/test_multi_parents.py index ac7686a..e3ad17f 100644 --- a/tests/test_multi_parents.py +++ b/tests/test_multi_parents.py @@ -1,6 +1,7 @@ -from tiramisu import IntOption, OptionDescription, MetaConfig +from tiramisu import IntOption, OptionDescription, MetaConfig, list_sessions from tiramisu.error import ConfigError import pytest +from .config import delete_sessions, event_loop async def make_metaconfig(): @@ -12,7 +13,7 @@ async def make_metaconfig(): i6 = IntOption('i6', '', properties=('disabled',)) od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6]) od2 = OptionDescription('od2', '', [od1]) - return await MetaConfig([], optiondescription=od2, session_id='metacfg1') + return await MetaConfig([], optiondescription=od2, session_id='metacfg1', delete_old_session=True) @pytest.mark.asyncio @@ -24,11 +25,12 @@ async def test_multi_parents_path(): """ metacfg1 = await make_metaconfig() cfg1 = await metacfg1.config.new(type='config', session_id="cfg1") - metacfg2 = await MetaConfig([cfg1], session_id='metacfg2') + metacfg2 = await MetaConfig([cfg1], session_id='metacfg2', delete_old_session=True) # assert await metacfg1.config.path() == 'metacfg1' assert await metacfg2.config.path() == 'metacfg2' assert await cfg1.config.path() == 'metacfg2.metacfg1.cfg1' + await delete_sessions([metacfg1, metacfg2]) @pytest.mark.asyncio @@ -61,16 +63,15 @@ async def test_multi_parents_path_same(): deep = children[0] assert await deep.config.path() == 'test_metacfg3.test_metacfg1.test_metacfg2.test_cfg1' assert await cfg1.option('od1.i1').value.get() == 1 - del orideep - with pytest.raises(ConfigError): - await deep.config.path() + await delete_sessions([metacfg1, orideep]) + @pytest.mark.asyncio async def test_multi_parents_value(): metacfg1 = await make_metaconfig() cfg1 = await metacfg1.config.new(type='config', session_id="cfg1") - metacfg2 = await MetaConfig([cfg1], session_id='metacfg2') + metacfg2 = await MetaConfig([cfg1], session_id='metacfg2', delete_old_session=True) # assert await cfg1.option('od1.i1').value.get() == None assert await cfg1.option('od1.i2').value.get() == 1 @@ -93,3 +94,4 @@ async def test_multi_parents_value(): assert await metacfg2.option('od1.i2').value.get() == 4 assert await metacfg1.option('od1.i2').value.get() == 1 assert await cfg1.option('od1.i2').value.get() == 4 + await delete_sessions([metacfg1, metacfg2]) diff --git a/tests/test_option.py b/tests/test_option.py index f94b40f..17bf65e 100644 --- a/tests/test_option.py +++ b/tests/test_option.py @@ -10,17 +10,13 @@ import warnings from tiramisu.error import APIError, ConfigError from tiramisu import IntOption, SymLinkOption, OptionDescription, Config, Calculation, groups, list_sessions from tiramisu.i18n import _ +from .config import event_loop try: groups.family except: groups.family = groups.GroupType('family') -def teardown_function(function): - # some tests emit a warnings because of doesn't create a Config - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - def a_func(): return None @@ -29,10 +25,10 @@ def a_func(): @pytest.mark.asyncio async def test_option_valid_name(): IntOption('test', '') - with pytest.raises(ValueError): + with pytest.raises(ValueError): IntOption(1, "") i = IntOption("test1", "") - with pytest.raises(ValueError): + with pytest.raises(ValueError): SymLinkOption(1, i) i = SymLinkOption("test1", i) @@ -42,11 +38,11 @@ async def test_option_get_information(): description = "it's ok" string = 'some informations' i = IntOption('test', description) - with pytest.raises(ValueError): + with pytest.raises(ValueError): i.impl_get_information('noinfo') i.impl_set_information('info', string) assert i.impl_get_information('info') == string - with pytest.raises(ValueError): + with pytest.raises(ValueError): i.impl_get_information('noinfo') assert i.impl_get_information('noinfo', 'default') == 'default' assert i.impl_get_information('doc') == description @@ -58,15 +54,17 @@ async def test_option_get_information_config(): string = 'some informations' i = IntOption('test', description) od = OptionDescription('od', '', [i]) - await Config(od) - with pytest.raises(ValueError): + async with await Config(od) as cfg: + pass + with pytest.raises(ValueError): i.impl_get_information('noinfo') - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): i.impl_set_information('info', string) - with pytest.raises(ValueError): + with pytest.raises(ValueError): i.impl_get_information('noinfo') assert i.impl_get_information('noinfo', 'default') == 'default' assert i.impl_get_information('doc') == description + assert not await list_sessions() @pytest.mark.asyncio @@ -76,12 +74,13 @@ async def test_option_get_information_default(): i = IntOption('test', description) i.impl_set_information('noinfo', 'optdefault') od = OptionDescription('od', '', [i]) - cfg = await Config(od) - # - assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault' - # - await cfg.option('test').information.set('noinfo', 'notdefault') - assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault' + async with await Config(od) as cfg: + # + assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'optdefault' + # + await cfg.option('test').information.set('noinfo', 'notdefault') + assert await cfg.option('test').information.get('noinfo', 'falsedefault') == 'notdefault' + assert not await list_sessions() @pytest.mark.asyncio @@ -91,16 +90,18 @@ async def test_option_get_information_config2(): i = IntOption('test', description) i.impl_set_information('info', string) od = OptionDescription('od', '', [i]) - await Config(od) - with pytest.raises(ValueError): + async with await Config(od) as cfg: + pass + with pytest.raises(ValueError): i.impl_get_information('noinfo') - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): i.impl_set_information('info', 'hello') assert i.impl_get_information('info') == string - with pytest.raises(ValueError): + with pytest.raises(ValueError): i.impl_get_information('noinfo') assert i.impl_get_information('noinfo', 'default') == 'default' assert i.impl_get_information('doc') == description + assert not await list_sessions() @pytest.mark.asyncio @@ -110,10 +111,11 @@ async def test_optiondescription_get_information(): o = OptionDescription('test', description, []) o.impl_set_information('info', string) assert o.impl_get_information('info') == string - with pytest.raises(ValueError): + with pytest.raises(ValueError): o.impl_get_information('noinfo') assert o.impl_get_information('noinfo', 'default') == 'default' assert o.impl_get_information('doc') == description + assert not await list_sessions() @pytest.mark.asyncio @@ -121,9 +123,10 @@ async def test_option_isoptiondescription(): i = IntOption('test', '') od = OptionDescription('od', '', [i]) od = OptionDescription('od', '', [od]) - cfg = await Config(od) - assert await cfg.option('od').option.isoptiondescription() - assert not await cfg.option('od.test').option.isoptiondescription() + async with await Config(od) as cfg: + assert await cfg.option('od').option.isoptiondescription() + assert not await cfg.option('od.test').option.isoptiondescription() + assert not await list_sessions() @pytest.mark.asyncio @@ -132,9 +135,10 @@ async def test_option_double(): od = OptionDescription('od1', '', [i]) od = OptionDescription('od2', '', [od]) od = OptionDescription('od3', '', [od]) - cfg = await Config(od) - assert await cfg.option('od2.od1.test').value.get() is None - assert await cfg.option('od2').option('od1').option('test').value.get() is None + async with await Config(od) as cfg: + assert await cfg.option('od2.od1.test').value.get() is None + assert await cfg.option('od2').option('od1').option('test').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -143,17 +147,18 @@ async def test_option_multi(): IntOption('test', '', multi=True, default_multi=1) IntOption('test', '', default=[1], multi=True, default_multi=1) #add default_multi to not multi's option - with pytest.raises(ValueError): + with pytest.raises(ValueError): IntOption('test', '', default_multi=1) #unvalid default_multi - with pytest.raises(ValueError): + with pytest.raises(ValueError): IntOption('test', '', multi=True, default_multi='yes') + assert not await list_sessions() #@pytest.mark.asyncio #async def test_option_multi_legacy(): # #not default_multi with callback -# #with pytest.raises(ValueError): +# #with pytest.raises(ValueError): # IntOption('test', '', multi=True, default_multi=1, callback=a_func)") @@ -162,19 +167,20 @@ async def test_unknown_option(): i = IntOption('test', '') od1 = OptionDescription('od', '', [i]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - # test is an option, not an optiondescription - with pytest.raises(TypeError): - await cfg.option('od.test.unknown').value.get() - # unknown is an unknown option - with pytest.raises(AttributeError): - await cfg.option('unknown').value.get() - # unknown is an unknown option - with pytest.raises(AttributeError): - await cfg.option('od.unknown').value.get() - # unknown is an unknown optiondescription - with pytest.raises(AttributeError): - await cfg.option('od.unknown.suboption').value.get() + async with await Config(od2) as cfg: + # test is an option, not an optiondescription + with pytest.raises(TypeError): + await cfg.option('od.test.unknown').value.get() + # unknown is an unknown option + with pytest.raises(AttributeError): + await cfg.option('unknown').value.get() + # unknown is an unknown option + with pytest.raises(AttributeError): + await cfg.option('od.unknown').value.get() + # unknown is an unknown optiondescription + with pytest.raises(AttributeError): + await cfg.option('od.unknown.suboption').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -188,25 +194,26 @@ async def test_optiondescription_list(): od3.impl_set_group_type(groups.notfamily1) od2 = OptionDescription('od', '', [od1, od3]) od4 = OptionDescription('od', '', [od2]) - cfg = await Config(od4) - assert len(list(await cfg.option('od').list('option'))) == 0 - assert len(list(await cfg.option('od').list('optiondescription'))) == 2 - assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.family))) == 1 - assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1 - assert len(list(await cfg.option('od.od').list('option'))) == 1 - assert len(list(await cfg.option('od.od2').list('option'))) == 1 - try: - list(await cfg.option('od').list('unknown')) - except AssertionError: - pass - else: - raise Exception('must raise') - try: - list(await cfg.option('od').list('option', group_type='toto')) - except AssertionError: - pass - else: - raise Exception('must raise') + async with await Config(od4) as cfg: + assert len(list(await cfg.option('od').list('option'))) == 0 + assert len(list(await cfg.option('od').list('optiondescription'))) == 2 + assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.family))) == 1 + assert len(list(await cfg.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1 + assert len(list(await cfg.option('od.od').list('option'))) == 1 + assert len(list(await cfg.option('od.od2').list('option'))) == 1 + try: + list(await cfg.option('od').list('unknown')) + except AssertionError: + pass + else: + raise Exception('must raise') + try: + list(await cfg.option('od').list('option', group_type='toto')) + except AssertionError: + pass + else: + raise Exception('must raise') + assert not await list_sessions() @pytest.mark.asyncio @@ -219,23 +226,24 @@ async def test_optiondescription_group(): od3 = OptionDescription('od2', '', [i2]) od3.impl_set_group_type(groups.notfamily) od2 = OptionDescription('od', '', [od1, od3]) - cfg = await Config(od2) - assert len(list(await cfg.option.list('option'))) == 0 - assert len(list(await cfg.option.list('optiondescription'))) == 2 - assert len(list(await cfg.option.list('optiondescription', group_type=groups.family))) == 1 - assert len(list(await cfg.option.list('optiondescription', group_type=groups.notfamily))) == 1 - try: - list(await cfg.option.list('unknown')) - except AssertionError: - pass - else: - raise Exception('must raise') - try: - list(await cfg.option.list('option', group_type='toto')) - except AssertionError: - pass - else: - raise Exception('must raise') + async with await Config(od2) as cfg: + assert len(list(await cfg.option.list('option'))) == 0 + assert len(list(await cfg.option.list('optiondescription'))) == 2 + assert len(list(await cfg.option.list('optiondescription', group_type=groups.family))) == 1 + assert len(list(await cfg.option.list('optiondescription', group_type=groups.notfamily))) == 1 + try: + list(await cfg.option.list('unknown')) + except AssertionError: + pass + else: + raise Exception('must raise') + try: + list(await cfg.option.list('option', group_type='toto')) + except AssertionError: + pass + else: + raise Exception('must raise') + assert not await list_sessions() @pytest.mark.asyncio @@ -247,16 +255,18 @@ async def test_optiondescription_group_redefined(): i = IntOption('test', '') od1 = OptionDescription('od', '', [i]) od1.impl_set_group_type(groups.family) - with pytest.raises(ValueError): + with pytest.raises(ValueError): od1.impl_set_group_type(groups.notfamily) + assert not await list_sessions() @pytest.mark.asyncio async def test_optiondescription_group_leadership(): i = IntOption('test', '') od1 = OptionDescription('od', '', [i]) - with pytest.raises(ConfigError): + with pytest.raises(ConfigError): od1.impl_set_group_type(groups.leadership) + assert not await list_sessions() @@ -265,11 +275,12 @@ async def test_asign_optiondescription(): i = IntOption('test', '') od1 = OptionDescription('od', '', [i]) od2 = OptionDescription('od', '', [od1]) - cfg = await Config(od2) - with pytest.raises(APIError): - await cfg.option('od').value.set('test') - with pytest.raises(APIError): - await cfg.option('od').value.reset() + async with await Config(od2) as cfg: + with pytest.raises(APIError): + await cfg.option('od').value.set('test') + with pytest.raises(APIError): + await cfg.option('od').value.reset() + assert not await list_sessions() @pytest.mark.asyncio @@ -277,25 +288,28 @@ async def test_intoption(): i1 = IntOption('test1', 'description', min_number=3) i2 = IntOption('test2', 'description', max_number=3) od = OptionDescription('od', '', [i1, i2]) - cfg = await Config(od) - with pytest.raises(ValueError): - await cfg.option('test1').value.set(2) - await cfg.option('test1').value.set(3) - await cfg.option('test1').value.set(4) - await cfg.option('test2').value.set(2) - await cfg.option('test2').value.set(3) - with pytest.raises(ValueError): - await cfg.option('test2').value.set(4) + async with await Config(od) as cfg: + with pytest.raises(ValueError): + await cfg.option('test1').value.set(2) + await cfg.option('test1').value.set(3) + await cfg.option('test1').value.set(4) + await cfg.option('test2').value.set(2) + await cfg.option('test2').value.set(3) + with pytest.raises(ValueError): + await cfg.option('test2').value.set(4) + assert not await list_sessions() @pytest.mark.asyncio async def test_get_display_type(): i1 = IntOption('test1', 'description', min_number=3) assert i1.get_display_type() == _('integer') + assert not await list_sessions() @pytest.mark.asyncio async def test_option_not_in_config(): i1 = IntOption('test1', 'description', min_number=3) - with pytest.raises(AttributeError): + with pytest.raises(AttributeError): i1.impl_getpath() + assert not await list_sessions() diff --git a/tests/test_option_callback.py b/tests/test_option_callback.py index 2cac717..491aafe 100644 --- a/tests/test_option_callback.py +++ b/tests/test_option_callback.py @@ -1,6 +1,5 @@ from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest import warnings @@ -15,11 +14,7 @@ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu.error import PropertiesOptionError, ConflictError, LeadershipError, ConfigError from tiramisu.i18n import _ from tiramisu.storage import list_sessions - - -def teardown_function(function): - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop def return_val(): @@ -120,7 +115,7 @@ async def test_identical_paths(): have the same name, an exection is raised """ with warnings.catch_warnings(record=True) as w: - with pytest.raises(ConflictError): + with pytest.raises(ConflictError): make_description_duplicates() @@ -134,18 +129,19 @@ async def test_hidden_if_in2(config_type): 'default': ParamValue(None)})) stroption = StrOption('str', 'Test string option', default="abc", properties=(hidden_property,)) descr = OptionDescription('constraints', '', [stroption, intoption]) - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - assert not 'hidden' in await cfg.option('str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('str').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('str').value.set('uvw') - if config_type == 'tiramisu-api': - await cfg.send() - assert 'hidden' in await cfg_ori.unrestraint.option('str').property.get() + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + assert not 'hidden' in await cfg.option('str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('str').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('str').value.set('uvw') + if config_type == 'tiramisu-api': + await cfg.send() + assert 'hidden' in await cfg_ori.unrestraint.option('str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -168,15 +164,16 @@ async def test_hidden_if_in_with_group(config_type): gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption], properties=(hidden_property,)) descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, stroption, intoption]) - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - assert not 'hidden' in await cfg_ori.option('str').property.get() - await cfg.option('int').value.set(1) - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(PropertiesOptionError): - await cfg_ori.option('gc.name').value.get() + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + assert not 'hidden' in await cfg_ori.option('str').property.get() + await cfg.option('int').value.set(1) + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(PropertiesOptionError): + await cfg_ori.option('gc.name').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -199,12 +196,13 @@ async def test_disabled_with_group(): gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption], properties=(disabled_property,)) descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption, stroption, intoption]) - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.option('gc.name').value.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.name').value.get() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.option('gc.name').value.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.name').value.get() + assert not await list_sessions() #____________________________________________________________ @@ -239,26 +237,28 @@ def make_description_callback(): async def test_has_callback(): descr = make_description_callback() # here the owner is 'default' - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('bool').value.set(False) - # because dummy has a callback - await cfg.property.add('freeze') - await cfg.option('gc.dummy').property.add('frozen') - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.set(True) + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('bool').value.set(False) + # because dummy has a callback + await cfg.property.add('freeze') + await cfg.option('gc.dummy').property.add('frozen') + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.set(True) + assert not await list_sessions() @pytest.mark.asyncio async def test_freeze_and_has_callback(): descr = make_description_callback() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('bool').value.set(False) - await cfg.property.add('freeze') - await cfg.option('gc.dummy').property.add('frozen') - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.set(True) + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('bool').value.set(False) + await cfg.property.add('freeze') + await cfg.option('gc.dummy').property.add('frozen') + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.set(True) + assert not await list_sessions() @pytest.mark.asyncio @@ -266,32 +266,33 @@ async def test_callback(config_type): val1 = StrOption('val1', "", Calculation(return_val)) val2 = StrOption('val2', "") maconfig = OptionDescription('rootconfig', '', [val1, val2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == 'val' - await cfg.option('val1').value.set('new-val') - assert await cfg.option('val1').value.get() == 'new-val' - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == 'val' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == 'val' + await cfg.option('val1').value.set('new-val') + assert await cfg.option('val1').value.get() == 'new-val' + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio async def test_params(): - with pytest.raises(ValueError): + with pytest.raises(ValueError): Params('str') - with pytest.raises(ValueError): + with pytest.raises(ValueError): Params(('str',)) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Params(kwargs={'a': 'str'}) @pytest.mark.asyncio async def test_param_option(): val1 = StrOption('val1', "") - with pytest.raises(ValueError): + with pytest.raises(ValueError): ParamOption('str') - with pytest.raises(AssertionError): + with pytest.raises(AssertionError): ParamOption(val1, 'str') @@ -299,9 +300,10 @@ async def test_param_option(): async def test_callback_with_error(config_type): val1 = StrOption("val1", "", Calculation(is_config, Params(ParamValue('string'), kwargs={'value': ParamValue('string')}))) maconfig = OptionDescription('rootconfig', '', [val1]) - cfg = await Config(maconfig) - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == 'no' + async with await Config(maconfig) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == 'no' + assert not await list_sessions() @pytest.mark.asyncio @@ -312,22 +314,23 @@ async def test_callback_value(config_type): val4 = StrOption('val4', "", Calculation(return_value, Params(kwargs={'value': ParamOption(val1)}))) val5 = StrOption('val5', "", Calculation(return_value, Params(ParamValue('yes')))) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == 'val' - assert await cfg.option('val2').value.get() == 'val' - assert await cfg.option('val4').value.get() == 'val' - await cfg.option('val1').value.set('new-val') - assert await cfg.option('val1').value.get() == 'new-val' - assert await cfg.option('val2').value.get() == 'new-val' - assert await cfg.option('val4').value.get() == 'new-val' - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == 'val' - assert await cfg.option('val2').value.get() == 'val' - assert await cfg.option('val3').value.get() == 'yes' - assert await cfg.option('val4').value.get() == 'val' - assert await cfg.option('val5').value.get() == 'yes' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == 'val' + assert await cfg.option('val2').value.get() == 'val' + assert await cfg.option('val4').value.get() == 'val' + await cfg.option('val1').value.set('new-val') + assert await cfg.option('val1').value.get() == 'new-val' + assert await cfg.option('val2').value.get() == 'new-val' + assert await cfg.option('val4').value.get() == 'new-val' + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == 'val' + assert await cfg.option('val2').value.get() == 'val' + assert await cfg.option('val3').value.get() == 'yes' + assert await cfg.option('val4').value.get() == 'val' + assert await cfg.option('val5').value.get() == 'yes' + assert not await list_sessions() @pytest.mark.asyncio @@ -337,17 +340,18 @@ async def test_callback_value_tuple(config_type): val3 = StrOption('val3', "", Calculation(return_concat, Params((ParamOption(val1), ParamOption(val2))))) val4 = StrOption('val4', "", Calculation(return_concat, Params((ParamValue('yes'), ParamValue('no'))))) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == 'val1' - assert await cfg.option('val2').value.get() == 'val2' - assert await cfg.option('val3').value.get() == 'val1.val2' - assert await cfg.option('val4').value.get() == 'yes.no' - await cfg.option('val1').value.set('new-val') - assert await cfg.option('val3').value.get() == 'new-val.val2' - await cfg.option('val1').value.reset() - assert await cfg.option('val3').value.get() == 'val1.val2' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == 'val1' + assert await cfg.option('val2').value.get() == 'val2' + assert await cfg.option('val3').value.get() == 'val1.val2' + assert await cfg.option('val4').value.get() == 'yes.no' + await cfg.option('val1').value.set('new-val') + assert await cfg.option('val3').value.get() == 'new-val.val2' + await cfg.option('val1').value.reset() + assert await cfg.option('val3').value.get() == 'val1.val2' + assert not await list_sessions() @pytest.mark.asyncio @@ -356,15 +360,16 @@ async def test_callback_value_force_permissive2(config_type): val2 = StrOption('val2', "", Calculation(return_value, Params(ParamOption(val1)))) val3 = StrOption('val3', "", Calculation(return_value, Params(ParamOption(val1, True)))) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3]) - cfg = await Config(maconfig) - await cfg.property.read_only() - if config_type != 'tiramisu-api': - with pytest.raises(ConfigError): - await cfg.option('val2').value.get() - await cfg.option('val3').value.get() is None - else: - with pytest.raises(ConfigError): - await get_config(cfg, config_type) + async with await Config(maconfig) as cfg: + await cfg.property.read_only() + if config_type != 'tiramisu-api': + with pytest.raises(ConfigError): + await cfg.option('val2').value.get() + await cfg.option('val3').value.get() is None + else: + with pytest.raises(ConfigError): + await get_config(cfg, config_type) + assert not await list_sessions() @pytest.mark.asyncio @@ -373,11 +378,12 @@ async def test_callback_value_force_permissive_kwargs(): val2 = StrOption('val2', "", Calculation(return_value, Params(value=ParamOption(val1)))) val3 = StrOption('val3', "", Calculation(return_value, Params(value=ParamOption(val1, True)))) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3]) - cfg = await Config(maconfig) - await cfg.property.read_only() - with pytest.raises(ConfigError): - await cfg.option('val2').value.get() - await cfg.option('val3').value.get() is None + async with await Config(maconfig) as cfg: + await cfg.property.read_only() + with pytest.raises(ConfigError): + await cfg.option('val2').value.get() + await cfg.option('val3').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -386,28 +392,30 @@ async def test_callback_symlink(config_type): val2 = SymLinkOption('val2', val1) val3 = StrOption('val3', "", Calculation(return_value, Params(ParamOption(val2)))) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == 'val' - assert await cfg.option('val2').value.get() == 'val' - assert await cfg.option('val3').value.get() == 'val' - await cfg.option('val1').value.set('new-val') - assert await cfg.option('val1').value.get() == 'new-val' - assert await cfg.option('val3').value.get() == 'new-val' - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == 'val' - assert await cfg.option('val3').value.get() == 'val' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == 'val' + assert await cfg.option('val2').value.get() == 'val' + assert await cfg.option('val3').value.get() == 'val' + await cfg.option('val1').value.set('new-val') + assert await cfg.option('val1').value.get() == 'new-val' + assert await cfg.option('val3').value.get() == 'new-val' + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == 'val' + assert await cfg.option('val3').value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_list(): val1 = StrOption('val1', "", Calculation(return_list)) maconfig = OptionDescription('rootconfig', '', [val1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(ValueError): - await cfg.option('val1').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(ValueError): + await cfg.option('val1').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -415,29 +423,31 @@ async def test_callback_list2(): val1 = StrOption('val1', "", Calculation(return_list)) val2 = StrOption('val2', "", Calculation(return_value, Params(ParamOption(val1)))) maconfig = OptionDescription('rootconfig', '', [val1, val2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(ValueError): - await cfg.option('val1').value.get() - #await cfg.val2 - with pytest.raises(ValueError): - await cfg.option('val2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(ValueError): + await cfg.option('val1').value.get() + #await cfg.val2 + with pytest.raises(ValueError): + await cfg.option('val2').value.get() + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_multi(config_type): val1 = StrOption('val1', "", [Calculation(return_val)], multi=True) maconfig = OptionDescription('rootconfig', '', [val1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == ['val'] - await cfg.option('val1').value.set(['new-val']) - assert await cfg.option('val1').value.get() == ['new-val'] - await cfg.option('val1').value.set(['new-val', 'new-val2']) - assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == ['val'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == ['val'] + await cfg.option('val1').value.set(['new-val']) + assert await cfg.option('val1').value.get() == ['new-val'] + await cfg.option('val1').value.set(['new-val', 'new-val2']) + assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == ['val'] + assert not await list_sessions() @pytest.mark.asyncio @@ -452,54 +462,57 @@ async def test_callback_multi_value(config_type): val3 = StrOption('val3', "", [Calculation(return_value, params2)], multi=True) val4 = StrOption('val4', "", Calculation(return_list2, params3), multi=True) maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == ['val'] - assert await cfg.option('val2').value.get() == ['val'] - assert await cfg.option('val4').value.get() == ['val', 'yes'] - await cfg.option('val1').value.set(['new-val']) - assert await cfg.option('val1').value.get() == ['new-val'] - assert await cfg.option('val2').value.get() == ['new-val'] - assert await cfg.option('val4').value.get() == ['new-val', 'yes'] - await cfg.option('val1').value.set(['new-val', 'new-val2']) - assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] - assert await cfg.option('val2').value.get() == ['new-val', 'new-val2'] - assert await cfg.option('val4').value.get() == ['new-val', 'new-val2', 'yes'] - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == ['val'] - assert await cfg.option('val2').value.get() == ['val'] - assert await cfg.option('val3').value.get() == ['yes'] - assert await cfg.option('val4').value.get() == ['val', 'yes'] - await cfg.option('val2').value.set(['val', 'new']) - assert await cfg.option('val1').value.get() == ['val'] - assert await cfg.option('val2').value.get() == ['val', 'new'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == ['val'] + assert await cfg.option('val2').value.get() == ['val'] + assert await cfg.option('val4').value.get() == ['val', 'yes'] + await cfg.option('val1').value.set(['new-val']) + assert await cfg.option('val1').value.get() == ['new-val'] + assert await cfg.option('val2').value.get() == ['new-val'] + assert await cfg.option('val4').value.get() == ['new-val', 'yes'] + await cfg.option('val1').value.set(['new-val', 'new-val2']) + assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] + assert await cfg.option('val2').value.get() == ['new-val', 'new-val2'] + assert await cfg.option('val4').value.get() == ['new-val', 'new-val2', 'yes'] + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == ['val'] + assert await cfg.option('val2').value.get() == ['val'] + assert await cfg.option('val3').value.get() == ['yes'] + assert await cfg.option('val4').value.get() == ['val', 'yes'] + await cfg.option('val2').value.set(['val', 'new']) + assert await cfg.option('val1').value.get() == ['val'] + assert await cfg.option('val2').value.get() == ['val', 'new'] + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_multi_list(config_type): val1 = StrOption('val1', "", Calculation(return_list), multi=True, properties=('notunique',)) maconfig = OptionDescription('rootconfig', '', [val1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == ['val', 'val'] - await cfg.option('val1').value.set(['new-val']) - assert await cfg.option('val1').value.get() == ['new-val'] - await cfg.option('val1').value.set(['new-val', 'new-val2']) - assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] - await cfg.option('val1').value.reset() - assert await cfg.option('val1').value.get() == ['val', 'val'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == ['val', 'val'] + await cfg.option('val1').value.set(['new-val']) + assert await cfg.option('val1').value.get() == ['new-val'] + await cfg.option('val1').value.set(['new-val', 'new-val2']) + assert await cfg.option('val1').value.get() == ['new-val', 'new-val2'] + await cfg.option('val1').value.reset() + assert await cfg.option('val1').value.get() == ['val', 'val'] + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_multi_list_extend(config_type): val1 = StrOption('val1', "", Calculation(return_list2, Params((ParamValue(['1', '2', '3']), ParamValue(['4', '5'])))), multi=True) maconfig = OptionDescription('rootconfig', '', [val1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1').value.get() == ['1', '2', '3', '4', '5'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1').value.get() == ['1', '2', '3', '4', '5'] + assert not await list_sessions() @pytest.mark.asyncio @@ -507,12 +520,13 @@ async def test_callback_multi_callback(config_type): val1 = StrOption('val1', "", [Calculation(return_val)], multi=True) interface1 = OptionDescription('val1', '', [val1]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == ['val'] - await cfg.option('val1.val1').value.set(['val1', undefined]) - assert await cfg.option('val1.val1').value.get() == ['val1', None] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == ['val'] + await cfg.option('val1.val1').value.set(['val1', undefined]) + assert await cfg.option('val1.val1').value.get() == ['val1', None] + assert not await list_sessions() @pytest.mark.asyncio @@ -520,12 +534,13 @@ async def test_callback_multi_callback_default(config_type): val1 = StrOption('val1', "", default_multi=Calculation(return_val), multi=True) interface1 = OptionDescription('val1', '', [val1]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == [] - await cfg.option('val1.val1').value.set(['val1', undefined]) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == [] + await cfg.option('val1.val1').value.set(['val1', undefined]) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val'] + assert not await list_sessions() @pytest.mark.asyncio @@ -534,14 +549,15 @@ async def test_callback_leader_and_followers_leader(config_type): val2 = StrOption('val2', "", multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == ['val'] - await cfg.option('val1.val1').value.set([undefined, undefined]) - assert await cfg.option('val1.val1').value.get() == ['val', 'val'] - assert await cfg.option('val1.val2', 0).value.get() == None - assert await cfg.option('val1.val2', 1).value.get() == None + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == ['val'] + await cfg.option('val1.val1').value.set([undefined, undefined]) + assert await cfg.option('val1.val1').value.get() == ['val', 'val'] + assert await cfg.option('val1.val2', 0).value.get() == None + assert await cfg.option('val1.val2', 1).value.get() == None + assert not await list_sessions() @pytest.mark.asyncio @@ -550,23 +566,24 @@ async def test_callback_follower(config_type): val2 = StrOption('val2', "", Calculation(return_value3, Params(ParamValue(['string', 'new']), {'index': ParamIndex()})), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('val1.val1').value.set(['val']) - assert await cfg.option('val1.val2', 0).value.get() == 'string' - await cfg.option('val1.val1').value.set(['val', 'val1']) - assert await cfg.option('val1.val2', 0).value.get() == 'string' - assert await cfg.option('val1.val2', 1).value.get() == 'new' - await cfg.option('val1.val1').value.set(['val', 'val1', 'val2']) - assert await cfg.option('val1.val2', 0).value.get() == 'string' - assert await cfg.option('val1.val2', 1).value.get() == 'new' - assert await cfg.option('val1.val2', 2).value.get() == None - await cfg.option('val1.val1').value.set(['val', 'val1', 'val2', 'val3']) - assert await cfg.option('val1.val2', 0).value.get() == 'string' - assert await cfg.option('val1.val2', 1).value.get() == 'new' - assert await cfg.option('val1.val2', 2).value.get() == None - assert await cfg.option('val1.val2', 3).value.get() == None + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('val1.val1').value.set(['val']) + assert await cfg.option('val1.val2', 0).value.get() == 'string' + await cfg.option('val1.val1').value.set(['val', 'val1']) + assert await cfg.option('val1.val2', 0).value.get() == 'string' + assert await cfg.option('val1.val2', 1).value.get() == 'new' + await cfg.option('val1.val1').value.set(['val', 'val1', 'val2']) + assert await cfg.option('val1.val2', 0).value.get() == 'string' + assert await cfg.option('val1.val2', 1).value.get() == 'new' + assert await cfg.option('val1.val2', 2).value.get() == None + await cfg.option('val1.val1').value.set(['val', 'val1', 'val2', 'val3']) + assert await cfg.option('val1.val2', 0).value.get() == 'string' + assert await cfg.option('val1.val2', 1).value.get() == 'new' + assert await cfg.option('val1.val2', 2).value.get() == None + assert await cfg.option('val1.val2', 3).value.get() == None + assert not await list_sessions() @pytest.mark.asyncio @@ -577,13 +594,14 @@ async def test_callback_leader_and_followers_leader2(config_type): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val3), {'index': ParamIndex()})), multi=True) interface1 = Leadership('val1', '', [val1, val2, val3, val4]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('val1.val1').value.set(['val']) - assert await cfg.option('val1.val4', 0).value.get() == 'val2' - assert await cfg.option('val1.val3', 0).value.get() == 'val2' - assert await cfg.option('val1.val2', 0).value.get() == 'val2' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('val1.val1').value.set(['val']) + assert await cfg.option('val1.val4', 0).value.get() == 'val2' + assert await cfg.option('val1.val3', 0).value.get() == 'val2' + assert await cfg.option('val1.val2', 0).value.get() == 'val2' + assert not await list_sessions() @pytest.mark.asyncio @@ -594,29 +612,30 @@ async def test_callback_leader_and_followers_leader_mandatory1(config_type): val4 = StrOption('val4', "", Calculation(return_index, Params(ParamOption(val1), {'index': ParamIndex()})), properties=('mandatory',), multi=True) interface1 = Leadership('val1', '', [val1, val3, val4]) maconfig = OptionDescription('rootconfig', '', [val, interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val1').value.get() == ['val'] - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('val1.val1').value.set([undefined, 'val3']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val1').value.get() == ['val', 'val3'] - assert await cfg.option('val1.val3', 0).value.get() == 'val' - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val3', 1).value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val4', 1).value.get() + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val1').value.get() == ['val'] + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('val1.val1').value.set([undefined, 'val3']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val1').value.get() == ['val', 'val3'] + assert await cfg.option('val1.val3', 0).value.get() == 'val' + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val3', 1).value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val4', 1).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -628,31 +647,32 @@ async def test_callback_leader_and_followers_leader_mandatory2(config_type): val4 = StrOption('val4', "", Calculation(return_index, Params(ParamOption(val1), {'val2': ParamOption(val_), 'index': ParamIndex()})), properties=('mandatory',), multi=True) interface1 = Leadership('val1', '', [val1, val3, val4]) maconfig = OptionDescription('rootconfig', '', [val, val_, interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val3', 1).value.get() == 'val_' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 1).value.get() == 'val_' - assert await cfg.option('val1.val1').value.get() == ['val', 'val_'] - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('val1.val1').value.set(['val', 'val_', 'val3']) - assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val3', 1).value.get() == 'val_' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 1).value.get() == 'val_' - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val3', 2).value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val4', 2).value.get() - assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val3', 1).value.get() == 'val_' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 1).value.get() == 'val_' + assert await cfg.option('val1.val1').value.get() == ['val', 'val_'] + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('val1.val1').value.set(['val', 'val_', 'val3']) + assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val3', 1).value.get() == 'val_' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 1).value.get() == 'val_' + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val3', 2).value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val4', 2).value.get() + assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] + assert not await list_sessions() @pytest.mark.asyncio @@ -664,26 +684,27 @@ async def test_callback_leader_and_followers_leader_mandatory3(config_type): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val1), {'index': ParamIndex()})), properties=('mandatory',), multi=True) interface1 = Leadership('val1', '', [val1, val3, val4]) maconfig = OptionDescription('rootconfig', '', [val, val_, interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val3', 1).value.get() == 'val_' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 1).value.get() == 'val_' - assert await cfg.option('val1.val1').value.get() == ['val', 'val_'] - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('val1.val1').value.set(['val', 'val_', 'val3']) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val3', 1).value.get() == 'val_' - assert await cfg.option('val1.val3', 2).value.get() == 'val3' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 1).value.get() == 'val_' - assert await cfg.option('val1.val4', 2).value.get() == 'val3' - assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val3', 1).value.get() == 'val_' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 1).value.get() == 'val_' + assert await cfg.option('val1.val1').value.get() == ['val', 'val_'] + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('val1.val1').value.set(['val', 'val_', 'val3']) + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val3', 1).value.get() == 'val_' + assert await cfg.option('val1.val3', 2).value.get() == 'val3' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 1).value.get() == 'val_' + assert await cfg.option('val1.val4', 2).value.get() == 'val3' + assert await cfg.option('val1.val1').value.get() == ['val', 'val_', 'val3'] + assert not await list_sessions() @pytest.mark.asyncio @@ -694,23 +715,24 @@ async def test_callback_leader_and_followers_leader_mandatory4(config_type): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val1), {'index': ParamIndex()})), properties=('mandatory',), multi=True) interface1 = Leadership('val1', '', [val1, val3, val4]) maconfig = OptionDescription('rootconfig', '', [val, interface1]) - cfg_ori = await Config(maconfig) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - #raises(IndexError, "await cfg.option('val1.val3').value.get()") - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val1').value.get() == ['val'] - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('val1.val1').value.set(['val', 'val3']) - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('val1.val1').value.get() == ['val', 'val3'] - assert await cfg.option('val1.val3', 0).value.get() == 'val' - assert await cfg.option('val1.val3', 1).value.get() == 'val3' - assert await cfg.option('val1.val4', 0).value.get() == 'val' - assert await cfg.option('val1.val4', 1).value.get() == 'val3' + async with await Config(maconfig) as cfg_ori: + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + #raises(IndexError, "await cfg.option('val1.val3').value.get()") + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val1').value.get() == ['val'] + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('val1.val1').value.set(['val', 'val3']) + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('val1.val1').value.get() == ['val', 'val3'] + assert await cfg.option('val1.val3', 0).value.get() == 'val' + assert await cfg.option('val1.val3', 1).value.get() == 'val3' + assert await cfg.option('val1.val4', 0).value.get() == 'val' + assert await cfg.option('val1.val4', 1).value.get() == 'val3' + assert not await list_sessions() @pytest.mark.asyncio @@ -721,10 +743,11 @@ async def test_callback_leader_and_followers_leader3(): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val3), {'index': ParamIndex()})), multi=True) interface1 = Leadership('val1', '', [val1, val2, val3, val4]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - # FIXME cfg = await get_config(cfg, config_type) - assert list(await cfg.value.mandatory()) == ['val1.val1'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + # FIXME cfg = await get_config(cfg, config_type) + assert list(await cfg.value.mandatory()) == ['val1.val1'] + assert not await list_sessions() @pytest.mark.asyncio @@ -735,12 +758,13 @@ async def test_callback_leader_and_followers_leader4(): val4 = StrOption('val4', "", Calculation(calc_value, Params(ParamOption(val3), {'index': ParamIndex()})), multi=True) interface1 = Leadership('val1', '', [val1, val2, val3, val4]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - # FIXME cfg = await get_config(cfg, config_type) - await cfg.property.add('expert') - await cfg.permissive.add('expert') - assert list(await cfg.value.mandatory()) == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + # FIXME cfg = await get_config(cfg, config_type) + await cfg.property.add('expert') + await cfg.permissive.add('expert') + assert list(await cfg.value.mandatory()) == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -750,16 +774,17 @@ async def test_consistency_leader_and_followers_leader_mandatory_transitive(): val2 = NetmaskOption('val2', "", multi=True, default_multi='255.255.255.0', properties=('disabled', 'mandatory'), validators=[Calculation(valid_ip_netmask, Params((ParamOption(val1), ParamSelfOption())))]) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - # FIXME cfg = await get_config(cfg, config_type) - try: - await cfg.option('val1.val2', 0).value.get() - except PropertiesOptionError as error: - assert str(error) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'val2', _('property'), '"disabled"')) - else: - raise Exception('must raises') - assert list(await cfg.value.mandatory()) == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + # FIXME cfg = await get_config(cfg, config_type) + try: + await cfg.option('val1.val2', 0).value.get() + except PropertiesOptionError as error: + assert str(error) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'val2', _('property'), '"disabled"')) + else: + raise Exception('must raises') + assert list(await cfg.value.mandatory()) == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -768,24 +793,25 @@ async def test_callback_leader_and_followers_leader_list(config_type): val2 = StrOption('val2', "", multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == ['val', 'val'] - assert await cfg.option('val1.val2', 0).value.get() == None - assert await cfg.option('val1.val2', 1).value.get() == None - await cfg.option('val1.val1').value.set(['val', 'val', undefined]) - assert await cfg.option('val1.val1').value.get() == ['val', 'val', None] - assert await cfg.option('val1.val2', 0).value.get() == None - assert await cfg.option('val1.val2', 1).value.get() == None - assert await cfg.option('val1.val2', 2).value.get() == None - await cfg.option('val1.val1').value.reset() - assert await cfg.option('val1.val1').value.get() == ['val', 'val'] - assert await cfg.option('val1.val2', 0).value.get() == None - assert await cfg.option('val1.val2', 1).value.get() == None - await cfg.option('val1.val1').value.pop(1) - assert await cfg.option('val1.val1').value.get() == ['val'] - assert await cfg.option('val1.val2', 0).value.get() == None + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == ['val', 'val'] + assert await cfg.option('val1.val2', 0).value.get() == None + assert await cfg.option('val1.val2', 1).value.get() == None + await cfg.option('val1.val1').value.set(['val', 'val', undefined]) + assert await cfg.option('val1.val1').value.get() == ['val', 'val', None] + assert await cfg.option('val1.val2', 0).value.get() == None + assert await cfg.option('val1.val2', 1).value.get() == None + assert await cfg.option('val1.val2', 2).value.get() == None + await cfg.option('val1.val1').value.reset() + assert await cfg.option('val1.val1').value.get() == ['val', 'val'] + assert await cfg.option('val1.val2', 0).value.get() == None + assert await cfg.option('val1.val2', 1).value.get() == None + await cfg.option('val1.val1').value.pop(1) + assert await cfg.option('val1.val1').value.get() == ['val'] + assert await cfg.option('val1.val2', 0).value.get() == None + assert not await list_sessions() @pytest.mark.asyncio @@ -794,18 +820,19 @@ async def test_callback_leader_and_followers_leader_follower_list(config_type): val2 = StrOption('val2', "", Calculation(return_list), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == [] - if config_type == 'tiramisu-api': - # when "tiramisu-api", raise when set and not in get function - with pytest.raises(ConfigError): + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == [] + if config_type == 'tiramisu-api': + # when "tiramisu-api", raise when set and not in get function + with pytest.raises(ConfigError): + await cfg.option('val1.val1').value.set(['val1']) + else: await cfg.option('val1.val1').value.set(['val1']) - else: - await cfg.option('val1.val1').value.set(['val1']) - with pytest.raises(LeadershipError): - await cfg.option('val1.val2', 0).value.get() + with pytest.raises(LeadershipError): + await cfg.option('val1.val2', 0).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -814,40 +841,41 @@ async def test_callback_leader_and_followers_follower(config_type): val2 = StrOption('val2', "", Calculation(return_val), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == [] - # - await cfg.option('val1.val1').value.set(['val1']) - assert await cfg.option('val1.val1').value.get() == ['val1'] - assert await cfg.option('val1.val2', 0).value.get() == 'val' - # - await cfg.option('val1.val1').value.set(['val1', 'val2']) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] - assert await cfg.option('val1.val2', 0).value.get() == 'val' - assert await cfg.option('val1.val2', 1).value.get() == 'val' - # - await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2', 'val3'] - assert await cfg.option('val1.val2', 0).value.get() == 'val' - assert await cfg.option('val1.val2', 1).value.get() == 'val' - assert await cfg.option('val1.val2', 2).value.get() == 'val' - # - await cfg.option('val1.val1').value.pop(2) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] - assert await cfg.option('val1.val2', 0).value.get() == 'val' - assert await cfg.option('val1.val2', 1).value.get() == 'val' - # - await cfg.option('val1.val2', 0).value.set('val2') - await cfg.option('val1.val2', 1).value.set('val2') - assert await cfg.option('val1.val2', 0).value.get() == 'val2' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - # - await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('val1.val2', 0).value.get() == 'val2' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val2', 2).value.get() == 'val' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == [] + # + await cfg.option('val1.val1').value.set(['val1']) + assert await cfg.option('val1.val1').value.get() == ['val1'] + assert await cfg.option('val1.val2', 0).value.get() == 'val' + # + await cfg.option('val1.val1').value.set(['val1', 'val2']) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] + assert await cfg.option('val1.val2', 0).value.get() == 'val' + assert await cfg.option('val1.val2', 1).value.get() == 'val' + # + await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2', 'val3'] + assert await cfg.option('val1.val2', 0).value.get() == 'val' + assert await cfg.option('val1.val2', 1).value.get() == 'val' + assert await cfg.option('val1.val2', 2).value.get() == 'val' + # + await cfg.option('val1.val1').value.pop(2) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] + assert await cfg.option('val1.val2', 0).value.get() == 'val' + assert await cfg.option('val1.val2', 1).value.get() == 'val' + # + await cfg.option('val1.val2', 0).value.set('val2') + await cfg.option('val1.val2', 1).value.set('val2') + assert await cfg.option('val1.val2', 0).value.get() == 'val2' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + # + await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('val1.val2', 0).value.get() == 'val2' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val2', 2).value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio @@ -856,8 +884,9 @@ async def test_callback_leader_and_followers(): val2 = StrOption('val2', "", Calculation(return_val), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + assert not await list_sessions() @pytest.mark.asyncio @@ -867,42 +896,43 @@ async def test_callback_leader_and_followers_follower_cal(config_type): val2 = StrOption('val2', "", Calculation(return_val), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1, val3]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - # - assert await cfg.option('val3').value.get() == [] - assert await cfg.option('val1.val1').value.get() == [] - # - await cfg.option('val1.val1').value.set(['val1']) - await cfg.option('val3').value.set(['val1']) - assert await cfg.option('val1.val1').value.get() == ['val1'] - assert await cfg.option('val1.val2', 0).value.get() == 'val' - # - await cfg.option('val1.val1').value.reset() - await cfg.option('val1.val2', 0).value.set('val') - # - await cfg.option('val3').value.set(['val1', 'val2']) - assert await cfg.option('val1.val2', 0).value.get() == 'val' - assert await cfg.option('val1.val2', 1).value.get() == 'val' - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] - # len of follower is higher than leader's one - await cfg.option('val1.val2', 0).value.set('val1') - await cfg.option('val1.val2', 1).value.set('val2') - if config_type == 'tiramisu-api': - # when "tiramisu-api", raise when set and not in get function - with pytest.raises(ConfigError): - await cfg.option('val3').value.set(['val1']) - else: + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + # + assert await cfg.option('val3').value.get() == [] + assert await cfg.option('val1.val1').value.get() == [] + # + await cfg.option('val1.val1').value.set(['val1']) await cfg.option('val3').value.set(['val1']) assert await cfg.option('val1.val1').value.get() == ['val1'] - with pytest.raises(LeadershipError): - await cfg.option('val1.val2', 0).value.get() - # - await cfg.option('val3').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('val1.val2', 0).value.get() == 'val1' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val2', 2).value.get() == 'val' + assert await cfg.option('val1.val2', 0).value.get() == 'val' + # + await cfg.option('val1.val1').value.reset() + await cfg.option('val1.val2', 0).value.set('val') + # + await cfg.option('val3').value.set(['val1', 'val2']) + assert await cfg.option('val1.val2', 0).value.get() == 'val' + assert await cfg.option('val1.val2', 1).value.get() == 'val' + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] + # len of follower is higher than leader's one + await cfg.option('val1.val2', 0).value.set('val1') + await cfg.option('val1.val2', 1).value.set('val2') + if config_type == 'tiramisu-api': + # when "tiramisu-api", raise when set and not in get function + with pytest.raises(ConfigError): + await cfg.option('val3').value.set(['val1']) + else: + await cfg.option('val3').value.set(['val1']) + assert await cfg.option('val1.val1').value.get() == ['val1'] + with pytest.raises(LeadershipError): + await cfg.option('val1.val2', 0).value.get() + # + await cfg.option('val3').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('val1.val2', 0).value.get() == 'val1' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val2', 2).value.get() == 'val' + assert not await list_sessions() @pytest.mark.asyncio @@ -912,14 +942,15 @@ async def test_callback_leader_and_followers_leader_disabled(): val2 = StrOption('val2', "", multi=True) interface1 = Leadership('val1', '', [val1, val2], properties=('disabled',)) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val1').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val1').value.set(['yes']) - with pytest.raises(PropertiesOptionError): - await cfg.option('val1.val2', 0).value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val1').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val1').value.set(['yes']) + with pytest.raises(PropertiesOptionError): + await cfg.option('val1.val2', 0).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -929,16 +960,17 @@ async def test_callback_leader_and_followers_leader_callback_disabled(): val2 = StrOption('val2', "", multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1, val0]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('val1.val1').value.get() - with pytest.raises(ConfigError): - await cfg.option('val1.val2').value.get() - await cfg.property.pop('disabled') - await cfg.option('val1.val1').value.set([]) - await cfg.property.add('disabled') - assert await cfg.option('val1.val1').value.get() == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('val1.val1').value.get() + with pytest.raises(ConfigError): + await cfg.option('val1.val2').value.get() + await cfg.property.pop('disabled') + await cfg.option('val1.val1').value.set([]) + await cfg.property.add('disabled') + assert await cfg.option('val1.val1').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -947,25 +979,26 @@ async def test_callback_leader_and_followers_follower_disabled(): val2 = StrOption('val2', "", multi=True, properties=('disabled',)) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - assert await cfg.option('val1.val1').value.get() == [] - await cfg.option('val1.val1').value.set(['yes']) - assert await cfg.option('val1.val1').value.get() == ['yes'] - await cfg.property.pop('disabled') - assert await cfg.option('val1.val2', 0).value.get() == None - await cfg.option('val1.val2', 0).value.set('no') - await cfg.option('val1.val1').value.set(['yes', 'yes2', 'yes3']) - await cfg.option('val1.val2', 2).value.set('no1') - assert await cfg.option('val1.val2', 0).value.get() == 'no' - assert await cfg.option('val1.val2', 1).value.get() == None - assert await cfg.option('val1.val2', 2).value.get() == 'no1' - await cfg.property.add('disabled') - await cfg.option('val1.val1').value.pop(0) - assert await cfg.option('val1.val1').value.get() == ['yes2', 'yes3'] - await cfg.property.pop('disabled') - assert await cfg.option('val1.val2', 0).value.get() == None - assert await cfg.option('val1.val2', 1).value.get() == 'no1' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + assert await cfg.option('val1.val1').value.get() == [] + await cfg.option('val1.val1').value.set(['yes']) + assert await cfg.option('val1.val1').value.get() == ['yes'] + await cfg.property.pop('disabled') + assert await cfg.option('val1.val2', 0).value.get() == None + await cfg.option('val1.val2', 0).value.set('no') + await cfg.option('val1.val1').value.set(['yes', 'yes2', 'yes3']) + await cfg.option('val1.val2', 2).value.set('no1') + assert await cfg.option('val1.val2', 0).value.get() == 'no' + assert await cfg.option('val1.val2', 1).value.get() == None + assert await cfg.option('val1.val2', 2).value.get() == 'no1' + await cfg.property.add('disabled') + await cfg.option('val1.val1').value.pop(0) + assert await cfg.option('val1.val1').value.get() == ['yes2', 'yes3'] + await cfg.property.pop('disabled') + assert await cfg.option('val1.val2', 0).value.get() == None + assert await cfg.option('val1.val2', 1).value.get() == 'no1' + assert not await list_sessions() @pytest.mark.asyncio @@ -975,17 +1008,18 @@ async def test_callback_leader_and_followers_follower_callback_disabled(): val2 = StrOption('val2', "", Calculation(return_value, Params(ParamOption(val0))), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1, val0]) - cfg = await Config(maconfig) - await cfg.property.read_write() - assert await cfg.option('val1.val1').value.get() == [] - await cfg.option('val1.val1').value.set(['yes']) - assert await cfg.option('val1.val1').value.get() == ['yes'] - await cfg.property.pop('disabled') - await cfg.option('val1.val2', 0).value.set('no') - await cfg.option('val1.val1').value.set(['yes', 'yes1']) - assert await cfg.option('val1.val2', 0).value.get() == 'no' - await cfg.property.add('disabled') - await cfg.option('val1.val1').value.pop(1) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + assert await cfg.option('val1.val1').value.get() == [] + await cfg.option('val1.val1').value.set(['yes']) + assert await cfg.option('val1.val1').value.get() == ['yes'] + await cfg.property.pop('disabled') + await cfg.option('val1.val2', 0).value.set('no') + await cfg.option('val1.val1').value.set(['yes', 'yes1']) + assert await cfg.option('val1.val2', 0).value.get() == 'no' + await cfg.property.add('disabled') + await cfg.option('val1.val1').value.pop(1) + assert not await list_sessions() @pytest.mark.asyncio @@ -998,78 +1032,79 @@ async def test_callback_leader_and_followers_value(): val6 = StrOption('val6', "", Calculation(return_value, Params(ParamOption(val5))), multi=True) interface1 = Leadership('val1', '', [val1, val2, val3, val5, val6]) maconfig = OptionDescription('rootconfig', '', [interface1, val4]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.option('val4').value.get() == ['val10', 'val11'] - assert await cfg.option('val1.val1').value.get() == [] - #with pytest.raises(LeadershipError): - # await cfg.val1.val1") - #with pytest.raises(LeadershipError): - # await cfg.val1.val2") - #with pytest.raises(LeadershipError): - # await cfg.val1.val3") - #with pytest.raises(LeadershipError): - # await cfg.val1.val5") - #with pytest.raises(LeadershipError): - # await cfg.val1.val6") - # - #default calculation has greater length - #with pytest.raises(LeadershipError): - # await cfg.option('val1.val1').value.set(['val1']") - # - await cfg.option('val1.val1').value.set(['val1', 'val2']) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] - assert await cfg.option('val1.val2', 0).value.get() == 'val1' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val3', 0).value.get() == 'yes' - assert await cfg.option('val1.val3', 1).value.get() == 'yes' - with pytest.raises(LeadershipError): - await cfg.option('val1.val5', 0).value.get() - with pytest.raises(LeadershipError): - await cfg.option('val1.val5', 1).value.get() - with pytest.raises(LeadershipError): - await cfg.option('val1.val6', 0).value.get() - with pytest.raises(LeadershipError): - await cfg.option('val1.val6', 1).value.get() - # - await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2', 'val3'] - assert await cfg.option('val1.val2', 0).value.get() == 'val1' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val2', 2).value.get() == 'val3' - assert await cfg.option('val1.val3', 0).value.get() == 'yes' - assert await cfg.option('val1.val3', 1).value.get() == 'yes' - assert await cfg.option('val1.val3', 2).value.get() == 'yes' - with pytest.raises(LeadershipError): - await cfg.option('val1.val5', 2).value.get() - with pytest.raises(LeadershipError): - await cfg.option('val1.val6', 2).value.get() - # - await cfg.option('val1.val1').value.pop(2) - assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] - assert await cfg.option('val1.val2', 0).value.get() == 'val1' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val3', 0).value.get() == 'yes' - assert await cfg.option('val1.val3', 1).value.get() == 'yes' - # - await cfg.option('val1.val2', 0).value.set('val2') - await cfg.option('val1.val2', 1).value.set('val2') - await cfg.option('val1.val3', 0).value.set('val2') - await cfg.option('val1.val3', 1).value.set('val2') - await cfg.option('val1.val5', 0).value.set('val2') - await cfg.option('val1.val5', 1).value.set('val2') - assert await cfg.option('val1.val2', 0).value.get() == 'val2' - assert await cfg.option('val1.val2', 1).value.get() == 'val2' - assert await cfg.option('val1.val3', 0).value.get() == 'val2' - assert await cfg.option('val1.val3', 1).value.get() == 'val2' - assert await cfg.option('val1.val5', 0).value.get() == 'val2' - assert await cfg.option('val1.val5', 1).value.get() == 'val2' - assert await cfg.option('val1.val6', 0).value.get() == 'val2' - assert await cfg.option('val1.val6', 1).value.get() == 'val2' - # - await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) - assert await cfg.option('val1.val2', 2).value.get() == 'val3' - assert await cfg.option('val1.val3', 2).value.get() == 'yes' + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.option('val4').value.get() == ['val10', 'val11'] + assert await cfg.option('val1.val1').value.get() == [] + #with pytest.raises(LeadershipError): + # await cfg.val1.val1") + #with pytest.raises(LeadershipError): + # await cfg.val1.val2") + #with pytest.raises(LeadershipError): + # await cfg.val1.val3") + #with pytest.raises(LeadershipError): + # await cfg.val1.val5") + #with pytest.raises(LeadershipError): + # await cfg.val1.val6") + # + #default calculation has greater length + #with pytest.raises(LeadershipError): + # await cfg.option('val1.val1').value.set(['val1']") + # + await cfg.option('val1.val1').value.set(['val1', 'val2']) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] + assert await cfg.option('val1.val2', 0).value.get() == 'val1' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val3', 0).value.get() == 'yes' + assert await cfg.option('val1.val3', 1).value.get() == 'yes' + with pytest.raises(LeadershipError): + await cfg.option('val1.val5', 0).value.get() + with pytest.raises(LeadershipError): + await cfg.option('val1.val5', 1).value.get() + with pytest.raises(LeadershipError): + await cfg.option('val1.val6', 0).value.get() + with pytest.raises(LeadershipError): + await cfg.option('val1.val6', 1).value.get() + # + await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2', 'val3'] + assert await cfg.option('val1.val2', 0).value.get() == 'val1' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val2', 2).value.get() == 'val3' + assert await cfg.option('val1.val3', 0).value.get() == 'yes' + assert await cfg.option('val1.val3', 1).value.get() == 'yes' + assert await cfg.option('val1.val3', 2).value.get() == 'yes' + with pytest.raises(LeadershipError): + await cfg.option('val1.val5', 2).value.get() + with pytest.raises(LeadershipError): + await cfg.option('val1.val6', 2).value.get() + # + await cfg.option('val1.val1').value.pop(2) + assert await cfg.option('val1.val1').value.get() == ['val1', 'val2'] + assert await cfg.option('val1.val2', 0).value.get() == 'val1' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val3', 0).value.get() == 'yes' + assert await cfg.option('val1.val3', 1).value.get() == 'yes' + # + await cfg.option('val1.val2', 0).value.set('val2') + await cfg.option('val1.val2', 1).value.set('val2') + await cfg.option('val1.val3', 0).value.set('val2') + await cfg.option('val1.val3', 1).value.set('val2') + await cfg.option('val1.val5', 0).value.set('val2') + await cfg.option('val1.val5', 1).value.set('val2') + assert await cfg.option('val1.val2', 0).value.get() == 'val2' + assert await cfg.option('val1.val2', 1).value.get() == 'val2' + assert await cfg.option('val1.val3', 0).value.get() == 'val2' + assert await cfg.option('val1.val3', 1).value.get() == 'val2' + assert await cfg.option('val1.val5', 0).value.get() == 'val2' + assert await cfg.option('val1.val5', 1).value.get() == 'val2' + assert await cfg.option('val1.val6', 0).value.get() == 'val2' + assert await cfg.option('val1.val6', 1).value.get() == 'val2' + # + await cfg.option('val1.val1').value.set(['val1', 'val2', 'val3']) + assert await cfg.option('val1.val2', 2).value.get() == 'val3' + assert await cfg.option('val1.val3', 2).value.get() == 'yes' + assert not await list_sessions() @pytest.mark.asyncio @@ -1080,22 +1115,23 @@ async def test_callback_different_type(config_type): val2 = IntOption('val2', "", Calculation(return_calc, Params((ParamOption(val), ParamOption(val1)), {'k': ParamOption(val_)})), multi=True) interface1 = Leadership('val1', '', [val1, val2]) maconfig = OptionDescription('rootconfig', '', [interface1, val, val_]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val1.val1').value.get() == [] - await cfg.option('val1.val1').value.set([1]) - assert await cfg.option('val1.val1').value.get() == [1] - assert await cfg.option('val1.val2', 0).value.get() == 6 - await cfg.option('val1.val1').value.set([1, 3]) - assert await cfg.option('val1.val1').value.get() == [1, 3] - assert await cfg.option('val1.val2', 0).value.get() == 6 - assert await cfg.option('val1.val2', 1).value.get() == 8 - await cfg.option('val1.val1').value.set([1, 3, 5]) - assert await cfg.option('val1.val1').value.get() == [1, 3, 5] - assert await cfg.option('val1.val2', 0).value.get() == 6 - assert await cfg.option('val1.val2', 1).value.get() == 8 - assert await cfg.option('val1.val2', 2).value.get() == 10 + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val1.val1').value.get() == [] + await cfg.option('val1.val1').value.set([1]) + assert await cfg.option('val1.val1').value.get() == [1] + assert await cfg.option('val1.val2', 0).value.get() == 6 + await cfg.option('val1.val1').value.set([1, 3]) + assert await cfg.option('val1.val1').value.get() == [1, 3] + assert await cfg.option('val1.val2', 0).value.get() == 6 + assert await cfg.option('val1.val2', 1).value.get() == 8 + await cfg.option('val1.val1').value.set([1, 3, 5]) + assert await cfg.option('val1.val1').value.get() == [1, 3, 5] + assert await cfg.option('val1.val2', 0).value.get() == 6 + assert await cfg.option('val1.val2', 1).value.get() == 8 + assert await cfg.option('val1.val2', 2).value.get() == 10 + assert not await list_sessions() @pytest.mark.asyncio @@ -1105,12 +1141,13 @@ async def test_callback_hidden(): od1 = OptionDescription('od1', '', [opt1], properties=('hidden',)) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.opt1').value.get() - # do not raise, forcepermissive - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.opt1').value.get() + # do not raise, forcepermissive + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1120,12 +1157,13 @@ async def test_callback_hidden_permissive(): od1 = OptionDescription('od1', '', [opt1], properties=('hidden',)) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.permissive.add('hidden') - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.opt1').value.get() - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.permissive.add('hidden') + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.opt1').value.get() + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1135,11 +1173,12 @@ async def test_callback_hidden_permissive_callback(): od1 = OptionDescription('od1', '', [opt1], properties=('hidden',)) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.opt1').value.get() - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.opt1').value.get() + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1149,10 +1188,11 @@ async def test_callback_two_disabled(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1162,12 +1202,13 @@ async def test_callback_two_disabled2(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - with pytest.raises(PropertiesOptionError): - await cfg.option('od2.opt2').value.get() - assert await cfg.forcepermissive.option('od2.opt2').owner.isdefault() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + with pytest.raises(PropertiesOptionError): + await cfg.option('od2.opt2').value.get() + assert await cfg.forcepermissive.option('od2.opt2').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -1177,13 +1218,14 @@ async def test_callback_calculating_invalid(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(ValueError): - await cfg.option('od2.opt2').value.get() - await cfg.unrestraint.option('od2.opt2').property.add('disabled') - with pytest.raises(PropertiesOptionError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(ValueError): + await cfg.option('od2.opt2').value.get() + await cfg.unrestraint.option('od2.opt2').property.add('disabled') + with pytest.raises(PropertiesOptionError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1193,10 +1235,11 @@ async def test_callback_calculating_disabled(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1206,10 +1249,11 @@ async def test_callback_calculating_mandatory(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_only() - with pytest.raises(ConfigError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_only() + with pytest.raises(ConfigError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1219,10 +1263,11 @@ async def test_callback_calculating_mandatory_multi(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_only() - with pytest.raises(ConfigError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_only() + with pytest.raises(ConfigError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1232,10 +1277,11 @@ async def test_callback_two_disabled_multi(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(PropertiesOptionError): - await cfg.option('od2.opt2').value.get() + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(PropertiesOptionError): + await cfg.option('od2.opt2').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1244,10 +1290,11 @@ async def test_callback_multi_list_params(config_type): val2 = StrOption('val2', "", Calculation(return_list, Params(ParamOption(val1))), multi=True, properties=('notunique',)) oval2 = OptionDescription('val2', '', [val2]) maconfig = OptionDescription('rootconfig', '', [val1, oval2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val2.val2').value.get() == ['val', 'val'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val2.val2').value.get() == ['val', 'val'] + assert not await list_sessions() @pytest.mark.asyncio @@ -1256,10 +1303,11 @@ async def test_callback_multi_list_params_key(config_type): val2 = StrOption('val2', "", Calculation(return_list, Params(kwargs={'value': ParamOption(val1)})), multi=True, properties=('notunique',)) oval2 = OptionDescription('val2', '', [val2]) maconfig = OptionDescription('rootconfig', '', [val1, oval2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('val2.val2').value.get() == ['val', 'val'] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('val2.val2').value.get() == ['val', 'val'] + assert not await list_sessions() @pytest.mark.asyncio @@ -1270,16 +1318,17 @@ async def test_leadership_callback_description(config_type): st = OptionDescription('st', '', [stm]) od = OptionDescription('od', '', [st]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - owner = await cfg.owner.get() - assert await cfg.option('od.st.st1.st1').value.get() == [] - assert await cfg.option('od.st.st1.st1').owner.isdefault() - ## - await cfg.option('od.st.st1.st1').value.set(['yes']) - await cfg.option('od.st.st1.st2', 0).value.set('yes') - assert await cfg.option('od.st.st1.st1').owner.get() == owner - assert await cfg.option('od.st.st1.st2', 0).owner.get() == owner + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + owner = await cfg.owner.get() + assert await cfg.option('od.st.st1.st1').value.get() == [] + assert await cfg.option('od.st.st1.st1').owner.isdefault() + ## + await cfg.option('od.st.st1.st1').value.set(['yes']) + await cfg.option('od.st.st1.st2', 0).value.set('yes') + assert await cfg.option('od.st.st1.st1').owner.get() == owner + assert await cfg.option('od.st.st1.st2', 0).owner.get() == owner + assert not await list_sessions() @pytest.mark.asyncio @@ -1289,16 +1338,17 @@ async def test_callback_raise(): od1 = OptionDescription('od1', '', [opt1]) od2 = OptionDescription('od2', '', [opt2]) maconfig = OptionDescription('rootconfig', '', [od1, od2]) - cfg = await Config(maconfig) - await cfg.property.read_write() - try: - await cfg.option('od1.opt1').value.get() - except ConfigError as err: - assert '"Option 1"' in str(err) - try: - await cfg.option('od2.opt2').value.get() - except ConfigError as err: - assert '"Option 2"' in str(err) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + try: + await cfg.option('od1.opt1').value.get() + except ConfigError as err: + assert '"Option 1"' in str(err) + try: + await cfg.option('od2.opt2').value.get() + except ConfigError as err: + assert '"Option 2"' in str(err) + assert not await list_sessions() @pytest.mark.asyncio @@ -1306,9 +1356,10 @@ async def test_calc_value_simple(config_type): val1 = StrOption('val1', '', 'val1') val2 = StrOption('val2', '', Calculation(calc_value, Params(ParamOption(val1)))) od = OptionDescription('root', '', [val1, val2]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1'} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1'} + assert not await list_sessions() @pytest.mark.asyncio @@ -1317,9 +1368,10 @@ async def test_calc_value_multi(config_type): val2 = StrOption('val2', "", 'val2') val3 = StrOption('val3', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True))), multi=True) od = OptionDescription('root', '', [val1, val2, val3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': ['val1', 'val2']} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': ['val1', 'val2']} + assert not await list_sessions() @pytest.mark.asyncio @@ -1327,11 +1379,12 @@ async def test_calc_value_disabled(): val1 = StrOption('val1', '', 'val1') val2 = StrOption('val2', '', Calculation(calc_value, Params(ParamOption(val1, True), default=ParamValue('default_value')))) od = OptionDescription('root', '', [val1, val2]) - cfg = await Config(od) - await cfg.property.read_write() - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1'} - await cfg.option('val1').property.add('disabled') - assert await cfg.value.dict() == {'val2': 'default_value'} + async with await Config(od) as cfg: + await cfg.property.read_write() + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1'} + await cfg.option('val1').property.add('disabled') + assert await cfg.value.dict() == {'val2': 'default_value'} + assert not await list_sessions() @pytest.mark.asyncio @@ -1343,12 +1396,13 @@ async def test_calc_value_condition(config_type): condition=ParamOption(boolean), expected=ParamValue(True)))) od = OptionDescription('root', '', [boolean, val1, val2]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'boolean': True, 'val1': 'val1', 'val2': 'val1'} - await cfg.option('boolean').value.set(False) - assert await cfg.value.dict() == {'boolean': False, 'val1': 'val1', 'val2': 'default_value'} + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'boolean': True, 'val1': 'val1', 'val2': 'val1'} + await cfg.option('boolean').value.set(False) + assert await cfg.value.dict() == {'boolean': False, 'val1': 'val1', 'val2': 'default_value'} + assert not await list_sessions() @pytest.mark.asyncio @@ -1357,9 +1411,10 @@ async def test_calc_value_allow_none(config_type): val2 = StrOption('val2', "") val3 = StrOption('val3', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), allow_none=ParamValue(True))), multi=True) od = OptionDescription('root', '', [val1, val2, val3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 'val1', 'val2': None, 'val3': ['val1', None]} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 'val1', 'val2': None, 'val3': ['val1', None]} + assert not await list_sessions() @pytest.mark.asyncio @@ -1368,9 +1423,10 @@ async def test_calc_value_remove_duplicate(config_type): val2 = StrOption('val2', "", 'val1') val3 = StrOption('val3', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), remove_duplicate_value=ParamValue(True))), multi=True) od = OptionDescription('root', '', [val1, val2, val3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1', 'val3': ['val1']} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val1', 'val3': ['val1']} + assert not await list_sessions() @pytest.mark.asyncio @@ -1379,9 +1435,10 @@ async def test_calc_value_join(config_type): val2 = StrOption('val2', "", 'val2') val3 = StrOption('val3', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2)), join=ParamValue('.')))) od = OptionDescription('root', '', [val1, val2, val3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': 'val1.val2'} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': 'val1.val2'} + assert not await list_sessions() @pytest.mark.asyncio @@ -1391,11 +1448,13 @@ async def test_calc_value_min(): val3 = StrOption('val3', "", 'val3') val4 = StrOption('val4', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2), ParamOption(val3, True)), join=ParamValue('.'), min_args_len=ParamValue(3)))) od = OptionDescription('root', '', [val1, val2, val3, val4]) - cfg = await Config(od) - await cfg.property.read_write() - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': 'val3', 'val4': 'val1.val2.val3'} - await cfg.option('val3').property.add('disabled') - assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val4': ''} + async with await Config(od) as cfg: + await cfg.property.read_write() + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val3': 'val3', 'val4': 'val1.val2.val3'} + await cfg.option('val3').property.add('disabled') + assert await cfg.value.dict() == {'val1': 'val1', 'val2': 'val2', 'val4': ''} + assert not await list_sessions() + @pytest.mark.asyncio async def test_calc_value_add(config_type): @@ -1403,6 +1462,7 @@ async def test_calc_value_add(config_type): val2 = IntOption('val2', "", 2) val3 = IntOption('val3', "", Calculation(calc_value, Params((ParamOption(val1), ParamOption(val2)), operator=ParamValue('add')))) od = OptionDescription('root', '', [val1, val2, val3]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'val1': 1, 'val2': 2, 'val3': 3} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'val1': 1, 'val2': 2, 'val3': 3} + assert not await list_sessions() diff --git a/tests/test_option_default.py b/tests/test_option_default.py index c32ff33..3fca1c0 100644 --- a/tests/test_option_default.py +++ b/tests/test_option_default.py @@ -1,23 +1,19 @@ "test all types of option default values for options, add new option in a descr" from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest from tiramisu.setting import owners from tiramisu.error import PropertiesOptionError, ConfigError, LeadershipError from tiramisu import IntOption, FloatOption, StrOption, ChoiceOption, \ - BoolOption, OptionDescription, Leadership, Config, undefined + BoolOption, OptionDescription, Leadership, Config, undefined, delete_session from tiramisu.storage import list_sessions +from .config import config_type, get_config, event_loop owners.addowner("frozenmultifollower") -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def make_description(): gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref') gcdummy = BoolOption('dummy', 'dummy', default=False) @@ -54,11 +50,12 @@ async def test_default_is_none(config_type): dummy1 = BoolOption('dummy1', 'doc dummy') dummy2 = BoolOption('dummy2', 'doc dummy') group = OptionDescription('group', '', [dummy1, dummy2]) - cfg = await Config(group) - cfg = await get_config(cfg, config_type) - # so when the default value is not set, there is actually a default value - assert await cfg.option('dummy1').value.get() is None - assert await cfg.option('dummy2').value.get() is None + async with await Config(group) as cfg: + cfg = await get_config(cfg, config_type) + # so when the default value is not set, there is actually a default value + assert await cfg.option('dummy1').value.get() is None + assert await cfg.option('dummy2').value.get() is None + assert not await list_sessions() @pytest.mark.asyncio @@ -66,6 +63,7 @@ async def test_set_defaut_value_from_option_object(): """Options have an available default setting and can give it back""" b = BoolOption("boolean", "", default=False) assert b.impl_getdefault() is False + assert not await list_sessions() @pytest.mark.asyncio @@ -74,42 +72,43 @@ async def test_force_default_on_freeze(): dummy1 = BoolOption('dummy1', 'doc dummy', default=False, properties=('force_default_on_freeze',)) dummy2 = BoolOption('dummy2', 'doc dummy', default=True) group = OptionDescription('group', '', [dummy1, dummy2]) - cfg_ori = await Config(group) - await cfg_ori.property.read_write() - cfg = cfg_ori - # FIXME cfg = await get_config(cfg_ori, config_type) - owner = await cfg.owner.get() - await cfg.option('dummy1').value.set(True) - await cfg.option('dummy2').value.set(False) - assert await cfg.option('dummy1').owner.get() == owner - assert await cfg.option('dummy2').owner.get() == owner - # if config_type == 'tiramisu-api': - # await cfg.send() - await cfg_ori.option('dummy1').property.add('frozen') - await cfg_ori.option('dummy2').property.add('frozen') - # cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy1').value.get() is False - assert await cfg.option('dummy2').value.get() is False - assert await cfg.option('dummy1').owner.isdefault() - assert await cfg.option('dummy2').owner.get() == owner - # if config_type == 'tiramisu-api': - # await cfg.send() - with pytest.raises(PropertiesOptionError): - await cfg_ori.option('dummy2').owner.set('frozen') - # cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): + async with await Config(group) as cfg_ori: + await cfg_ori.property.read_write() + cfg = cfg_ori + # FIXME cfg = await get_config(cfg_ori, config_type) + owner = await cfg.owner.get() + await cfg.option('dummy1').value.set(True) + await cfg.option('dummy2').value.set(False) + assert await cfg.option('dummy1').owner.get() == owner + assert await cfg.option('dummy2').owner.get() == owner + # if config_type == 'tiramisu-api': + # await cfg.send() + await cfg_ori.option('dummy1').property.add('frozen') + await cfg_ori.option('dummy2').property.add('frozen') + # cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy1').value.get() is False + assert await cfg.option('dummy2').value.get() is False + assert await cfg.option('dummy1').owner.isdefault() + assert await cfg.option('dummy2').owner.get() == owner + # if config_type == 'tiramisu-api': + # await cfg.send() + with pytest.raises(PropertiesOptionError): + await cfg_ori.option('dummy2').owner.set('frozen') + # cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('dummy1').value.reset() + # if config_type == 'tiramisu-api': + # await cfg.send() + await cfg_ori.option('dummy1').property.pop('frozen') + # cfg = await get_config(cfg_ori, config_type) await cfg.option('dummy1').value.reset() - # if config_type == 'tiramisu-api': - # await cfg.send() - await cfg_ori.option('dummy1').property.pop('frozen') - # cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy1').value.reset() - # if config_type == 'tiramisu-api': - # await cfg.send() - await cfg.option('dummy1').property.add('frozen') - # cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('dummy2').owner.set('frozen') + # if config_type == 'tiramisu-api': + # await cfg.send() + await cfg.option('dummy1').property.add('frozen') + # cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('dummy2').owner.set('frozen') + assert not await list_sessions() @pytest.mark.asyncio @@ -117,36 +116,37 @@ async def test_force_default_on_freeze_multi(): dummy1 = BoolOption('dummy1', 'doc dummy', default=[False], properties=('force_default_on_freeze',), multi=True) dummy2 = BoolOption('dummy2', 'doc dummy', default=[True], multi=True) group = OptionDescription('group', '', [dummy1, dummy2]) - cfg_ori = await Config(group) - await cfg_ori.property.read_write() - cfg = cfg_ori - # FIXME cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy1').value.set([undefined, True]) - await cfg.option('dummy2').value.set([undefined, False]) - owner = await cfg.owner.get() - assert await cfg.option('dummy1').owner.get() == owner - assert await cfg.option('dummy2').owner.get() == owner - # if config_type == 'tiramisu-api': - # await cfg.send() - await cfg_ori.option('dummy1').property.add('frozen') - await cfg_ori.option('dummy2').property.add('frozen') - # cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy1').value.get() == [False] - assert await cfg.option('dummy2').value.get() == [True, False] - assert await cfg.option('dummy1').owner.isdefault() - assert await cfg.option('dummy2').owner.get() == owner - # if config_type == 'tiramisu-api': - # await cfg.send() - with pytest.raises(PropertiesOptionError): - await cfg_ori.option('dummy2').owner.set('owner') - # cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('dummy2').value.reset() - # if config_type == 'tiramisu-api': - # await cfg.send() - await cfg_ori.option('dummy1').property.pop('frozen') - # cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy1').value.reset() + async with await Config(group) as cfg_ori: + await cfg_ori.property.read_write() + cfg = cfg_ori + # FIXME cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy1').value.set([undefined, True]) + await cfg.option('dummy2').value.set([undefined, False]) + owner = await cfg.owner.get() + assert await cfg.option('dummy1').owner.get() == owner + assert await cfg.option('dummy2').owner.get() == owner + # if config_type == 'tiramisu-api': + # await cfg.send() + await cfg_ori.option('dummy1').property.add('frozen') + await cfg_ori.option('dummy2').property.add('frozen') + # cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy1').value.get() == [False] + assert await cfg.option('dummy2').value.get() == [True, False] + assert await cfg.option('dummy1').owner.isdefault() + assert await cfg.option('dummy2').owner.get() == owner + # if config_type == 'tiramisu-api': + # await cfg.send() + with pytest.raises(PropertiesOptionError): + await cfg_ori.option('dummy2').owner.set('owner') + # cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('dummy2').value.reset() + # if config_type == 'tiramisu-api': + # await cfg.send() + await cfg_ori.option('dummy1').property.pop('frozen') + # cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy1').value.reset() + assert not await list_sessions() @pytest.mark.asyncio @@ -155,8 +155,10 @@ async def test_force_default_on_freeze_leader(): dummy2 = BoolOption('dummy2', 'Test string option', multi=True) descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = OptionDescription("root", "", [descr]) - with pytest.raises(ConfigError): - await Config(descr) + with pytest.raises(ConfigError): + await Config(descr, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio @@ -165,8 +167,10 @@ async def test_force_metaconfig_on_freeze_leader(): dummy2 = BoolOption('dummy2', 'Test string option', multi=True) descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = OptionDescription("root", "", [descr]) - with pytest.raises(ConfigError): - await Config(descr) + with pytest.raises(ConfigError): + await Config(descr, session_id='error') + await delete_session('error') + assert not await list_sessions() @pytest.mark.asyncio @@ -175,9 +179,10 @@ async def test_force_default_on_freeze_leader_frozen(): dummy2 = BoolOption('dummy2', 'Test string option', multi=True) descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = OptionDescription("root", "", [descr]) - cfg = await Config(descr) - with pytest.raises(LeadershipError): - await cfg.option('dummy1.dummy1').property.pop('frozen') + async with await Config(descr) as cfg: + with pytest.raises(LeadershipError): + await cfg.option('dummy1.dummy1').property.pop('frozen') + assert not await list_sessions() @pytest.mark.asyncio @@ -186,9 +191,10 @@ async def test_force_metaconfig_on_freeze_leader_frozen(): dummy2 = BoolOption('dummy2', 'Test string option', multi=True) descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = OptionDescription("root", "", [descr]) - cfg = await Config(descr) - with pytest.raises(LeadershipError): - await cfg.option('dummy1.dummy1').property.pop('frozen') + async with await Config(descr) as cfg: + with pytest.raises(LeadershipError): + await cfg.option('dummy1.dummy1').property.pop('frozen') + assert not await list_sessions() @pytest.mark.asyncio @@ -197,62 +203,63 @@ async def test_force_default_on_freeze_follower(config_type): dummy2 = BoolOption('dummy2', 'Test string option', multi=True, properties=('force_default_on_freeze',)) descr = Leadership("dummy1", "", [dummy1, dummy2]) descr = OptionDescription("root", "", [descr]) - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy1.dummy1').value.set([True]) - await cfg.option('dummy1.dummy2', 0).value.set(False) - assert await cfg.option('dummy1.dummy1').value.get() == [True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == False - assert await cfg.option('dummy1.dummy1').owner.get() == 'user' - assert await cfg.option('dummy1.dummy2', 0).owner.get() == 'user' - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('dummy1.dummy2').property.add('frozen') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy1.dummy1').value.get() == [True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == None - assert await cfg.option('dummy1.dummy1').owner.get() == 'user' - assert await cfg.option('dummy1.dummy2', 0).owner.isdefault() - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(PropertiesOptionError): - await cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower') - cfg = await get_config(cfg_ori, config_type) - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('dummy1.dummy2').property.pop('frozen') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy1.dummy1').value.set([True, True]) - await cfg.option('dummy1.dummy2', 1).value.set(False) - assert await cfg.option('dummy1.dummy1').value.get() == [True, True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == False - assert await cfg.option('dummy1.dummy2', 1).value.get() == False - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('dummy1.dummy2').property.add('frozen') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy1.dummy1').value.get() == [True, True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == None - assert await cfg.option('dummy1.dummy2', 1).value.get() == None - # - await cfg.option('dummy1.dummy1').value.pop(1) - assert await cfg.option('dummy1.dummy1').value.get() == [True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == None - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('dummy1.dummy2').property.pop('frozen') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy1.dummy1').value.get() == [True] - assert await cfg.option('dummy1.dummy2', 0).value.get() == False - # - await cfg.option('dummy1.dummy1').value.set([True, True]) - assert await cfg.option('dummy1.dummy2', 0).value.get() == False - assert await cfg.option('dummy1.dummy2', 1).value.get() == None + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy1.dummy1').value.set([True]) + await cfg.option('dummy1.dummy2', 0).value.set(False) + assert await cfg.option('dummy1.dummy1').value.get() == [True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == False + assert await cfg.option('dummy1.dummy1').owner.get() == 'user' + assert await cfg.option('dummy1.dummy2', 0).owner.get() == 'user' + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('dummy1.dummy2').property.add('frozen') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy1.dummy1').value.get() == [True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == None + assert await cfg.option('dummy1.dummy1').owner.get() == 'user' + assert await cfg.option('dummy1.dummy2', 0).owner.isdefault() + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(PropertiesOptionError): + await cfg_ori.option('dummy1.dummy2', 0).owner.set('frozenmultifollower') + cfg = await get_config(cfg_ori, config_type) + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('dummy1.dummy2').property.pop('frozen') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy1.dummy1').value.set([True, True]) + await cfg.option('dummy1.dummy2', 1).value.set(False) + assert await cfg.option('dummy1.dummy1').value.get() == [True, True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == False + assert await cfg.option('dummy1.dummy2', 1).value.get() == False + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('dummy1.dummy2').property.add('frozen') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy1.dummy1').value.get() == [True, True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == None + assert await cfg.option('dummy1.dummy2', 1).value.get() == None + # + await cfg.option('dummy1.dummy1').value.pop(1) + assert await cfg.option('dummy1.dummy1').value.get() == [True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == None + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('dummy1.dummy2').property.pop('frozen') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy1.dummy1').value.get() == [True] + assert await cfg.option('dummy1.dummy2', 0).value.get() == False + # + await cfg.option('dummy1.dummy1').value.set([True, True]) + assert await cfg.option('dummy1.dummy2', 0).value.get() == False + assert await cfg.option('dummy1.dummy2', 1).value.get() == None + assert not await list_sessions() @pytest.mark.asyncio @@ -260,25 +267,28 @@ async def test_overrides_changes_option_value(config_type): "with config.override(), the default is changed and the value is changed" descr = OptionDescription("test", "", [ BoolOption("b", "", default=False)]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - await cfg.option('b').value.set(True) + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('b').value.set(True) + assert not await list_sessions() @pytest.mark.asyncio async def test_choice_with_no_default(config_type): descr = OptionDescription("test", "", [ ChoiceOption("backend", "", ("c", "cli"))]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('backend').value.get() is None - await cfg.option('backend').value.set('c') + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('backend').value.get() is None + await cfg.option('backend').value.set('c') + assert not await list_sessions() @pytest.mark.asyncio async def test_choice_with_default(config_type): descr = OptionDescription("test", "", [ ChoiceOption("backend", "", ("c", "cli"), default="cli")]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('backend').value.get() == 'cli' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('backend').value.get() == 'cli' + assert not await list_sessions() diff --git a/tests/test_option_owner.py b/tests/test_option_owner.py index 10de4bf..803f55a 100644 --- a/tests/test_option_owner.py +++ b/tests/test_option_owner.py @@ -1,6 +1,5 @@ from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest @@ -9,16 +8,13 @@ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ StrOption, OptionDescription, SymLinkOption, Leadership, Config from tiramisu.error import ConfigError, ConstError, PropertiesOptionError, APIError from tiramisu.storage import list_sessions +from .config import config_type, get_config, event_loop owners.addowner("readonly2") owners.addowner("new2") -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - def make_description(): gcoption = ChoiceOption('name', 'GC name', ['ref', 'framework'], 'ref') gcdummy = BoolOption('dummy', 'dummy', default=False) @@ -45,61 +41,64 @@ def make_description(): async def test_default_owner(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' - await cfg.option('dummy').value.set(True) - owner = await cfg.owner.get() - assert await cfg.option('dummy').owner.get() == owner + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + await cfg.option('dummy').value.set(True) + owner = await cfg.owner.get() + assert await cfg.option('dummy').owner.get() == owner + assert not await list_sessions() @pytest.mark.asyncio async def test_hidden_owner(): gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',)) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr) - await cfg.property.read_write() - #with pytest.raises(PropertiesOptionError): - # await cfg.forcepermissive.option('dummy').owner.get() - #with pytest.raises(PropertiesOptionError): - # await cfg.option('dummy').owner.isdefault() - #with pytest.raises(PropertiesOptionError): - # await cfg.forcepermissive.option('dummy').owner.isdefault() - await cfg.permissive.add('hidden') - await cfg.forcepermissive.option('dummy').value.get() - await cfg.forcepermissive.option('dummy').owner.isdefault() + async with await Config(descr) as cfg: + await cfg.property.read_write() + #with pytest.raises(PropertiesOptionError): + # await cfg.forcepermissive.option('dummy').owner.get() + #with pytest.raises(PropertiesOptionError): + # await cfg.option('dummy').owner.isdefault() + #with pytest.raises(PropertiesOptionError): + # await cfg.forcepermissive.option('dummy').owner.isdefault() + await cfg.permissive.add('hidden') + await cfg.forcepermissive.option('dummy').value.get() + await cfg.forcepermissive.option('dummy').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio async def test_addowner(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg_ori = await Config(descr) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' - assert await cfg.option('dummy').owner.isdefault() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.owner.set('gen_config') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy').value.set(True) - assert await cfg.option('dummy').owner.get() == owners.gen_config - assert not await cfg.option('dummy').owner.isdefault() + async with await Config(descr) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + assert await cfg.option('dummy').owner.isdefault() + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.owner.set('gen_config') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy').value.set(True) + assert await cfg.option('dummy').owner.get() == owners.gen_config + assert not await cfg.option('dummy').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio async def test_addowner_multiple_time(): owners.addowner("testowner2") - with pytest.raises(ConstError): + with pytest.raises(ConstError): owners.addowner("testowner2") @pytest.mark.asyncio async def test_delete_owner(): owners.addowner('deleted2') - with pytest.raises(ConstError): + with pytest.raises(ConstError): del(owners.deleted2) @@ -107,88 +106,93 @@ async def test_delete_owner(): async def test_owner_is_not_a_string(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == owners.default - assert await cfg.option('dummy').owner.get() == 'default' - if config_type == 'tiramisu': - assert isinstance(await cfg.option('dummy').owner.get(), owners.Owner) - await cfg.option('dummy').value.set(True) - assert await cfg.option('dummy').owner.get() == 'user' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == owners.default + assert await cfg.option('dummy').owner.get() == 'default' + if config_type == 'tiramisu': + assert isinstance(await cfg.option('dummy').owner.get(), owners.Owner) + await cfg.option('dummy').value.set(True) + assert await cfg.option('dummy').owner.get() == 'user' + assert not await list_sessions() @pytest.mark.asyncio async def test_setowner_without_valid_owner(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + assert not await list_sessions() @pytest.mark.asyncio async def test_setowner_for_value(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg_ori = await Config(descr) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(ConfigError): + async with await Config(descr) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(ConfigError): + await cfg_ori.option('dummy').owner.set('new2') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy').value.set(False) + assert await cfg.option('dummy').owner.get() == owners.user + if config_type == 'tiramisu-api': + await cfg.send() await cfg_ori.option('dummy').owner.set('new2') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy').value.set(False) - assert await cfg.option('dummy').owner.get() == owners.user - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('dummy').owner.set('new2') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').owner.get() == owners.new2 + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').owner.get() == owners.new2 + assert not await list_sessions() @pytest.mark.asyncio async def test_setowner_forbidden(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg_ori = await Config(descr) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(ValueError): - await cfg_ori.owner.set('default') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('dummy').value.set(False) - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(ValueError): - await cfg_ori.option('dummy').owner.set('default') - cfg = await get_config(cfg_ori, config_type) + async with await Config(descr) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(ValueError): + await cfg_ori.owner.set('default') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('dummy').value.set(False) + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(ValueError): + await cfg_ori.option('dummy').owner.set('default') + cfg = await get_config(cfg_ori, config_type) + assert not await list_sessions() @pytest.mark.asyncio async def test_setowner_read_only(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr = OptionDescription('tiramisu', '', [gcdummy]) - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('dummy').owner.get() == 'default' - await cfg.option('dummy').value.set(False) - assert await cfg.option('dummy').owner.get() == owners.user - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_only() - with pytest.raises(PropertiesOptionError): - await cfg_ori.option('dummy').owner.set('readonly2') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('dummy').owner.get() == owners.user + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('dummy').owner.get() == 'default' + await cfg.option('dummy').value.set(False) + assert await cfg.option('dummy').owner.get() == owners.user + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_only() + with pytest.raises(PropertiesOptionError): + await cfg_ori.option('dummy').owner.set('readonly2') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('dummy').owner.get() == owners.user + assert not await list_sessions() @pytest.mark.asyncio @@ -196,12 +200,13 @@ async def test_setowner_optiondescription(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) descr1 = OptionDescription('tiramisu', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [descr1]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - with pytest.raises(APIError): - await cfg.option('tiramisu').owner.get() - with pytest.raises(APIError): - await cfg.option('tiramisu').owner.set('user') + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + with pytest.raises(APIError): + await cfg.option('tiramisu').owner.get() + with pytest.raises(APIError): + await cfg.option('tiramisu').owner.set('user') + assert not await list_sessions() @pytest.mark.asyncio @@ -210,15 +215,16 @@ async def test_setowner_symlinkoption(config_type): s = SymLinkOption('symdummy', gcdummy) descr1 = OptionDescription('tiramisu', '', [gcdummy, s]) descr = OptionDescription('tiramisu', '', [descr1]) - cfg_ori = await Config(descr) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('tiramisu.symdummy').owner.isdefault() - await cfg.option('tiramisu.dummy').value.set(True) - assert not await cfg.option('tiramisu.symdummy').owner.isdefault() - if config_type == 'tiramisu-api': - await cfg.send() - with pytest.raises(ConfigError): - await cfg_ori.option('tiramisu.symdummy').owner.set('user') + async with await Config(descr) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('tiramisu.symdummy').owner.isdefault() + await cfg.option('tiramisu.dummy').value.set(True) + assert not await cfg.option('tiramisu.symdummy').owner.isdefault() + if config_type == 'tiramisu-api': + await cfg.send() + with pytest.raises(ConfigError): + await cfg_ori.option('tiramisu.symdummy').owner.set('user') + assert not await list_sessions() @pytest.mark.asyncio @@ -227,20 +233,21 @@ async def test_owner_leadership(config_type): c = StrOption('str', 'Test string option', multi=True) descr = Leadership("int", "", [b, c]) od = OptionDescription('od', '', [descr]) - cfg_ori = await Config(od) - with pytest.raises(ConfigError): - await cfg_ori.option('int.str', 0).owner.set('user') - cfg = await get_config(cfg_ori, config_type) + async with await Config(od) as cfg_ori: + with pytest.raises(ConfigError): + await cfg_ori.option('int.str', 0).owner.set('user') + cfg = await get_config(cfg_ori, config_type) - await cfg.option('int.int').value.set([0, 1]) - await cfg.option('int.str', 0).value.set('yes') - assert not await cfg.option('int.str', 0).owner.isdefault() - assert await cfg.option('int.str', 1).owner.isdefault() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('int.str', 0).owner.set('user') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('int.str', 0).owner.get() == owners.user - assert await cfg.option('int.str', 1).owner.isdefault() - assert await cfg.option('int.str', 0).value.get() == 'yes' - assert await cfg.option('int.str', 1).value.get() == None + await cfg.option('int.int').value.set([0, 1]) + await cfg.option('int.str', 0).value.set('yes') + assert not await cfg.option('int.str', 0).owner.isdefault() + assert await cfg.option('int.str', 1).owner.isdefault() + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('int.str', 0).owner.set('user') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('int.str', 0).owner.get() == owners.user + assert await cfg.option('int.str', 1).owner.isdefault() + assert await cfg.option('int.str', 0).value.get() == 'yes' + assert await cfg.option('int.str', 1).value.get() == None + assert not await list_sessions() diff --git a/tests/test_option_setting.py b/tests/test_option_setting.py index 9c74336..797e773 100644 --- a/tests/test_option_setting.py +++ b/tests/test_option_setting.py @@ -1,7 +1,6 @@ "config.set() or config.setoption() or option.setoption()" from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest from os import environ @@ -16,10 +15,7 @@ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ from tiramisu.error import PropertiesOptionError from tiramisu.storage import list_sessions import warnings - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop def make_description(): @@ -50,11 +46,12 @@ async def test_attribute_access(config_type): "Once set, option values can't be changed again by attribute access" s = StrOption("string", "", default="string") descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - # let's try to change it again - await cfg.option('string').value.set('foo') - assert await cfg.option('string').value.get() == 'foo' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + # let's try to change it again + await cfg.option('string').value.set('foo') + assert await cfg.option('string').value.get() == 'foo' + assert not await list_sessions() @pytest.mark.asyncio @@ -62,87 +59,89 @@ async def test_mod_read_only_write(): "default with multi is a list" s = StrOption("string", "", default=[], default_multi="string", multi=True) descr = OptionDescription("options", "", [s]) - config = await Config(descr) - config2 = await Config(descr) - assert await config.property.getdefault() == {'cache', 'validator', 'warnings'} - assert await config.property.getdefault('read_only', 'append') == {'frozen', - 'disabled', - 'validator', - 'everything_frozen', - 'mandatory', - 'empty', - 'force_store_value'} - assert await config.property.getdefault('read_only', 'remove') == {'permissive', - 'hidden'} - assert await config.property.getdefault('read_write', 'append') == {'frozen', - 'disabled', - 'validator', - 'hidden', - 'force_store_value'} - assert await config.property.getdefault('read_write', 'remove') == {'permissive', - 'everything_frozen', - 'mandatory', - 'empty'} - # - await config.property.setdefault(frozenset(['cache'])) - await config.property.setdefault(type='read_only', when='append', properties=frozenset(['disabled'])) - await config.property.setdefault(type='read_only', when='remove', properties=frozenset(['hidden'])) - await config.property.setdefault(type='read_write', when='append', properties=frozenset(['disabled', 'hidden'])) - await config.property.setdefault(type='read_write', when='remove', properties=frozenset([])) - with pytest.raises(ValueError): - await config.property.setdefault(type='unknown', when='append', properties=frozenset(['disabled'])) - with pytest.raises(ValueError): - await config.property.setdefault(type='read_only', when='unknown', properties=frozenset(['disabled'])) - with pytest.raises(TypeError): - await config.property.setdefault(type='read_only', when='append', properties=['disabled']) + async with await Config(descr) as config: + async with await Config(descr) as config2: + assert await config.property.getdefault() == {'cache', 'validator', 'warnings'} + assert await config.property.getdefault('read_only', 'append') == {'frozen', + 'disabled', + 'validator', + 'everything_frozen', + 'mandatory', + 'empty', + 'force_store_value'} + assert await config.property.getdefault('read_only', 'remove') == {'permissive', + 'hidden'} + assert await config.property.getdefault('read_write', 'append') == {'frozen', + 'disabled', + 'validator', + 'hidden', + 'force_store_value'} + assert await config.property.getdefault('read_write', 'remove') == {'permissive', + 'everything_frozen', + 'mandatory', + 'empty'} + # + await config.property.setdefault(frozenset(['cache'])) + await config.property.setdefault(type='read_only', when='append', properties=frozenset(['disabled'])) + await config.property.setdefault(type='read_only', when='remove', properties=frozenset(['hidden'])) + await config.property.setdefault(type='read_write', when='append', properties=frozenset(['disabled', 'hidden'])) + await config.property.setdefault(type='read_write', when='remove', properties=frozenset([])) + with pytest.raises(ValueError): + await config.property.setdefault(type='unknown', when='append', properties=frozenset(['disabled'])) + with pytest.raises(ValueError): + await config.property.setdefault(type='read_only', when='unknown', properties=frozenset(['disabled'])) + with pytest.raises(TypeError): + await config.property.setdefault(type='read_only', when='append', properties=['disabled']) - assert await config.property.getdefault() == {'cache'} - assert await config.property.getdefault('read_only', 'append') == {'disabled'} - assert await config.property.getdefault('read_only', 'remove') == {'hidden'} - assert await config.property.getdefault('read_write', 'append') == {'disabled', - 'hidden'} - assert await config.property.getdefault('read_write', 'remove') == set([]) - # - await config.property.read_only() - assert await config.property.get() == {'cache', 'disabled'} - await config.property.read_write() - assert await config.property.get() == {'cache', 'disabled', 'hidden'} - await config.property.read_only() - assert await config.property.get() == {'cache', 'disabled'} - # - assert await config2.property.getdefault() == {'cache', 'validator', 'warnings'} - assert await config2.property.getdefault('read_only', 'append') == {'frozen', - 'disabled', - 'validator', - 'everything_frozen', - 'mandatory', - 'empty', - 'force_store_value'} - assert await config2.property.getdefault('read_only', 'remove') == {'permissive', - 'hidden'} - assert await config2.property.getdefault('read_write', 'append') == {'frozen', - 'disabled', - 'validator', - 'hidden', - 'force_store_value'} - assert await config2.property.getdefault('read_write', 'remove') == {'permissive', - 'everything_frozen', - 'mandatory', - 'empty'} - with pytest.raises(ValueError): - await config2.property.getdefault('unknown', 'remove') - with pytest.raises(ValueError): - await config2.property.getdefault('read_write', 'unknown') + assert await config.property.getdefault() == {'cache'} + assert await config.property.getdefault('read_only', 'append') == {'disabled'} + assert await config.property.getdefault('read_only', 'remove') == {'hidden'} + assert await config.property.getdefault('read_write', 'append') == {'disabled', + 'hidden'} + assert await config.property.getdefault('read_write', 'remove') == set([]) + # + await config.property.read_only() + assert await config.property.get() == {'cache', 'disabled'} + await config.property.read_write() + assert await config.property.get() == {'cache', 'disabled', 'hidden'} + await config.property.read_only() + assert await config.property.get() == {'cache', 'disabled'} + # + assert await config2.property.getdefault() == {'cache', 'validator', 'warnings'} + assert await config2.property.getdefault('read_only', 'append') == {'frozen', + 'disabled', + 'validator', + 'everything_frozen', + 'mandatory', + 'empty', + 'force_store_value'} + assert await config2.property.getdefault('read_only', 'remove') == {'permissive', + 'hidden'} + assert await config2.property.getdefault('read_write', 'append') == {'frozen', + 'disabled', + 'validator', + 'hidden', + 'force_store_value'} + assert await config2.property.getdefault('read_write', 'remove') == {'permissive', + 'everything_frozen', + 'mandatory', + 'empty'} + with pytest.raises(ValueError): + await config2.property.getdefault('unknown', 'remove') + with pytest.raises(ValueError): + await config2.property.getdefault('read_write', 'unknown') + assert not await list_sessions() @pytest.mark.asyncio async def test_setitem(config_type): s = StrOption("string", "", default=["string", "sdfsdf"], default_multi="prout", multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - await cfg.option('string').value.set([undefined, 'foo']) - assert await cfg.option('string').value.get() == ['string', 'foo'] + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('string').value.set([undefined, 'foo']) + assert await cfg.option('string').value.get() == ['string', 'foo'] + assert not await list_sessions() @pytest.mark.asyncio @@ -150,34 +149,36 @@ async def test_reset(config_type): "if value is None, resets to default owner" s = StrOption("string", "", default="string") descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - await cfg.option('string').value.set('foo') - assert await cfg.option('string').value.get() == "foo" - assert await cfg.option('string').owner.get() ==owners.user - await cfg.option('string').value.reset() - assert await cfg.option('string').value.get() == 'string' - assert await cfg.option('string').owner.get() ==owners.default + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('string').value.set('foo') + assert await cfg.option('string').value.get() == "foo" + assert await cfg.option('string').owner.get() ==owners.user + await cfg.option('string').value.reset() + assert await cfg.option('string').value.get() == 'string' + assert await cfg.option('string').owner.get() ==owners.default + assert not await list_sessions() @pytest.mark.asyncio async def test_reset_with_multi(config_type): s = StrOption("string", "", default=["string"], default_multi="string", multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) -# await cfg.option('string').value.set([]) - await cfg.option('string').value.reset() - assert await cfg.option('string').value.get() == ["string"] - assert await cfg.option('string').owner.get() =='default' - await cfg.option('string').value.set(["eggs", "spam", "foo"]) - assert await cfg.option('string').owner.get() =='user' - await cfg.option('string').value.set([]) - await cfg.option('string').value.reset() -# assert await cfg.option('string').value.get() == ["string"] - assert await cfg.option('string').owner.get() =='default' - with pytest.raises(ValueError): - await cfg.option('string').value.set(None) + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + # await cfg.option('string').value.set([]) + await cfg.option('string').value.reset() + assert await cfg.option('string').value.get() == ["string"] + assert await cfg.option('string').owner.get() =='default' + await cfg.option('string').value.set(["eggs", "spam", "foo"]) + assert await cfg.option('string').owner.get() =='user' + await cfg.option('string').value.set([]) + await cfg.option('string').value.reset() + # assert await cfg.option('string').value.get() == ["string"] + assert await cfg.option('string').owner.get() =='default' + with pytest.raises(ValueError): + await cfg.option('string').value.set(None) + assert not await list_sessions() @pytest.mark.asyncio @@ -187,12 +188,13 @@ async def test_property_get_unique_empty(): s3 = StrOption("string3", "", default=["string"], default_multi="string", multi=True, properties=('notempty',)) s4 = StrOption("string4", "", default=["string"], default_multi="string", multi=True, properties=('notunique', 'notempty')) descr = OptionDescription("options", "", [s, s2, s3, s4]) - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.option('string').property.get() == {'empty', 'unique'} - assert await cfg.option('string2').property.get() == {'empty'} - assert await cfg.option('string3').property.get() == {'unique'} - assert await cfg.option('string4').property.get() == set() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.option('string').property.get() == {'empty', 'unique'} + assert await cfg.option('string2').property.get() == {'empty'} + assert await cfg.option('string3').property.get() == {'unique'} + assert await cfg.option('string4').property.get() == set() + assert not await list_sessions() @pytest.mark.asyncio @@ -205,10 +207,11 @@ async def test_property_only_raises(): 'expected': ParamValue(1)})) stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc", properties=(hidden_property,), multi=True) descr = OptionDescription("options", "", [s, intoption, stroption]) - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.option('str').property.get() == {'empty', 'unique'} - assert await cfg.option('str').property.get(only_raises=True) == set() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.option('str').property.get() == {'empty', 'unique'} + assert await cfg.option('str').property.get(only_raises=True) == set() + assert not await list_sessions() @pytest.mark.asyncio @@ -216,21 +219,23 @@ async def test_default_with_multi(): "default with multi is a list" s = StrOption("string", "", default=[], default_multi="string", multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - assert await cfg.option('string').value.get() == [] - s = StrOption("string", "", default=None, default_multi="string", multi=True) - descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - assert await cfg.option('string').value.get() == [] + async with await Config(descr) as cfg: + assert await cfg.option('string').value.get() == [] + s = StrOption("string", "", default=None, default_multi="string", multi=True) + descr = OptionDescription("options", "", [s]) + async with await Config(descr) as cfg: + assert await cfg.option('string').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio async def test_idontexist(): descr = make_description() - cfg = await Config(descr) - await cfg.value.dict() - with pytest.raises(AttributeError): - await cfg.option('idontexist').value.get() + async with await Config(descr) as cfg: + await cfg.value.dict() + with pytest.raises(AttributeError): + await cfg.option('idontexist').value.get() + assert not await list_sessions() # ____________________________________________________________ @@ -238,34 +243,37 @@ async def test_idontexist(): async def test_attribute_access_with_multi(config_type): s = StrOption("string", "", default=["string"], default_multi="string", multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - await cfg.option('string').value.set(["foo", "bar"]) - assert await cfg.option('string').value.get() == ["foo", "bar"] + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('string').value.set(["foo", "bar"]) + assert await cfg.option('string').value.get() == ["foo", "bar"] + assert not await list_sessions() @pytest.mark.asyncio async def test_item_access_with_multi(config_type): s = StrOption("string", "", default=["string"], multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - await cfg.option('string').value.set(["foo", "bar"]) - assert await cfg.option('string').value.get() == ["foo", "bar"] - await cfg.option('string').value.set(["changetest", "bar"]) - assert await cfg.option('string').value.get() == ["changetest", "bar"] + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('string').value.set(["foo", "bar"]) + assert await cfg.option('string').value.get() == ["foo", "bar"] + await cfg.option('string').value.set(["changetest", "bar"]) + assert await cfg.option('string').value.get() == ["changetest", "bar"] + assert not await list_sessions() @pytest.mark.asyncio async def test_access_with_multi_default(config_type): s = StrOption("string", "", default=["string"], multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('string').owner.get() =='default' - await cfg.option('string').value.set(["foo", "bar"]) - assert await cfg.option('string').value.get() == ["foo", "bar"] - assert await cfg.option('string').owner.get() =='user' + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('string').owner.get() =='default' + await cfg.option('string').value.set(["foo", "bar"]) + assert await cfg.option('string').value.get() == ["foo", "bar"] + assert await cfg.option('string').owner.get() =='user' + assert not await list_sessions() @pytest.mark.asyncio @@ -278,13 +286,14 @@ async def test_multi_with_requires(): 'expected': ParamValue(1)})) stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc", properties=(hidden_property,), multi=True) descr = OptionDescription("options", "", [s, intoption, stroption]) - cfg = await Config(descr) - await cfg.property.read_write() - assert not 'hidden' in await cfg.option('str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('str').value.set(['a', 'b']) - assert 'hidden' in await cfg.forcepermissive.option('str').property.get() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert not 'hidden' in await cfg.option('str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('str').value.set(['a', 'b']) + assert 'hidden' in await cfg.forcepermissive.option('str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -298,12 +307,13 @@ async def test_requires_with_inverted(): 'reverse_condition': ParamValue(True)})) stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc", properties=(hide_property,), multi=True) descr = OptionDescription("options", "", [s, intoption, stroption]) - cfg = await Config(descr) - assert not 'hidden' in await cfg.option('str').property.get() - assert 'hide' in await cfg.option('str').property.get() - await cfg.option('int').value.set(1) - assert not 'hidden' in await cfg.option('str').property.get() - assert not 'hide' in await cfg.option('str').property.get() + async with await Config(descr) as cfg: + assert not 'hidden' in await cfg.option('str').property.get() + assert 'hide' in await cfg.option('str').property.get() + await cfg.option('int').value.set(1) + assert not 'hidden' in await cfg.option('str').property.get() + assert not 'hide' in await cfg.option('str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -317,13 +327,14 @@ async def test_multi_with_requires_in_another_group(): stroption = StrOption('str', 'Test string option', default=["abc"], properties=(hidden_property,), multi=True) descr = OptionDescription("opt", "", [stroption]) descr2 = OptionDescription("opt2", "", [intoption, s, descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert not 'hidden' in await cfg.option('opt.str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('opt.str').value.set(['a', 'b']) - assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert not 'hidden' in await cfg.option('opt.str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('opt.str').value.set(['a', 'b']) + assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -338,13 +349,14 @@ async def test_multi_with_requires_in_another_group_inverse(): stroption = StrOption('str', 'Test string option', default=["abc"], properties=(hidden_property,), multi=True) descr = OptionDescription("opt", "", [stroption]) descr2 = OptionDescription("opt2", "", [intoption, s, descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert not 'hidden' in await cfg.option('opt.str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('opt.str').value.set(['a', 'b']) - assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert not 'hidden' in await cfg.option('opt.str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('opt.str').value.set(['a', 'b']) + assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -358,15 +370,16 @@ async def test_apply_requires_from_config(): stroption = StrOption('str', 'Test string option', default=["abc"], properties=(hidden_property,), multi=True) descr = OptionDescription("opt", "", [stroption]) descr2 = OptionDescription("opt2", "", [intoption, s, descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert not 'hidden' in await cfg.option('opt.str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('opt.str').value.get() - assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() - assert 'hidden' not in await cfg.forcepermissive.option('opt.str').option.properties() - assert 'hidden' not in await cfg.forcepermissive.option('opt.str').option.properties(only_raises=True) + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert not 'hidden' in await cfg.option('opt.str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('opt.str').value.get() + assert 'hidden' in await cfg.forcepermissive.option('opt.str').property.get() + assert 'hidden' not in await cfg.forcepermissive.option('opt.str').option.properties() + assert 'hidden' not in await cfg.forcepermissive.option('opt.str').option.properties(only_raises=True) + assert not await list_sessions() @pytest.mark.asyncio @@ -380,15 +393,16 @@ async def test_apply_requires_with_disabled(): stroption = StrOption('str', 'Test string option', default=["abc"], properties=(disabled_property,), multi=True) descr = OptionDescription("opt", "", [stroption]) descr2 = OptionDescription("opt2", "", [intoption, s, descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert not 'disabled' in await cfg.option('opt.str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('opt.str').value.get() - assert 'disabled' not in await cfg.unrestraint.option('opt.str').option.properties() - assert 'disabled' not in await cfg.unrestraint.option('opt.str').option.properties(only_raises=True) - assert 'disabled' in await cfg.unrestraint.option('opt.str').property.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert not 'disabled' in await cfg.option('opt.str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('opt.str').value.get() + assert 'disabled' not in await cfg.unrestraint.option('opt.str').option.properties() + assert 'disabled' not in await cfg.unrestraint.option('opt.str').option.properties(only_raises=True) + assert 'disabled' in await cfg.unrestraint.option('opt.str').property.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -402,57 +416,58 @@ async def test_multi_with_requires_with_disabled_in_another_group(): stroption = StrOption('str', 'Test string option', default=["abc"], properties=(disabled_property,), multi=True) descr = OptionDescription("opt", "", [stroption]) descr2 = OptionDescription("opt2", "", [intoption, s, descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert not 'disabled' in await cfg.option('opt.str').property.get() - await cfg.option('int').value.set(1) - with pytest.raises(PropertiesOptionError): - await cfg.option('opt.str').value.set(['a', 'b']) - assert 'disabled' in await cfg.unrestraint.option('opt.str').property.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert not 'disabled' in await cfg.option('opt.str').property.get() + await cfg.option('int').value.set(1) + with pytest.raises(PropertiesOptionError): + await cfg.option('opt.str').value.set(['a', 'b']) + assert 'disabled' in await cfg.unrestraint.option('opt.str').property.get() + assert not await list_sessions() + + +# FIXME @pytest.mark.asyncio +# FIXME async def test_multi_with_requires_that_is_multi(): +# FIXME b = IntOption('int', 'Test int option', default=[0], multi=True) +# FIXME hidden_property = Calculation(calc_value, +# FIXME Params(ParamValue('hidden'), +# FIXME kwargs={'condition': ParamOption(b), +# FIXME 'expected': ParamValue(1)})) +# FIXME c = StrOption('str', 'Test string option', default=['abc'], properties=(hidden_property,), multi=True) +# FIXME descr = OptionDescription("opt", "", [b, c]) +# FIXME descr +# FIXME # FIXME: ValueError: requirement mal formĂ©s pour l'option "int" ne doit pas Ăªtre une valeur multiple pour "str" +# FIXME with pytest.raises(ValueError): +# FIXME Config(descr)") # # -#@pytest.mark.asyncio -#async def test_multi_with_requires_that_is_multi(): -# b = IntOption('int', 'Test int option', default=[0], multi=True) -# hidden_property = Calculation(calc_value, -# Params(ParamValue('hidden'), -# kwargs={'condition': ParamOption(b), -# 'expected': ParamValue(1)})) -# c = StrOption('str', 'Test string option', default=['abc'], properties=(hidden_property,), multi=True) -# descr = OptionDescription("opt", "", [b, c]) -# descr -# # FIXME: ValueError: requirement mal formĂ©s pour l'option "int" ne doit pas Ăªtre une valeur multiple pour "str" -# with pytest.raises(ValueError): -# Config(descr)") +# FIXME @pytest.mark.asyncio +# FIXME async def test_multi_with_requires_that_is_multi_inverse(): +# FIXME b = IntOption('int', 'Test int option', default=[0], multi=True) +# FIXME c = StrOption('str', 'Test string option', default=['abc'], requires=[{'option': b, 'expected': 0, 'action': 'hidden', 'inverse': True}], multi=True) +# FIXME descr = OptionDescription("opt", "", [b, c]) +# FIXME descr +# FIXME Config(descr) +# FIXME # FIXME: ValueError: requirement mal formĂ©s pour l'option "int" ne doit pas Ăªtre une valeur multiple pour "str" +# FIXME with pytest.raises(ValueError): +# FIXME Config(descr)") # # -#@pytest.mark.asyncio -#async def test_multi_with_requires_that_is_multi_inverse(): -# b = IntOption('int', 'Test int option', default=[0], multi=True) -# c = StrOption('str', 'Test string option', default=['abc'], requires=[{'option': b, 'expected': 0, 'action': 'hidden', 'inverse': True}], multi=True) -# descr = OptionDescription("opt", "", [b, c]) -# descr -# Config(descr) -# # FIXME: ValueError: requirement mal formĂ©s pour l'option "int" ne doit pas Ăªtre une valeur multiple pour "str" -# with pytest.raises(ValueError): -# Config(descr)") +# FIXME @pytest.mark.asyncio +# FIXME async def test_multi_with_requires_that_is_leadership(): +# FIXME b = IntOption('int', 'Test int option', default=[0], multi=True) +# FIXME c = StrOption('str', 'Test string option', requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True) +# FIXME descr = Leadership("int", "", [b, c]) +# FIXME od = OptionDescription('root', '', [descr]) +# FIXME Config(od) # # -#@pytest.mark.asyncio -#async def test_multi_with_requires_that_is_leadership(): -# b = IntOption('int', 'Test int option', default=[0], multi=True) -# c = StrOption('str', 'Test string option', requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True) -# descr = Leadership("int", "", [b, c]) -# od = OptionDescription('root', '', [descr]) -# Config(od) -# -# -#@pytest.mark.asyncio -#async def test_multi_with_requires_that_is_leadership_leader(): -# b = IntOption('int', 'Test int option', multi=True) -# c = StrOption('str', 'Test string option', requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True) -# with pytest.raises(ValueError): -# Leadership('str', '', [c, b])") +# FIXME @pytest.mark.asyncio +# FIXME async def test_multi_with_requires_that_is_leadership_leader(): +# FIXME b = IntOption('int', 'Test int option', multi=True) +# FIXME c = StrOption('str', 'Test string option', requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True) +# FIXME with pytest.raises(ValueError): +# FIXME Leadership('str', '', [c, b])") @pytest.mark.asyncio @@ -467,25 +482,26 @@ async def test_multi_with_requires_that_is_leadership_follower(): d = StrOption('str1', 'Test string option', properties=(hidden_property,), multi=True) descr = Leadership("int", "", [b, c, d]) descr2 = OptionDescription('od', '', [descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert await cfg.option('int.int').value.get() == [0] - assert await cfg.option('int.str', 0).value.get() == None - assert await cfg.option('int.str1', 0).value.get() == None - await cfg.option('int.int').value.set([0, 1]) - assert await cfg.option('int.int').value.get() == [0, 1] - assert await cfg.option('int.str', 0).value.get() == None - assert await cfg.option('int.str', 1).value.get() == None - assert await cfg.option('int.str1', 0).value.get() == None - assert await cfg.option('int.str1', 1).value.get() == None - await cfg.option('int.str', 1).value.set('1') - await cfg.property.read_only() - assert await cfg.option('int.str1', 0).value.get() == None - assert await cfg.option('int.str1', 1).value.get() == None - await cfg.property.read_write() - assert await cfg.option('int.str1', 0).value.get() == None - with pytest.raises(PropertiesOptionError): - await cfg.option('int.str1', 1).value.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert await cfg.option('int.int').value.get() == [0] + assert await cfg.option('int.str', 0).value.get() == None + assert await cfg.option('int.str1', 0).value.get() == None + await cfg.option('int.int').value.set([0, 1]) + assert await cfg.option('int.int').value.get() == [0, 1] + assert await cfg.option('int.str', 0).value.get() == None + assert await cfg.option('int.str', 1).value.get() == None + assert await cfg.option('int.str1', 0).value.get() == None + assert await cfg.option('int.str1', 1).value.get() == None + await cfg.option('int.str', 1).value.set('1') + await cfg.property.read_only() + assert await cfg.option('int.str1', 0).value.get() == None + assert await cfg.option('int.str1', 1).value.get() == None + await cfg.property.read_write() + assert await cfg.option('int.str1', 0).value.get() == None + with pytest.raises(PropertiesOptionError): + await cfg.option('int.str1', 1).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -501,25 +517,26 @@ async def test_multi_with_requires_that_is_leadership_follower_inverse(): d = StrOption('str1', 'Test string option', properties=(hidden_property,), multi=True) descr = Leadership("int", "", [b, c, d]) descr2 = OptionDescription('od', '', [descr]) - cfg = await Config(descr2) - await cfg.property.read_write() - assert await cfg.option('int.int').value.get() == [0] - assert await cfg.option('int.str', 0).value.get() is None - assert await cfg.option('int.str1', 0).value.get() is None - await cfg.option('int.int').value.set([0, 1]) - assert await cfg.option('int.int').value.get() == [0, 1] - assert await cfg.option('int.str', 0).value.get() is None - assert await cfg.option('int.str', 1).value.get() is None - assert await cfg.option('int.str1', 0).value.get() is None - assert await cfg.option('int.str1', 1).value.get() is None - await cfg.option('int.str', 1).value.set('1') - await cfg.property.read_only() - assert await cfg.option('int.str1', 0).value.get() is None - assert await cfg.option('int.str1', 1).value.get() is None - await cfg.property.read_write() - assert await cfg.option('int.str1', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('int.str1', 1).value.get() + async with await Config(descr2) as cfg: + await cfg.property.read_write() + assert await cfg.option('int.int').value.get() == [0] + assert await cfg.option('int.str', 0).value.get() is None + assert await cfg.option('int.str1', 0).value.get() is None + await cfg.option('int.int').value.set([0, 1]) + assert await cfg.option('int.int').value.get() == [0, 1] + assert await cfg.option('int.str', 0).value.get() is None + assert await cfg.option('int.str', 1).value.get() is None + assert await cfg.option('int.str1', 0).value.get() is None + assert await cfg.option('int.str1', 1).value.get() is None + await cfg.option('int.str', 1).value.set('1') + await cfg.property.read_only() + assert await cfg.option('int.str1', 0).value.get() is None + assert await cfg.option('int.str1', 1).value.get() is None + await cfg.property.read_write() + assert await cfg.option('int.str1', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('int.str1', 1).value.get() + assert not await list_sessions() #@pytest.mark.asyncio @@ -538,7 +555,7 @@ async def test_multi_with_requires_that_is_leadership_follower_inverse(): # descr2 = Leadership("int1", "", [d, e]) # descr3 = OptionDescription('val', '', [descr1, descr2]) # descr3 -# with pytest.raises(ValueError): +# with pytest.raises(ValueError): # Config(descr3)") @@ -546,18 +563,20 @@ async def test_multi_with_requires_that_is_leadership_follower_inverse(): async def test_multi_with_bool(): s = BoolOption("bool", "", default=[False], multi=True) descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - await cfg.option('bool').value.set([True, False]) - assert await cfg.option('bool').value.get() == [True, False] + async with await Config(descr) as cfg: + await cfg.option('bool').value.set([True, False]) + assert await cfg.option('bool').value.get() == [True, False] + assert not await list_sessions() @pytest.mark.asyncio async def test_choice_access_with_multi(): ch = ChoiceOption("t1", "", ("a", "b"), default=["a"], multi=True, properties=('notunique',)) descr = OptionDescription("options", "", [ch]) - cfg = await Config(descr) - await cfg.option('t1').value.set(["a", "b", "a", "b"]) - assert await cfg.option('t1').value.get() == ["a", "b", "a", "b"] + async with await Config(descr) as cfg: + await cfg.option('t1').value.set(["a", "b", "a", "b"]) + assert await cfg.option('t1').value.get() == ["a", "b", "a", "b"] + assert not await list_sessions() #____________________________________________________________ @@ -565,15 +584,16 @@ async def test_choice_access_with_multi(): async def test_accepts_multiple_changes_from_option(): s = StrOption("string", "", default="string") descr = OptionDescription("options", "", [s]) - cfg = await Config(descr) - await cfg.option('string').value.set("egg") - assert await cfg.option('string').option.default() == "string" - assert await cfg.option('string').value.get() == "egg" - await cfg.option('string').value.set('blah') - assert await cfg.option('string').option.default() == "string" - assert await cfg.option('string').value.get() == "blah" - await cfg.option('string').value.set('bol') - assert await cfg.option('string').value.get() == 'bol' + async with await Config(descr) as cfg: + await cfg.option('string').value.set("egg") + assert await cfg.option('string').option.default() == "string" + assert await cfg.option('string').value.get() == "egg" + await cfg.option('string').value.set('blah') + assert await cfg.option('string').option.default() == "string" + assert await cfg.option('string').value.get() == "blah" + await cfg.option('string').value.set('bol') + assert await cfg.option('string').value.get() == 'bol' + assert not await list_sessions() @pytest.mark.asyncio @@ -586,11 +606,12 @@ async def test_allow_multiple_changes_from_config(): s2 = StrOption("string2", "", default="string") suboption = OptionDescription("bip", "", [s2]) descr = OptionDescription("options", "", [s, suboption]) - cfg = await Config(descr) - await cfg.option('string').value.set("oh") - assert await cfg.option('string').value.get() == "oh" - await cfg.option('string').value.set("blah") - assert await cfg.option('string').value.get() == "blah" + async with await Config(descr) as cfg: + await cfg.option('string').value.set("oh") + assert await cfg.option('string').value.get() == "oh" + await cfg.option('string').value.set("blah") + assert await cfg.option('string').value.get() == "blah" + assert not await list_sessions() # ____________________________________________________________ @@ -598,13 +619,14 @@ async def test_allow_multiple_changes_from_config(): @pytest.mark.asyncio async def test_access_by_get(): descr = make_description() - cfg = await Config(descr) - with pytest.raises(AttributeError): - list(await cfg.option.find('idontexist')) - ret = await cfg.option.find('wantref', first=True) - assert await ret.value.get() is False - ret = await cfg.option.find('dummy', first=True) - assert await ret.value.get() is False + async with await Config(descr) as cfg: + with pytest.raises(AttributeError): + list(await cfg.option.find('idontexist')) + ret = await cfg.option.find('wantref', first=True) + assert await ret.value.get() is False + ret = await cfg.option.find('dummy', first=True) + assert await ret.value.get() is False + assert not await list_sessions() @pytest.mark.asyncio @@ -616,43 +638,47 @@ async def test_access_by_get_whith_hide(): BoolOption("d1", "")]), BoolOption("b2", ""), BoolOption("d1", "")]) - cfg = await Config(descr) - await cfg.property.read_write() - with pytest.raises(AttributeError): - ret = await cfg.option.find('b1') - await ret.value.get() + async with await Config(descr) as cfg: + await cfg.property.read_write() + with pytest.raises(AttributeError): + ret = await cfg.option.find('b1') + await ret.value.get() + assert not await list_sessions() @pytest.mark.asyncio async def test_append_properties(): descr = make_description() - cfg = await Config(descr) - assert await cfg.option('gc.dummy').property.get() == set() - await cfg.option('gc.dummy').property.add('test') - assert await cfg.option('gc.dummy').property.get() == {'test'} - with pytest.raises(ConfigError): - await cfg.option('gc.dummy').property.add('force_store_value') - assert await cfg.option('gc.dummy').property.get() == {'test'} + async with await Config(descr) as cfg: + assert await cfg.option('gc.dummy').property.get() == set() + await cfg.option('gc.dummy').property.add('test') + assert await cfg.option('gc.dummy').property.get() == {'test'} + with pytest.raises(ConfigError): + await cfg.option('gc.dummy').property.add('force_store_value') + assert await cfg.option('gc.dummy').property.get() == {'test'} + assert not await list_sessions() @pytest.mark.asyncio async def test_reset_properties(): descr = make_description() - cfg = await Config(descr) - assert await cfg.option('gc.dummy').property.get() == set() - await cfg.option('gc.dummy').property.add('frozen') - assert await cfg.option('gc.dummy').property.get() == {'frozen'} - await cfg.option('gc.dummy').property.reset() - assert await cfg.option('gc.dummy').property.get() == set() + async with await Config(descr) as cfg: + assert await cfg.option('gc.dummy').property.get() == set() + await cfg.option('gc.dummy').property.add('frozen') + assert await cfg.option('gc.dummy').property.get() == {'frozen'} + await cfg.option('gc.dummy').property.reset() + assert await cfg.option('gc.dummy').property.get() == set() + assert not await list_sessions() @pytest.mark.asyncio async def test_properties_cached(): b1 = BoolOption("b1", "", properties=('test',)) descr = OptionDescription("opt", "", [OptionDescription("sub", "", [b1])]) - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.option('sub.b1').property.get() == {'test'} + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.option('sub.b1').property.get() == {'test'} + assert not await list_sessions() @pytest.mark.asyncio @@ -660,10 +686,11 @@ async def test_append_properties_force_store_value(): gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('force_store_value',)) gcgroup = OptionDescription('gc', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcgroup]) - cfg = await Config(descr) - assert await cfg.option('gc.dummy').property.get() == {'force_store_value'} - await cfg.option('gc.dummy').property.add('test') - assert await cfg.option('gc.dummy').property.get() == {'force_store_value', 'test'} + async with await Config(descr) as cfg: + assert await cfg.option('gc.dummy').property.get() == {'force_store_value'} + await cfg.option('gc.dummy').property.add('test') + assert await cfg.option('gc.dummy').property.get() == {'force_store_value', 'test'} + assert not await list_sessions() @pytest.mark.asyncio @@ -671,38 +698,39 @@ async def test_reset_properties_force_store_value(): gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('force_store_value',)) gcgroup = OptionDescription('gc', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcgroup]) - cfg = await Config(descr) - assert await cfg.property.exportation() == {} - await cfg.property.add('frozen') - assert await cfg.property.exportation() == \ - {None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}} - await cfg.property.reset() - if environ.get('TIRAMISU_STORAGE') == 'sqlite3': + async with await Config(descr) as cfg: assert await cfg.property.exportation() == {} - else: - assert await cfg.property.exportation() == {None: {}} - await cfg.option('gc.dummy').property.add('test') - if environ.get('TIRAMISU_STORAGE') == 'sqlite3': - assert await cfg.property.exportation() == {'gc.dummy': {None: set(('test', 'force_store_value'))}} - else: - assert await cfg.property.exportation() == {None: {}, 'gc.dummy': {None: set(('test', 'force_store_value'))}} - await cfg.property.reset() - if environ.get('TIRAMISU_STORAGE') == 'sqlite3': - assert await cfg.property.exportation() == {'gc.dummy': {None: set(('test', 'force_store_value'))}} - else: - assert await cfg.property.exportation() == {None: {}, 'gc.dummy': {None: set(('test', 'force_store_value'))}} - await cfg.property.add('frozen') - assert await cfg.property.exportation() == \ - {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, - 'gc.dummy': {None: set(('test', 'force_store_value'))}} - await cfg.property.add('frozen') - assert await cfg.property.exportation() == \ - {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, - 'gc.dummy': {None: set(('test', 'force_store_value'))}} - await cfg.option('gc.dummy').property.add('test') - assert await cfg.property.exportation() == \ - {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, - 'gc.dummy': {None: set(('test', 'force_store_value'))}} + await cfg.property.add('frozen') + assert await cfg.property.exportation() == \ + {None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}} + await cfg.property.reset() + if environ.get('TIRAMISU_STORAGE') in ['sqlite3', 'postgres']: + assert await cfg.property.exportation() == {} + else: + assert await cfg.property.exportation() == {None: {}} + await cfg.option('gc.dummy').property.add('test') + if environ.get('TIRAMISU_STORAGE') in ['sqlite3', 'postgres']: + assert await cfg.property.exportation() == {'gc.dummy': {None: set(('test', 'force_store_value'))}} + else: + assert await cfg.property.exportation() == {None: {}, 'gc.dummy': {None: set(('test', 'force_store_value'))}} + await cfg.property.reset() + if environ.get('TIRAMISU_STORAGE') in ['sqlite3', 'postgres']: + assert await cfg.property.exportation() == {'gc.dummy': {None: set(('test', 'force_store_value'))}} + else: + assert await cfg.property.exportation() == {None: {}, 'gc.dummy': {None: set(('test', 'force_store_value'))}} + await cfg.property.add('frozen') + assert await cfg.property.exportation() == \ + {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, + 'gc.dummy': {None: set(('test', 'force_store_value'))}} + await cfg.property.add('frozen') + assert await cfg.property.exportation() == \ + {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, + 'gc.dummy': {None: set(('test', 'force_store_value'))}} + await cfg.option('gc.dummy').property.add('test') + assert await cfg.property.exportation() == \ + {None: {None: set(('frozen', 'validator', 'cache', 'warnings'))}, + 'gc.dummy': {None: set(('test', 'force_store_value'))}} + assert not await list_sessions() @pytest.mark.asyncio @@ -711,19 +739,20 @@ async def test_importation_force_store_value(): properties=('force_store_value',)) gcgroup = OptionDescription('gc', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcgroup]) - config1 = await Config(descr) - assert await config1.value.exportation() == [[], [], [], []] - await config1.property.add('frozen') - assert await config1.value.exportation() == [[], [], [], []] - await config1.property.add('force_store_value') - assert await config1.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] - exportation = await config1.property.exportation() - config2 = await Config(descr) - assert await config2.value.exportation() == [[], [], [], []] - await config2.property.importation(exportation) - assert await config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] - await config2.property.importation(exportation) - assert await config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] + async with await Config(descr) as config1: + assert await config1.value.exportation() == [[], [], [], []] + await config1.property.add('frozen') + assert await config1.value.exportation() == [[], [], [], []] + await config1.property.add('force_store_value') + assert await config1.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] + exportation = await config1.property.exportation() + async with await Config(descr) as config2: + assert await config2.value.exportation() == [[], [], [], []] + await config2.property.importation(exportation) + assert await config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] + await config2.property.importation(exportation) + assert await config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']] + assert not await list_sessions() @pytest.mark.asyncio @@ -731,11 +760,12 @@ async def test_set_modified_value(): gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('force_store_value',)) gcgroup = OptionDescription('gc', '', [gcdummy]) descr = OptionDescription('tiramisu', '', [gcgroup]) - cfg = await Config(descr) - assert await cfg.property.exportation() == {} - await cfg.property.importation({None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}}) - assert await cfg.property.exportation() == \ - {None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}} + async with await Config(descr) as cfg: + assert await cfg.property.exportation() == {} + await cfg.property.importation({None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}}) + assert await cfg.property.exportation() == \ + {None: {None: set(('frozen', 'cache', 'validator', 'warnings'))}} + assert not await list_sessions() @pytest.mark.asyncio @@ -791,55 +821,56 @@ async def test_pprint(): #val3 = StrOption('val3', "", requires=[{'option': stroption, 'expected': '2', 'action': 'hidden', 'inverse': True}]) descr = OptionDescription("options", "", [s, s2, s3, intoption, stroption, descr2, val3]) - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('int').value.set(1) - err = None - try: - await cfg.option('str').value.get() - except PropertiesOptionError as error: - err = error + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('int').value.set(1) + err = None + try: + await cfg.option('str').value.get() + except PropertiesOptionError as error: + err = error - list_disabled = '"disabled" (' + display_list([msg_is.format('Test int option', '"1"'), msg_is.format('string2', '"string"')], add_quote=False) + ')' - list_hidden = '"hidden" (' + msg_is_not.format('Test int option', display_list([2, 3, 4], 'or', add_quote=True)) + ')' - # FIXME assert str(err) == _(msg_error.format('option', 'Test string option', properties, display_list([list_disabled, list_hidden], add_quote=False))) - del err + list_disabled = '"disabled" (' + display_list([msg_is.format('Test int option', '"1"'), msg_is.format('string2', '"string"')], add_quote=False) + ')' + list_hidden = '"hidden" (' + msg_is_not.format('Test int option', display_list([2, 3, 4], 'or', add_quote=True)) + ')' + assert str(err) == _(msg_error.format('option', 'Test string option', properties, display_list([list_disabled, list_hidden], add_quote=False))) + del err - err = None - try: - await cfg.option('options.val2').value.get() - except PropertiesOptionError as error: - err = error + err = None + try: + await cfg.option('options.val2').value.get() + except PropertiesOptionError as error: + err = error - # FIXME assert str(err) == msg_error.format('optiondescription', 'options', prop, '"hidden" (' + msg_is.format('Test int option', '"1"') + ')') + assert str(err) == msg_error.format('optiondescription', 'options', prop, '"hidden" (' + msg_is.format('Test int option', '"1"') + ')') - #err = None - #try: - # await cfg.option('val3').value.get() - #except PropertiesOptionError as error: - # err = error + #err = None + #try: + # await cfg.option('val3').value.get() + #except PropertiesOptionError as error: + # err = error - #msg_1 = msg_is.format('string2', 'string') - #msg_2 = msg_is.format('Test int option', 1) - #msg_3 = msg_is_not.format('Test int option', display_list([2, 3, 4], 'or', add_quote=True)) - #list_hidden = '"hidden" (' + display_list([msg_2, msg_3, msg_1]) + ')' + #msg_1 = msg_is.format('string2', 'string') + #msg_2 = msg_is.format('Test int option', 1) + #msg_3 = msg_is_not.format('Test int option', display_list([2, 3, 4], 'or', add_quote=True)) + #list_hidden = '"hidden" (' + display_list([msg_2, msg_3, msg_1]) + ')' - #assert str(err) == msg_error.format('option', 'val3', prop, list_hidden) + #assert str(err) == msg_error.format('option', 'val3', prop, list_hidden) - err = None - try: - await cfg.option('string').value.get() - except Exception as error: - err = error + err = None + try: + await cfg.option('string').value.get() + except Exception as error: + err = error - assert str(err) == msg_error.format('option', 'string', properties, display_list(['disabled', 'hidden'], add_quote=True)) - del err + assert str(err) == msg_error.format('option', 'string', properties, display_list(['disabled', 'hidden'], add_quote=True)) + del err - err = None - try: - await cfg.option('string3').value.get() - except Exception as error: - err = error + err = None + try: + await cfg.option('string3').value.get() + except Exception as error: + err = error - assert str(err) == msg_error.format('option', 'string3', prop, '"hidden"') - del err + assert str(err) == msg_error.format('option', 'string3', prop, '"hidden"') + del err + assert not await list_sessions() diff --git a/tests/test_option_type.py b/tests/test_option_type.py index db5ff08..4398877 100644 --- a/tests/test_option_type.py +++ b/tests/test_option_type.py @@ -2,7 +2,6 @@ "frozen and hidden values" from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest @@ -11,10 +10,7 @@ from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \ Calculation, Params, ParamOption, ParamValue, calc_value from tiramisu.error import PropertiesOptionError from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop def make_description(): @@ -56,140 +52,147 @@ def make_description(): @pytest.mark.asyncio async def test_is_hidden(config_type): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - assert not 'frozen' in await cfg.forcepermissive.option('gc.dummy').property.get() - cfg = await get_config(cfg, config_type) - # setattr - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.get() == False - # getattr - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.get() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert not 'frozen' in await cfg.forcepermissive.option('gc.dummy').property.get() + cfg = await get_config(cfg, config_type) + # setattr + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.get() == False + # getattr + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.get() + assert not await list_sessions() @pytest.mark.asyncio async def test_group_is_hidden(config_type): descr = make_description() - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - await cfg_ori.option('gc').property.add('hidden') - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - assert 'hidden' in await cfg_ori.forcepermissive.option('gc').property.get() - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.float').value.get() - # manually set the subconfigs to "show" - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('gc').property.pop('hidden') - cfg = await get_config(cfg_ori, config_type) - assert not 'hidden' in await cfg.option('gc').property.get() - assert await cfg.option('gc.float').value.get() == 2.3 - #dummy est en hide - prop = [] - try: - await cfg.option('gc.dummy').value.set(False) - except PropertiesOptionError as err: - prop = err.proptype - if config_type == 'tiramisu-api': - assert 'disabled' in prop - else: - assert 'hidden' in prop + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.option('gc').property.add('hidden') + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.get() + if config_type == 'tiramisu-api': + await cfg.send() + assert 'hidden' in await cfg_ori.forcepermissive.option('gc').property.get() + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.float').value.get() + # manually set the subconfigs to "show" + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('gc').property.pop('hidden') + cfg = await get_config(cfg_ori, config_type) + assert not 'hidden' in await cfg.option('gc').property.get() + assert await cfg.option('gc.float').value.get() == 2.3 + #dummy est en hide + prop = [] + try: + await cfg.option('gc.dummy').value.set(False) + except PropertiesOptionError as err: + prop = err.proptype + if config_type == 'tiramisu-api': + assert 'disabled' in prop + else: + assert 'hidden' in prop + assert not await list_sessions() @pytest.mark.asyncio async def test_group_is_hidden_multi(config_type): descr = make_description() - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - await cfg_ori.option('objspace').property.add('hidden') - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('objspace').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - assert 'hidden' in await cfg_ori.forcepermissive.option('objspace').property.get() - cfg = await get_config(cfg_ori, config_type) - prop = [] - try: - await cfg.option('objspace').value.set(['std']) - except PropertiesOptionError as err: - prop = err.proptype - if config_type == 'tiramisu-api': - assert 'disabled' in prop - else: - assert 'hidden' in prop - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('objspace').property.pop('hidden') - cfg = await get_config(cfg_ori, config_type) - assert not 'hidden' in await cfg.option('objspace').property.get() - await cfg.option('objspace').value.set(['std', 'thunk']) + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.option('objspace').property.add('hidden') + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('objspace').value.get() + if config_type == 'tiramisu-api': + await cfg.send() + assert 'hidden' in await cfg_ori.forcepermissive.option('objspace').property.get() + cfg = await get_config(cfg_ori, config_type) + prop = [] + try: + await cfg.option('objspace').value.set(['std']) + except PropertiesOptionError as err: + prop = err.proptype + if config_type == 'tiramisu-api': + assert 'disabled' in prop + else: + assert 'hidden' in prop + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('objspace').property.pop('hidden') + cfg = await get_config(cfg_ori, config_type) + assert not 'hidden' in await cfg.option('objspace').property.get() + await cfg.option('objspace').value.set(['std', 'thunk']) + assert not await list_sessions() @pytest.mark.asyncio async def test_global_show(config_type): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.forcepermissive.option('gc.dummy').property.add('hidden') - assert 'hidden' in await cfg.forcepermissive.option('gc.dummy').property.get() - cfg = await get_config(cfg, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('gc.dummy').value.get() == False + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.forcepermissive.option('gc.dummy').property.add('hidden') + assert 'hidden' in await cfg.forcepermissive.option('gc.dummy').property.get() + cfg = await get_config(cfg, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('gc.dummy').value.get() == False + assert not await list_sessions() @pytest.mark.asyncio async def test_with_many_subgroups(config_type): descr = make_description() - cfg_ori = await Config(descr) - #booltwo = config.unwrap_from_path('gc.subgroup.booltwo') - #setting = config.cfgimpl_get_settings() - cfg = await get_config(cfg_ori, config_type) - assert not 'hidden' in await cfg.option('gc.subgroup.booltwo').property.get() - assert await cfg.option('gc.subgroup.booltwo').value.get() is False - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.option('gc.subgroup.booltwo').property.add('hidden') + async with await Config(descr) as cfg_ori: + #booltwo = config.unwrap_from_path('gc.subgroup.booltwo') + #setting = config.cfgimpl_get_settings() + cfg = await get_config(cfg_ori, config_type) + assert not 'hidden' in await cfg.option('gc.subgroup.booltwo').property.get() + assert await cfg.option('gc.subgroup.booltwo').value.get() is False + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.option('gc.subgroup.booltwo').property.add('hidden') + assert not await list_sessions() @pytest.mark.asyncio async def test_password_option(config_type): o = PasswordOption('o', '') d = OptionDescription('d', '', [o]) - cfg = await Config(d) - cfg = await get_config(cfg, config_type) + async with await Config(d) as cfg: + cfg = await get_config(cfg, config_type) - await cfg.option('o').value.set('a_valid_password') - with pytest.raises(ValueError): - await cfg.option('o').value.set(1) + await cfg.option('o').value.set('a_valid_password') + with pytest.raises(ValueError): + await cfg.option('o').value.set(1) + assert not await list_sessions() @pytest.mark.asyncio async def test_date_option(config_type): o = DateOption('o', '') d = OptionDescription('d', '', [o]) - cfg = await Config(d) - cfg = await get_config(cfg, config_type) + async with await Config(d) as cfg: + cfg = await get_config(cfg, config_type) - await cfg.option('o').value.set('2017-02-04') - await cfg.option('o').value.set('2017-2-4') - with pytest.raises(ValueError): - await cfg.option('o').value.set(1) - with pytest.raises(ValueError): - await cfg.option('o').value.set('2017-13-20') - with pytest.raises(ValueError): - await cfg.option('o').value.set('2017-11-31') - with pytest.raises(ValueError): - await cfg.option('o').value.set('2017-12-32') - with pytest.raises(ValueError): - await cfg.option('o').value.set('2017-2-29') - with pytest.raises(ValueError): - await cfg.option('o').value.set('2-2-2017') - with pytest.raises(ValueError): - await cfg.option('o').value.set('2017/2/2') + await cfg.option('o').value.set('2017-02-04') + await cfg.option('o').value.set('2017-2-4') + with pytest.raises(ValueError): + await cfg.option('o').value.set(1) + with pytest.raises(ValueError): + await cfg.option('o').value.set('2017-13-20') + with pytest.raises(ValueError): + await cfg.option('o').value.set('2017-11-31') + with pytest.raises(ValueError): + await cfg.option('o').value.set('2017-12-32') + with pytest.raises(ValueError): + await cfg.option('o').value.set('2017-2-29') + with pytest.raises(ValueError): + await cfg.option('o').value.set('2-2-2017') + with pytest.raises(ValueError): + await cfg.option('o').value.set('2017/2/2') + assert not await list_sessions() diff --git a/tests/test_option_username.py b/tests/test_option_username.py index f06d55d..d618b96 100644 --- a/tests/test_option_username.py +++ b/tests/test_option_username.py @@ -2,10 +2,9 @@ from .autopath import do_autopath do_autopath() -from py.test import raises +import pytest -from tiramisu.option import UsernameOption -from tiramisu.storage import list_sessions +from tiramisu import UsernameOption def test_username(): @@ -15,14 +14,20 @@ def test_username(): UsernameOption('a', '', 'string_') UsernameOption('a', '', 'string$') UsernameOption('a', '', '_string$') - raises(ValueError, "UsernameOption('a', '', 'strin$g')") + with pytest.raises(ValueError): + UsernameOption('a', '', 'strin$g') UsernameOption('a', '', 's-tring') - raises(ValueError, "UsernameOption('a', '', '-string')") + with pytest.raises(ValueError): + UsernameOption('a', '', '-string') UsernameOption('a', '', 's9tring') - raises(ValueError, "UsernameOption('a', '', '9string')") - raises(ValueError, "UsernameOption('a', '', '')") + with pytest.raises(ValueError): + UsernameOption('a', '', '9string') + with pytest.raises(ValueError): + UsernameOption('a', '', '') UsernameOption('a', '', 's') UsernameOption('a', '', 's2345678901234567890123456789012') - raises(ValueError, "UsernameOption('a', '', 's23456789012345678901234567890123')") + with pytest.raises(ValueError): + UsernameOption('a', '', 's23456789012345678901234567890123') UsernameOption('a', '', 's234567890123456789012345678901$') - raises(ValueError, "UsernameOption('a', '', 's2345678901234567890123456789012$')") + with pytest.raises(ValueError): + UsernameOption('a', '', 's2345678901234567890123456789012$') diff --git a/tests/test_option_validator.py b/tests/test_option_validator.py index 748eacb..5ab0ab0 100644 --- a/tests/test_option_validator.py +++ b/tests/test_option_validator.py @@ -1,6 +1,5 @@ from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import warnings import pytest @@ -13,10 +12,7 @@ from tiramisu.setting import groups from tiramisu.error import ValueWarning, ConfigError, PropertiesOptionError from tiramisu.i18n import _ from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop msg_err = _('attention, "{0}" could be an invalid {1} for "{2}"') @@ -88,35 +84,36 @@ async def test_validator(config_type): opt1 = StrOption('opt1', '', validators=[Calculation(return_true, Params(ParamSelfOption()))], default='val') opt2 = StrOption('opt2', '', validators=[Calculation(return_false, Params(ParamSelfOption()))]) root = OptionDescription('root', '', [opt1, opt2]) - cfg_ori = await Config(root) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('opt1').value.get() == 'val' - with pytest.raises(ValueError): - await cfg.option('opt2').value.set('val') - try: - await cfg.option('opt2').value.set('val') - except ValueError as err: - msg = _('"{0}" is an invalid {1} for "{2}"').format('val', _('string'), 'opt2') + ', ' + _('test error return_false') - assert str(err) == msg + async with await Config(root) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('opt1').value.get() == 'val' + with pytest.raises(ValueError): + await cfg.option('opt2').value.set('val') + try: + await cfg.option('opt2').value.set('val') + except ValueError as err: + msg = _('"{0}" is an invalid {1} for "{2}"').format('val', _('string'), 'opt2') + ', ' + _('test error return_false') + assert str(err) == msg + if config_type == 'tiramisu-api': + msg = _('"{0}" is an invalid {1} for "{2}"').format('val', 'string', 'opt2') + ', ' + _('test error return_false') if config_type == 'tiramisu-api': - msg = _('"{0}" is an invalid {1} for "{2}"').format('val', 'string', 'opt2') + ', ' + _('test error return_false') - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - assert len(w) == 1 - assert str(w[0].message) == msg - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.get() - assert len(w) == 1 - assert str(w[0].message) == msg - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.get() - assert len(w) == 1 - assert str(w[0].message) == msg + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + assert len(w) == 1 + assert str(w[0].message) == msg + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.get() + assert len(w) == 1 + assert str(w[0].message) == msg + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.get() + assert len(w) == 1 + assert str(w[0].message) == msg + assert not await list_sessions() @pytest.mark.asyncio @@ -124,39 +121,42 @@ async def test_validator_params(config_type): opt1 = StrOption('opt1', '', validators=[Calculation(return_true, Params((ParamSelfOption(), ParamValue('yes'))))], default='val') opt2 = StrOption('opt2', '', validators=[Calculation(return_false, Params((ParamSelfOption(), ParamValue('yes'))))]) root = OptionDescription('root', '', [opt1, opt2]) - cfg_ori = await Config(root) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('opt1').value.get() == 'val' - with pytest.raises(ValueError): - await cfg.option('opt2').value.set('val') - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - assert len(w) == 1 + async with await Config(root) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('opt1').value.get() == 'val' + with pytest.raises(ValueError): + await cfg.option('opt2').value.set('val') + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_validator_params_value_values(config_type): opt1 = StrOption('opt1', '', validators=[Calculation(value_values, Params((ParamSelfOption(whole=False), ParamSelfOption())))], default=['val'], multi=True) root = OptionDescription('root', '', [opt1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('opt1').value.get() == ['val'] - await cfg.option('opt1').value.set(['val1', 'val2']) + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('opt1').value.get() == ['val'] + await cfg.option('opt1').value.set(['val1', 'val2']) + assert not await list_sessions() @pytest.mark.asyncio async def test_validator_params_value_values_index(config_type): opt1 = StrOption('opt1', '', validators=[Calculation(value_values_index, Params((ParamSelfOption(whole=False), ParamSelfOption(), ParamIndex())))], default=['val'], multi=True) root = OptionDescription('root', '', [opt1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('opt1').value.get() == ['val'] - await cfg.option('opt1').value.set(['val1', 'val2']) + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('opt1').value.get() == ['val'] + await cfg.option('opt1').value.set(['val1', 'val2']) + assert not await list_sessions() @pytest.mark.asyncio @@ -165,10 +165,11 @@ async def test_validator_params_value_values_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + assert not await list_sessions() @pytest.mark.asyncio @@ -177,10 +178,11 @@ async def test_validator_params_value_values_index_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + assert not await list_sessions() @pytest.mark.asyncio @@ -189,13 +191,14 @@ async def test_validator_params_value_values_follower(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True, validators=[Calculation(value_values, Params((ParamSelfOption(), ParamSelfOption(whole=True))))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + assert not await list_sessions() @pytest.mark.asyncio @@ -204,13 +207,14 @@ async def test_validator_params_value_values_index_follower(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True, validators=[Calculation(value_values_index, Params((ParamSelfOption(), ParamSelfOption(whole=True), ParamIndex())))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + assert not await list_sessions() @pytest.mark.asyncio @@ -223,12 +227,13 @@ async def test_validator_params_value_values_kwargs_empty(config_type): validators=[Calculation(value_empty, Params((ParamSelfOption(), ParamOption(v))))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [v, interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val']) - #await cfg.ip_admin_eth0.ip_admin_eth0.append('val') - #await cfg.ip_admin_eth0.netmask_admin_eth0[1] = 'val2' + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val']) + #await cfg.ip_admin_eth0.ip_admin_eth0.append('val') + #await cfg.ip_admin_eth0.netmask_admin_eth0[1] = 'val2' + assert not await list_sessions() @pytest.mark.asyncio @@ -241,12 +246,13 @@ async def test_validator_params_value_values_kwargs(config_type): validators=[Calculation(value_values_auto, Params((ParamSelfOption(), ParamSelfOption(whole=True)), kwargs={'auto': ParamOption(v)}))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [v, interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip'] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + assert not await list_sessions() @pytest.mark.asyncio @@ -258,13 +264,14 @@ async def test_validator_params_value_values_kwargs_values(config_type): validators=[Calculation(value_values_auto2, Params(ParamSelfOption(), kwargs={'values': ParamOption(ip_admin_eth0)}))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2') + assert not await list_sessions() @pytest.mark.asyncio @@ -272,41 +279,43 @@ async def test_validator_params_option(config_type): opt0 = StrOption('opt0', '', default='yes') opt1 = StrOption('opt1', '', validators=[Calculation(return_true, Params((ParamSelfOption(), ParamOption(opt0))))], default='val') r = OptionDescription('root', '', [opt0, opt1]) - cfg_ori = await Config(r) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('opt1').value.get() == 'val' - await cfg.option('opt0').value.set('val') - with pytest.raises(ValueError): - await cfg.option('opt1').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt1').value.get() - assert len(w) == 1 + async with await Config(r) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('opt1').value.get() == 'val' + await cfg.option('opt0').value.set('val') + with pytest.raises(ValueError): + await cfg.option('opt1').value.get() + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt1').value.get() + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_validator_multi(config_type): opt1 = StrOption('opt1', '', validators=[Calculation(return_if_val, Params(ParamSelfOption(whole=False)))], multi=True) root = OptionDescription('root', '', [opt1]) - cfg_ori = await Config(root) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('opt1').value.get() == [] - await cfg.option('opt1').value.set(['val']) - assert await cfg.option('opt1').value.get() == ['val'] - with pytest.raises(ValueError): - await cfg.option('opt1').value.set(['val', 'val1']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt1').value.set(['val', 'val1']) - assert len(w) == 1 + async with await Config(root) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('opt1').value.get() == [] + await cfg.option('opt1').value.set(['val']) + assert await cfg.option('opt1').value.get() == ['val'] + with pytest.raises(ValueError): + await cfg.option('opt1').value.set(['val', 'val1']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt1').value.set(['val', 'val1']) + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -315,46 +324,47 @@ async def test_validator_warning(config_type): opt2 = StrOption('opt2', '', validators=[Calculation(return_false, Params(ParamSelfOption()), warnings_only=True)]) opt3 = StrOption('opt3', '', validators=[Calculation(return_if_val, Params(ParamSelfOption(whole=False)), warnings_only=True)], multi=True, properties=('notunique',)) root = OptionDescription('root', '', [opt1, opt2, opt3]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('opt1').value.get() == 'val' - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt1').value.set('val') - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - assert len(w) == 1 - if config_type != 'tiramisu-api': - assert w[0].message.opt() == opt2 - assert str(w[0].message) == msg_err.format('val', opt2._display_name, 'opt2') + ', ' + 'test error return_false' - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt3').value.set(['val']) - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt3').value.set(['val', 'val1']) - assert len(w) == 1 - if config_type != 'tiramisu-api': - assert w[0].message.opt() == opt3 - assert str(w[0].message) == msg_err.format('val1', opt3._display_name, 'opt3') + ', ' + 'test error' - # - with warnings.catch_warnings(record=True) as w: - with pytest.raises(ValueError): - await cfg.option('opt2').value.set(1) - assert len(w) == 0 - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - await cfg.option('opt3').value.set(['val', 'val1', 'val']) - assert len(w) == 2 - if config_type != 'tiramisu-api': - assert w[0].message.opt() == opt2 - assert str(w[0].message) == msg_err.format('val', opt2._display_name, 'opt2') + ', ' + 'test error return_false' - assert w[1].message.opt() == opt3 - assert str(w[1].message) == msg_err.format('val1', opt3._display_name, 'opt3') + ', ' + 'test error' + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('opt1').value.get() == 'val' + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt1').value.set('val') + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + assert len(w) == 1 + if config_type != 'tiramisu-api': + assert w[0].message.opt() == opt2 + assert str(w[0].message) == msg_err.format('val', opt2._display_name, 'opt2') + ', ' + 'test error return_false' + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt3').value.set(['val']) + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt3').value.set(['val', 'val1']) + assert len(w) == 1 + if config_type != 'tiramisu-api': + assert w[0].message.opt() == opt3 + assert str(w[0].message) == msg_err.format('val1', opt3._display_name, 'opt3') + ', ' + 'test error' + # + with warnings.catch_warnings(record=True) as w: + with pytest.raises(ValueError): + await cfg.option('opt2').value.set(1) + assert len(w) == 0 + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + await cfg.option('opt3').value.set(['val', 'val1', 'val']) + assert len(w) == 2 + if config_type != 'tiramisu-api': + assert w[0].message.opt() == opt2 + assert str(w[0].message) == msg_err.format('val', opt2._display_name, 'opt2') + ', ' + 'test error return_false' + assert w[1].message.opt() == opt3 + assert str(w[1].message) == msg_err.format('val1', opt3._display_name, 'opt3') + ', ' + 'test error' + assert not await list_sessions() @pytest.mark.asyncio @@ -363,43 +373,44 @@ async def test_validator_warning_disabled(config_type): opt2 = StrOption('opt2', '', validators=[Calculation(return_false, Params(ParamSelfOption()), warnings_only=True)]) opt3 = StrOption('opt3', '', validators=[Calculation(return_if_val, Params(ParamSelfOption(whole=False)), warnings_only=True)], multi=True, properties=('notunique',)) root = OptionDescription('root', '', [opt1, opt2, opt3]) - cfg_ori = await Config(root) - await cfg_ori.property.pop('warnings') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('opt1').value.get() == 'val' - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt1').value.set('val') - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt3').value.set(['val']) - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt3').value.set(['val', 'val1']) - assert w == [] - with pytest.raises(ValueError): - await cfg.option('opt2').value.set(1) - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('opt2').value.set('val') - await cfg.option('opt3').value.set(['val', 'val1', 'val']) - assert w == [] - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - if config_type != 'tiramisu-api': + async with await Config(root) as cfg_ori: + await cfg_ori.property.pop('warnings') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('opt1').value.get() == 'val' warnings.simplefilter("always", ValueWarning) with warnings.catch_warnings(record=True) as w: + await cfg.option('opt1').value.set('val') + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt3').value.set(['val']) + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt3').value.set(['val', 'val1']) + assert w == [] + with pytest.raises(ValueError): await cfg.option('opt2').value.set(1) - assert len(w) == 1 + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set('val') + await cfg.option('opt3').value.set(['val', 'val1', 'val']) + assert w == [] + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + if config_type != 'tiramisu-api': + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('opt2').value.set(1) + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -411,52 +422,53 @@ async def test_validator_warning_leadership(config_type): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) assert interface1.impl_get_group_type() == groups.leadership root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([None]) - assert w == [] - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') - assert len(w) == 1 - if config_type != 'tiramisu-api': - assert w[0].message.opt() == netmask_admin_eth0 - assert str(w[0].message) == msg_err.format('val1', netmask_admin_eth0._display_name, display_name_netmask) + ', test error' - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) - if config_type != 'tiramisu-api': - assert w[0].message.opt() == ip_admin_eth0 - assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' - else: - assert len(w) == 2 - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1', 'val1']) - if config_type != 'tiramisu-api': - assert w[0].message.opt() == ip_admin_eth0 - assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' - else: - assert len(w) == 3 - # - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val', 'val1']) - if config_type != 'tiramisu-api': - assert w[0].message.opt() == ip_admin_eth0 - assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' - else: - assert len(w) == 3 - # - warnings.resetwarnings() - with warnings.catch_warnings(record=True) as w: - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val1', 'val']) - if config_type != 'tiramisu-api': - assert w[0].message.opt() == ip_admin_eth0 - assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' - else: - assert len(w) == 3 + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([None]) + assert w == [] + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1') + assert len(w) == 1 + if config_type != 'tiramisu-api': + assert w[0].message.opt() == netmask_admin_eth0 + assert str(w[0].message) == msg_err.format('val1', netmask_admin_eth0._display_name, display_name_netmask) + ', test error' + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val']) + if config_type != 'tiramisu-api': + assert w[0].message.opt() == ip_admin_eth0 + assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' + else: + assert len(w) == 2 + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1', 'val1']) + if config_type != 'tiramisu-api': + assert w[0].message.opt() == ip_admin_eth0 + assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' + else: + assert len(w) == 3 + # + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val', 'val1']) + if config_type != 'tiramisu-api': + assert w[0].message.opt() == ip_admin_eth0 + assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' + else: + assert len(w) == 3 + # + warnings.resetwarnings() + with warnings.catch_warnings(record=True) as w: + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val1', 'val']) + if config_type != 'tiramisu-api': + assert w[0].message.opt() == ip_admin_eth0 + assert str(w[0].message) == msg_err.format('val', ip_admin_eth0._display_name, display_name_ip) + ', test error return_false' + else: + assert len(w) == 3 + assert not await list_sessions() @pytest.mark.asyncio @@ -468,13 +480,14 @@ async def test_validator_follower_param(config_type): validators=[Calculation(return_true, Params(ParamSelfOption(), kwargs={'param': ParamOption(ip_admin_eth0)}))]) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) root = OptionDescription('root', '', [interface1]) - cfg = await Config(root) - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes', 'yes']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val') + async with await Config(root) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes', 'yes']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val') + assert not await list_sessions() @pytest.mark.asyncio @@ -485,14 +498,15 @@ async def test_validator_dependencies(): validators=[Calculation(return_true, Params(ParamSelfOption(whole=False), kwargs={'param': ParamOption(ip_admin_eth0)}))]) opt2 = StrOption('opt2', '', validators=[Calculation(return_false, Params(ParamSelfOption(whole=False)))]) root = OptionDescription('root', '', [ip_admin_eth0, netmask_admin_eth0, opt2]) - cfg = await Config(root) - assert await cfg.option('ip_admin_eth0').option.has_dependency() is False - assert await cfg.option('netmask_admin_eth0').option.has_dependency() is True - assert await cfg.option('opt2').option.has_dependency() is False - # - assert await cfg.option('ip_admin_eth0').option.has_dependency(False) is True - assert await cfg.option('netmask_admin_eth0').option.has_dependency(False) is False - assert await cfg.option('opt2').option.has_dependency(False) is False + async with await Config(root) as cfg: + assert await cfg.option('ip_admin_eth0').option.has_dependency() is False + assert await cfg.option('netmask_admin_eth0').option.has_dependency() is True + assert await cfg.option('opt2').option.has_dependency() is False + # + assert await cfg.option('ip_admin_eth0').option.has_dependency(False) is True + assert await cfg.option('netmask_admin_eth0').option.has_dependency(False) is False + assert await cfg.option('opt2').option.has_dependency(False) is False + assert not await list_sessions() @pytest.mark.asyncio @@ -500,33 +514,34 @@ async def test_validator_ip_netmask(config_type): a = IPOption('a', '') b = NetmaskOption('b', '', validators=[Calculation(valid_ip_netmask, Params((ParamOption(a, todict=True), ParamSelfOption())))]) od = OptionDescription('od', '', [a, b]) - cfg_ori = await Config(od) - cfg = cfg_ori - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a').value.set('192.168.1.1') - await cfg.option('b').value.set('255.255.255.0') - await cfg.option('a').value.set('192.168.1.2') - await cfg.option('b').value.set('255.255.255.128') - await cfg.option('b').value.set('255.255.255.0') - await cfg.option('a').value.set('192.168.1.0') - with pytest.raises(ValueError): - await cfg.option('b').value.get() - await cfg.option('a').value.set('192.168.1.255') - with pytest.raises(ValueError): - await cfg.option('b').value.get() - await cfg.option('a').value.reset() - await cfg.option('b').value.reset() - await cfg.option('a').value.set('192.168.1.255') - with pytest.raises(ValueError): + async with await Config(od) as cfg_ori: + cfg = cfg_ori + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a').value.set('192.168.1.1') await cfg.option('b').value.set('255.255.255.0') - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: + await cfg.option('a').value.set('192.168.1.2') + await cfg.option('b').value.set('255.255.255.128') await cfg.option('b').value.set('255.255.255.0') - assert len(w) == 1 + await cfg.option('a').value.set('192.168.1.0') + with pytest.raises(ValueError): + await cfg.option('b').value.get() + await cfg.option('a').value.set('192.168.1.255') + with pytest.raises(ValueError): + await cfg.option('b').value.get() + await cfg.option('a').value.reset() + await cfg.option('b').value.reset() + await cfg.option('a').value.set('192.168.1.255') + with pytest.raises(ValueError): + await cfg.option('b').value.set('255.255.255.0') + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + await cfg.option('b').value.set('255.255.255.0') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -534,27 +549,28 @@ async def test_validator_network_netmask(config_type): a = NetworkOption('a', '') b = NetmaskOption('b', '', validators=[Calculation(valid_network_netmask, Params((ParamOption(a, todict=True), ParamSelfOption())))]) od = OptionDescription('od', '', [a, b]) - cfg_ori = await Config(od) - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a').value.set('192.168.1.1') - await cfg.option('b').value.set('255.255.255.255') - await cfg.option('b').value.reset() - await cfg.option('a').value.set('192.168.1.0') - await cfg.option('b').value.set('255.255.255.0') - await cfg.option('a').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('b').value.get() - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: + async with await Config(od) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) await cfg.option('a').value.set('192.168.1.1') - assert len(w) == 0 - with warnings.catch_warnings(record=True) as w: - await cfg.option('b').value.get() - assert len(w) == 1 + await cfg.option('b').value.set('255.255.255.255') + await cfg.option('b').value.reset() + await cfg.option('a').value.set('192.168.1.0') + await cfg.option('b').value.set('255.255.255.0') + await cfg.option('a').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('b').value.get() + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + await cfg.option('a').value.set('192.168.1.1') + assert len(w) == 0 + with warnings.catch_warnings(record=True) as w: + await cfg.option('b').value.get() + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -565,20 +581,21 @@ async def test_validator_ip_in_network(config_type): d = IPOption('d', '', validators=[Calculation(valid_in_network, Params((ParamSelfOption(), ParamOption(a, todict=True), ParamOption(b, todict=True))), warnings_only=True)]) od = OptionDescription('od', '', [a, b, c, d]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('192.168.1.0') - await cfg.option('b').value.set('255.255.255.0') - await cfg.option('c').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.2.1') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.0') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.255') - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set('192.168.2.1') - assert len(w) == 1 + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('192.168.1.0') + await cfg.option('b').value.set('255.255.255.0') + await cfg.option('c').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.2.1') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.0') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.255') + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.set('192.168.2.1') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -588,19 +605,20 @@ async def test_validator_ip_in_network_cidr(config_type): d = IPOption('d', '', validators=[Calculation(valid_in_network, Params((ParamSelfOption(), ParamOption(a, todict=True))), warnings_only=True)]) od = OptionDescription('od', '', [a, c, d]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set('192.168.1.0/24') - await cfg.option('c').value.set('192.168.1.1') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.2.1') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.0') - with pytest.raises(ValueError): - await cfg.option('c').value.set('192.168.1.255') - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set('192.168.2.1') - assert len(w) == 1 + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set('192.168.1.0/24') + await cfg.option('c').value.set('192.168.1.1') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.2.1') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.0') + with pytest.raises(ValueError): + await cfg.option('c').value.set('192.168.1.255') + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.set('192.168.2.1') + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -609,26 +627,27 @@ async def test_validator_ip_netmask_multi(config_type): b = NetmaskOption('b', '', multi=True, validators=[Calculation(valid_ip_netmask, Params((ParamOption(a, todict=True), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg_ori = await Config(od2) - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a.a').value.set(['192.168.1.1']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.2']) - await cfg.option('a.b', 0).value.set('255.255.255.128') - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.0']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() - # - await cfg.option('a.a').value.set(['192.168.1.2']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a.a').value.set(['192.168.1.0']) - with warnings.catch_warnings(record=True) as w: - await cfg.option('a.b', 0).value.get() - assert len(w) == 1 + async with await Config(od2) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a.a').value.set(['192.168.1.1']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.2']) + await cfg.option('a.b', 0).value.set('255.255.255.128') + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.0']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + # + await cfg.option('a.a').value.set(['192.168.1.2']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a.a').value.set(['192.168.1.0']) + with warnings.catch_warnings(record=True) as w: + await cfg.option('a.b', 0).value.get() + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -637,16 +656,17 @@ async def test_validator_network_netmask_multi(config_type): b = NetmaskOption('b', '', multi=True, validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - await cfg.option('a.a').value.set(['192.168.1.1']) - await cfg.option('a.b', 0).value.set('255.255.255.255') - await cfg.option('a.b', 0).value.reset() - await cfg.option('a.a').value.set(['192.168.1.0']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.1']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a.a').value.set(['192.168.1.1']) + await cfg.option('a.b', 0).value.set('255.255.255.255') + await cfg.option('a.b', 0).value.reset() + await cfg.option('a.a').value.set(['192.168.1.0']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.1']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -655,12 +675,13 @@ async def test_validator_network_netmask_multi_follower_default_multi(config_typ b = NetmaskOption('b', '', default_multi=u'255.255.255.0', multi=True, properties=('mandatory',), validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('a.a').value.set([undefined]) - assert await cfg.option('a.a').value.get() == ['192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + async with await Config(od2) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('a.a').value.set([undefined]) + assert await cfg.option('a.a').value.get() == ['192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + assert not await list_sessions() @pytest.mark.asyncio @@ -669,31 +690,32 @@ async def test_validator_network_netmask_multi_follower_default(config_type): b = NetmaskOption('b', '', default_multi=u'255.255.255.0', multi=True, properties=('mandatory',), validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg_ori = await Config(od2) - await cfg_ori.property.read_write() - await cfg_ori.property.pop('cache') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('a.a').value.get() == [] - await cfg.option('a.a').value.set(['192.168.1.0']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == u'255.255.255.0' - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.set([u'192.168.1.0']) - with pytest.raises(ValueError): - await cfg.option('a.b', 1).value.set([u'192.168.1.1']) - await cfg.option('a.a').value.set(['192.168.1.0', undefined]) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.b', 1).value.set('255.255.255.255') - await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) + async with await Config(od2) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.property.pop('cache') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('a.a').value.get() == [] + await cfg.option('a.a').value.set(['192.168.1.0']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == u'255.255.255.0' + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.set([u'192.168.1.0']) + with pytest.raises(ValueError): + await cfg.option('a.b', 1).value.set([u'192.168.1.1']) + await cfg.option('a.a').value.set(['192.168.1.0', undefined]) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.b', 1).value.set('255.255.255.255') + await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) + assert not await list_sessions() def return_netmask(*args, **kwargs): @@ -715,30 +737,31 @@ async def test_validator_network_netmask_multi_follower_callback(config_type): b = NetmaskOption('b', '', Calculation(return_netmask, Params(kwargs={'index': ParamIndex()})), multi=True, properties=('mandatory',), validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg_ori = await Config(od2) - await cfg_ori.property.read_write() - await cfg_ori.property.pop('cache') - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('a.a').value.get() == [] - await cfg.option('a.a').value.set(['192.168.1.0']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_only() - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) - await cfg.option('a.b', 0).value.get() - with pytest.raises(ValueError): - await cfg.option('a.b', 1).value.get() - await cfg.option('a.a').value.set(['192.168.1.0', undefined]) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.b', 1).value.set('255.255.255.255') - await cfg.option('a.a').value.set(['192.168.1.0', '192.168.1.1']) + async with await Config(od2) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.property.pop('cache') + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('a.a').value.get() == [] + await cfg.option('a.a').value.set(['192.168.1.0']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_only() + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1']) + await cfg.option('a.b', 0).value.get() + with pytest.raises(ValueError): + await cfg.option('a.b', 1).value.get() + await cfg.option('a.a').value.set(['192.168.1.0', undefined]) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.b', 1).value.set('255.255.255.255') + await cfg.option('a.a').value.set(['192.168.1.0', '192.168.1.1']) + assert not await list_sessions() @pytest.mark.asyncio @@ -747,32 +770,33 @@ async def test_validator_network_netmask_multi_follower_callback_value(config_ty b = NetmaskOption('b', '', Calculation(return_netmask2, Params(ParamOption(a))), multi=True, properties=('mandatory',), validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - await cfg.property.read_write() - await cfg.property.pop('cache') - cfg = await get_config(cfg, config_type) - assert await cfg.option('a.a').value.get() == [] - await cfg.option('a.a').value.set(['192.168.1.0']) - assert await cfg.option('a.a').value.get() == ['192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' - await cfg.option('a.a').value.set(['192.168.1.0', '192.168.2.1']) - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' - with pytest.raises(ValueError): - await cfg.option('a.b', 1).value.get() - await cfg.option('a.a').value.pop(1) - # - assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' - await cfg.option('a.a').value.set(['192.168.2.1']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() - await cfg.option('a.a').value.set(['192.168.1.0']) - # - assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] - assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' - await cfg.option('a.a').value.set(['192.168.1.0', '192.168.1.1']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.b', 1).value.set('255.255.255.255') + async with await Config(od2) as cfg: + await cfg.property.read_write() + await cfg.property.pop('cache') + cfg = await get_config(cfg, config_type) + assert await cfg.option('a.a').value.get() == [] + await cfg.option('a.a').value.set(['192.168.1.0']) + assert await cfg.option('a.a').value.get() == ['192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + await cfg.option('a.a').value.set(['192.168.1.0', '192.168.2.1']) + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + with pytest.raises(ValueError): + await cfg.option('a.b', 1).value.get() + await cfg.option('a.a').value.pop(1) + # + assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + await cfg.option('a.a').value.set(['192.168.2.1']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + await cfg.option('a.a').value.set(['192.168.1.0']) + # + assert await cfg.option('a.a').value.get() == [u'192.168.1.0'] + assert await cfg.option('a.b', 0).value.get() == '255.255.255.0' + await cfg.option('a.a').value.set(['192.168.1.0', '192.168.1.1']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.b', 1).value.set('255.255.255.255') + assert not await list_sessions() @pytest.mark.asyncio @@ -781,20 +805,21 @@ async def test_validator_ip_netmask_multi_leader(config_type): b = NetmaskOption('b', '', multi=True, validators=[Calculation(valid_ip_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - await cfg.option('a.a').value.set(['192.168.1.1']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.2']) - await cfg.option('a.b', 0).value.set('255.255.255.128') - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.0']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() - await cfg.option('a.a').value.set(['192.168.1.128']) - with pytest.raises(ValueError): + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a.a').value.set(['192.168.1.1']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.2']) await cfg.option('a.b', 0).value.set('255.255.255.128') - await cfg.option('a.a').value.set(['192.168.1.2', '192.168.1.3']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.0']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + await cfg.option('a.a').value.set(['192.168.1.128']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.set('255.255.255.128') + await cfg.option('a.a').value.set(['192.168.1.2', '192.168.1.3']) + assert not await list_sessions() @pytest.mark.asyncio @@ -803,16 +828,17 @@ async def test_validator_network_netmask_multi_leader(config_type): b = NetmaskOption('b', '', multi=True, validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - await cfg.option('a.a').value.set(['192.168.1.1']) - await cfg.option('a.b', 0).value.set('255.255.255.255') - await cfg.option('a.b', 0).value.reset() - await cfg.option('a.a').value.set(['192.168.1.0']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.a').value.set(['192.168.1.1']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a.a').value.set(['192.168.1.1']) + await cfg.option('a.b', 0).value.set('255.255.255.255') + await cfg.option('a.b', 0).value.reset() + await cfg.option('a.a').value.set(['192.168.1.0']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.a').value.set(['192.168.1.1']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -822,30 +848,31 @@ async def test_validator_broadcast(config_type): c = BroadcastOption('c', '', multi=True, validators=[Calculation(valid_broadcast, Params((ParamOption(a), ParamOption(b), ParamSelfOption())))]) od = Leadership('a', '', [a, b, c]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - #first, test network_netmask - await cfg.option('a.a').value.set(['192.168.1.128']) - with pytest.raises(ValueError): - await cfg.option('a.a').value.set(['255.255.255.0']) - # - await cfg.option('a.a').value.set(['192.168.1.0']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.c', 0).value.set('192.168.1.255') - await cfg.option('a.a').value.set(['192.168.1.1']) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() - with pytest.raises(ValueError): - await cfg.option('a.c', 0).value.get() - # - await cfg.option('a.a').value.set(['192.168.1.0', '192.168.2.128']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.b', 1).value.set('255.255.255.128') - await cfg.option('a.c', 0).value.set('192.168.1.255') - await cfg.option('a.c', 1).value.set('192.168.2.255') - with pytest.raises(ValueError): - await cfg.option('a.c', 1).value.set('192.168.2.128') - await cfg.option('a.c', 1).value.set('192.168.2.255') + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + #first, test network_netmask + await cfg.option('a.a').value.set(['192.168.1.128']) + with pytest.raises(ValueError): + await cfg.option('a.a').value.set(['255.255.255.0']) + # + await cfg.option('a.a').value.set(['192.168.1.0']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.c', 0).value.set('192.168.1.255') + await cfg.option('a.a').value.set(['192.168.1.1']) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + with pytest.raises(ValueError): + await cfg.option('a.c', 0).value.get() + # + await cfg.option('a.a').value.set(['192.168.1.0', '192.168.2.128']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.b', 1).value.set('255.255.255.128') + await cfg.option('a.c', 0).value.set('192.168.1.255') + await cfg.option('a.c', 1).value.set('192.168.2.255') + with pytest.raises(ValueError): + await cfg.option('a.c', 1).value.set('192.168.2.128') + await cfg.option('a.c', 1).value.set('192.168.2.255') + assert not await list_sessions() @pytest.mark.asyncio @@ -854,19 +881,20 @@ async def test_validator_broadcast_warnings(config_type): a = NetworkOption('a', '', properties=('mandatory', 'disabled')) b = NetmaskOption('b', '', properties=('mandatory', 'disabled'), validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())), warnings_only=True)]) od = OptionDescription('a', '', [a, b]) - cfg_ori = await Config(od) - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: - await cfg.option('a').value.set('192.168.1.4') - await cfg.option('b').value.set('255.255.255.0') - assert len(w) == 1 - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: - list(await cfg.value.mandatory()) - assert len(w) == 0 + async with await Config(od) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + await cfg.option('a').value.set('192.168.1.4') + await cfg.option('b').value.set('255.255.255.0') + assert len(w) == 1 + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + list(await cfg.value.mandatory()) + assert len(w) == 0 + assert not await list_sessions() @pytest.mark.asyncio @@ -875,9 +903,10 @@ async def test_validator_broadcast_default_1(): b = NetmaskOption('b', '', '255.255.255.128') c = BroadcastOption('c', '', '192.168.2.127', validators=[Calculation(valid_broadcast, Params((ParamOption(a), ParamOption(b), ParamSelfOption())))]) od = OptionDescription('a', '', [a, b, c]) - cfg = await Config(od) - with pytest.raises(ValueError): - await cfg.value.dict() + async with await Config(od) as cfg: + with pytest.raises(ValueError): + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -886,8 +915,9 @@ async def test_validator_broadcast_default_2(): b = NetmaskOption('b', '', '255.255.255.128') d = BroadcastOption('d', '', '192.168.1.127', validators=[Calculation(valid_broadcast, Params((ParamOption(a), ParamOption(b), ParamSelfOption())))]) od = OptionDescription('a', '', [a, b, d]) - cfg = await Config(od) - assert await cfg.value.dict() + async with await Config(od) as cfg: + assert await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -897,11 +927,12 @@ async def test_validator_not_all(config_type): c = BroadcastOption('c', '', multi=True) od = Leadership('a', '', [a, b, c]) od = OptionDescription('od2', '', [od]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a.a').value.set(['192.168.1.0']) - await cfg.option('a.b', 0).value.set('255.255.255.0') - await cfg.option('a.c', 0).value.set('192.168.1.255') + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a.a').value.set(['192.168.1.0']) + await cfg.option('a.b', 0).value.set('255.255.255.0') + await cfg.option('a.c', 0).value.set('192.168.1.255') + assert not await list_sessions() @pytest.mark.asyncio @@ -910,10 +941,11 @@ async def test_validator_network_netmask_mandatory(config_type): b = NetmaskOption('b', '', multi=True, properties=('mandatory',), default_multi=u'0.0.0.0', validators=[Calculation(valid_network_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('od2', '', [od]) - cfg = await Config(od2) - await cfg.property.read_only() - cfg = await get_config(cfg, config_type) - await cfg.value.dict() + async with await Config(od2) as cfg: + await cfg.property.read_only() + cfg = await get_config(cfg, config_type) + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -921,11 +953,12 @@ async def test_validator_has_dependency(): a = IPOption('a', '') b = NetmaskOption('b', '', validators=[Calculation(valid_ip_netmask, Params((ParamOption(a), ParamSelfOption())))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - assert await cfg.option('a').option.has_dependency() is False - assert await cfg.option('b').option.has_dependency() is True - assert await cfg.option('a').option.has_dependency(False) is True - assert await cfg.option('b').option.has_dependency(False) is False + async with await Config(od) as cfg: + assert await cfg.option('a').option.has_dependency() is False + assert await cfg.option('b').option.has_dependency() is True + assert await cfg.option('a').option.has_dependency(False) is True + assert await cfg.option('b').option.has_dependency(False) is False + assert not await list_sessions() @pytest.mark.asyncio @@ -934,18 +967,19 @@ async def test_validator_warnings_only_more_option(config_type): b = IntOption('b', '') d = IntOption('d', '', validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True), ParamOption(b, todict=True))), warnings_only=True)]) od = OptionDescription('od', '', [a, b, d]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - await cfg.option('a').value.set(1) - await cfg.option('b').value.set(1) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.get() - assert w == [] - with warnings.catch_warnings(record=True) as w: - await cfg.option('d').value.set(1) - assert w != [] - assert len(w) == 1 + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + await cfg.option('a').value.set(1) + await cfg.option('b').value.set(1) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.get() + assert w == [] + with warnings.catch_warnings(record=True) as w: + await cfg.option('d').value.set(1) + assert w != [] + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -953,17 +987,18 @@ async def test_validator_error_prefix(): a = IntOption('a', '') b = IntOption('b', '', validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - await cfg.option('a').value.set(1) - try: - await cfg.option('b').value.set(1) - except Exception as err: - assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('1', _('integer'), 'b') + ', ' + _('value is identical to {}').format('"a"') - try: - await cfg.option('b').value.set(1) - except Exception as err: - err.prefix = '' - assert str(err) == _('value is identical to {}').format('"a"') + async with await Config(od) as cfg: + await cfg.option('a').value.set(1) + try: + await cfg.option('b').value.set(1) + except Exception as err: + assert str(err) == _('"{0}" is an invalid {1} for "{2}"').format('1', _('integer'), 'b') + ', ' + _('value is identical to {}').format('"a"') + try: + await cfg.option('b').value.set(1) + except Exception as err: + err.prefix = '' + assert str(err) == _('value is identical to {}').format('"a"') + assert not await list_sessions() @pytest.mark.asyncio @@ -971,11 +1006,12 @@ async def test_validator_warnings_only_option(config_type): a = IntOption('a', '') b = IntOption('b', '', warnings_only=True, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True))))]) od = OptionDescription('od', '', [a, b]) - cfg_ori = await Config(od) - cfg = await get_config(cfg_ori, config_type) - await cfg.option('a').value.set(1) - with pytest.raises(ValueError): - await cfg.option('b').value.set(1) + async with await Config(od) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + await cfg.option('a').value.set(1) + with pytest.raises(ValueError): + await cfg.option('b').value.set(1) + assert not await list_sessions() @pytest.mark.asyncio @@ -983,25 +1019,26 @@ async def test_validator_not_equal(config_type): a = IntOption('a', '') b = IntOption('b', '', validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a))))]) od = OptionDescription('od', '', [a, b]) - cfg_ori = await Config(od) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('a').value.get() is None - assert await cfg.option('b').value.get() is None - await cfg.option('a').value.set(1) - await cfg.option('a').value.reset() - await cfg.option('a').value.set(1) - with pytest.raises(ValueError): - await cfg.option('b').value.set(1) - await cfg.option('b').value.set(2) - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('demoting_error_warning') - cfg = await get_config(cfg_ori, config_type) - warnings.simplefilter("always", ValueWarning) - with warnings.catch_warnings(record=True) as w: - await cfg.option('b').value.set(1) - assert len(w) == 1 + async with await Config(od) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('a').value.get() is None + assert await cfg.option('b').value.get() is None + await cfg.option('a').value.set(1) + await cfg.option('a').value.reset() + await cfg.option('a').value.set(1) + with pytest.raises(ValueError): + await cfg.option('b').value.set(1) + await cfg.option('b').value.set(2) + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('demoting_error_warning') + cfg = await get_config(cfg_ori, config_type) + warnings.simplefilter("always", ValueWarning) + with warnings.catch_warnings(record=True) as w: + await cfg.option('b').value.set(1) + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -1010,18 +1047,19 @@ async def test_validator_not_equal_leadership(config_type): b = IntOption('b', '', multi=True, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a))))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('b', '', [od]) - cfg = await Config(od2) - cfg = await get_config(cfg, config_type) - assert await cfg.option('a.a').value.get() == [] - await cfg.option('a.a').value.set([1]) - await cfg.option('a.a').value.reset() - await cfg.option('a.a').value.set([1]) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.set(1) - await cfg.option('a.b', 0).value.set(2) - await cfg.option('a.a').value.reset() - await cfg.option('a.a').value.set([1]) - await cfg.value.dict() + async with await Config(od2) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('a.a').value.get() == [] + await cfg.option('a.a').value.set([1]) + await cfg.option('a.a').value.reset() + await cfg.option('a.a').value.set([1]) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.set(1) + await cfg.option('a.b', 0).value.set(2) + await cfg.option('a.a').value.reset() + await cfg.option('a.a').value.set([1]) + await cfg.value.dict() + assert not await list_sessions() @pytest.mark.asyncio @@ -1030,20 +1068,21 @@ async def test_validator_not_equal_leadership_default(): b = IntOption('b', '', multi=True, default_multi=1, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a))))]) od = Leadership('a', '', [a, b]) od2 = OptionDescription('a', '', [od]) - cfg = await Config(od2) - # FIXME cfg = await get_config(cfg, config_type) - assert await cfg.option('a.a').value.get() == [] - await cfg.option('a.a').value.set([1]) - with pytest.raises(ValueError): - await cfg.option('a.b', 0).value.get() - await cfg.option('a.a').value.set([2]) - await cfg.option('a.a').value.reset() - await cfg.option('a.a').value.set([2]) - # - await cfg.property.add('demoting_error_warning') - with warnings.catch_warnings(record=True) as w: - await cfg.option('a.b', 0).value.set(2) - assert len(w) == 1 + async with await Config(od2) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + assert await cfg.option('a.a').value.get() == [] + await cfg.option('a.a').value.set([1]) + with pytest.raises(ValueError): + await cfg.option('a.b', 0).value.get() + await cfg.option('a.a').value.set([2]) + await cfg.option('a.a').value.reset() + await cfg.option('a.a').value.set([2]) + # + await cfg.property.add('demoting_error_warning') + with warnings.catch_warnings(record=True) as w: + await cfg.option('a.b', 0).value.set(2) + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -1051,20 +1090,21 @@ async def test_validator_default_diff(): a = IntOption('a', '', 3) b = IntOption('b', '', 1, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - # FIXME cfg = await get_config(cfg, config_type) - await cfg.option('b').value.set(2) - await cfg.option('a').value.set(1) - owner = await cfg.owner.get() - assert await cfg.option('b').owner.get() == owner - with pytest.raises(ValueError): - await cfg.option('b').value.reset() - assert await cfg.option('b').owner.get() == owner - # - await cfg.property.add('demoting_error_warning') - with warnings.catch_warnings(record=True) as w: - await cfg.option('b').value.reset() - assert len(w) == 1 + async with await Config(od) as cfg: + # FIXME cfg = await get_config(cfg, config_type) + await cfg.option('b').value.set(2) + await cfg.option('a').value.set(1) + owner = await cfg.owner.get() + assert await cfg.option('b').owner.get() == owner + with pytest.raises(ValueError): + await cfg.option('b').value.reset() + assert await cfg.option('b').owner.get() == owner + # + await cfg.property.add('demoting_error_warning') + with warnings.catch_warnings(record=True) as w: + await cfg.option('b').value.reset() + assert len(w) == 1 + assert not await list_sessions() @pytest.mark.asyncio @@ -1072,13 +1112,14 @@ async def test_validator_permissive(config_type): a = IntOption('a', '', 1, properties=('hidden',)) b = IntOption('b', '', 2, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - await cfg.permissive.add('hidden') - cfg = await get_config(cfg, config_type) - with pytest.raises(ValueError): - await cfg.option('b').value.set(1) - await cfg.option('b').value.set(2) + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.permissive.add('hidden') + cfg = await get_config(cfg, config_type) + with pytest.raises(ValueError): + await cfg.option('b').value.set(1) + await cfg.option('b').value.set(2) + assert not await list_sessions() @pytest.mark.asyncio @@ -1086,11 +1127,12 @@ async def test_validator_disabled(config_type): a = IntOption('a', '', 1, properties=('disabled',)) b = IntOption('b', '', 2, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True, raisepropertyerror=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('b').value.set(1) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('b').value.set(1) + assert not await list_sessions() @pytest.mark.asyncio @@ -1098,10 +1140,11 @@ async def test_consistency_disabled_transitive(config_type): a = IntOption('a', '', 1, properties=('disabled',)) b = IntOption('b', '', 2, validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True, notraisepropertyerror=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('b').value.set(1) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('b').value.set(1) + assert not await list_sessions() @pytest.mark.asyncio @@ -1112,29 +1155,30 @@ async def test_consistency_double_warnings(config_type): od = OptionDescription('od', '', [a, b, c]) warnings.simplefilter("always", ValueWarning) od2 = OptionDescription('od2', '', [od]) - cfg_ori = await Config(od2) - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: - await cfg.option('od.c').value.set(1) - assert w != [] - if config_type == 'tiramisu-api': - # in this case warnings is for '"a" and "b"' + async with await Config(od2) as cfg_ori: + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + await cfg.option('od.c').value.set(1) + assert w != [] + if config_type == 'tiramisu-api': + # in this case warnings is for '"a" and "b"' + assert len(w) == 1 + else: + # in this cas one warnings is for "a" and the second for "b" + assert len(w) == 2 + await cfg.option('od.a').value.set(2) + with warnings.catch_warnings(record=True) as w: + await cfg.option('od.c').value.get() assert len(w) == 1 - else: - # in this cas one warnings is for "a" and the second for "b" - assert len(w) == 2 - await cfg.option('od.a').value.set(2) - with warnings.catch_warnings(record=True) as w: - await cfg.option('od.c').value.get() - assert len(w) == 1 - # - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.pop('warnings') - cfg = await get_config(cfg_ori, config_type) - with warnings.catch_warnings(record=True) as w: - await cfg.option('od.c').value.set(1) - assert w == [] + # + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.pop('warnings') + cfg = await get_config(cfg_ori, config_type) + with warnings.catch_warnings(record=True) as w: + await cfg.option('od.c').value.set(1) + assert w == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -1147,12 +1191,13 @@ async def test_consistency_warnings_error(config_type): ]) od = OptionDescription('od', '', [a, b, c]) warnings.simplefilter("always", ValueWarning) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - with warnings.catch_warnings(record=True) as w: - with pytest.raises(ValueError): - await cfg.option('c').value.set(1) - assert w == [] + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + with warnings.catch_warnings(record=True) as w: + with pytest.raises(ValueError): + await cfg.option('c').value.set(1) + assert w == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -1161,8 +1206,9 @@ async def test_consistency_not_equal_has_dependency(): b = IntOption('b', '', ) b = IntOption('b', '', validators=[Calculation(valid_not_equal, Params((ParamSelfOption(), ParamOption(a, todict=True))))]) od = OptionDescription('od', '', [a, b]) - cfg = await Config(od) - assert await cfg.option('a').option.has_dependency() is False - assert await cfg.option('b').option.has_dependency() is True - assert await cfg.option('a').option.has_dependency(False) is True - assert await cfg.option('b').option.has_dependency(False) is False + async with await Config(od) as cfg: + assert await cfg.option('a').option.has_dependency() is False + assert await cfg.option('b').option.has_dependency() is True + assert await cfg.option('a').option.has_dependency(False) is True + assert await cfg.option('b').option.has_dependency(False) is False + assert not await list_sessions() diff --git a/tests/test_option_with_special_name.py b/tests/test_option_with_special_name.py index 9fe867e..d320905 100644 --- a/tests/test_option_with_special_name.py +++ b/tests/test_option_with_special_name.py @@ -1,16 +1,12 @@ #this test is much more to test that **it's there** and answers attribute access from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest from tiramisu import BoolOption, OptionDescription, ChoiceOption,\ IntOption, FloatOption, StrOption, Config from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop def make_description(): @@ -42,13 +38,14 @@ async def test_root_config_answers_ok(config_type): gcdummy = BoolOption('dummy', 'dummy', default=False) boolop = BoolOption('boolop', 'Test boolean option op', default=True) descr = OptionDescription('tiramisu', '', [gcdummy, boolop]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - #settings = await cfg.cfgimpl_get_settings() - #settings.append('hidden') + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + #settings = await cfg.cfgimpl_get_settings() + #settings.append('hidden') - assert await cfg.option('dummy').value.get() is False - assert await cfg.option('boolop').value.get() is True + assert await cfg.option('dummy').value.get() is False + assert await cfg.option('boolop').value.get() is True + assert not await list_sessions() #@pytest.mark.asyncio @@ -61,7 +58,8 @@ async def test_root_config_answers_ok(config_type): async def test_option_has_an_api_name(config_type): b = BoolOption('impl_has_dependency', 'dummy', default=True) descr = OptionDescription('tiramisu', '', [b]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('impl_has_dependency').value.get() is True - assert b.impl_has_dependency() is False + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('impl_has_dependency').value.get() is True + assert b.impl_has_dependency() is False + assert not await list_sessions() diff --git a/tests/test_permissive.py b/tests/test_permissive.py index 5b55d55..bcf7b46 100644 --- a/tests/test_permissive.py +++ b/tests/test_permissive.py @@ -1,17 +1,13 @@ # coding: utf-8 from .autopath import do_autopath do_autopath() -from .config import config_type, get_config import pytest from tiramisu import IntOption, StrOption, OptionDescription, Config from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.storage import list_sessions, delete_session - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop def make_description(): @@ -23,410 +19,425 @@ def make_description(): @pytest.mark.asyncio async def test_permissive(config_type): descr = make_description() - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.permissive.add('disabled') + await cfg_ori.unrestraint.permissive.pop('hidden') + assert await cfg_ori.unrestraint.permissive.get() == frozenset(['disabled']) + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('permissive') + cfg = await get_config(cfg_ori, config_type) await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.permissive.add('disabled') - await cfg_ori.unrestraint.permissive.pop('hidden') - assert await cfg_ori.unrestraint.permissive.get() == frozenset(['disabled']) - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('permissive') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('u1').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.pop('permissive') - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.pop('permissive') + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_add(config_type): descr = make_description() - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.permissive.add('disabled') + assert await cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('permissive') + cfg = await get_config(cfg_ori, config_type) await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.permissive.add('disabled') - assert await cfg_ori.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('permissive') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('u1').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.pop('permissive') - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.pop('permissive') + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_pop(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.property.read_write() - props = frozenset() - try: + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.property.read_write() + props = frozenset() + try: + await cfg.forcepermissive.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + await cfg.unrestraint.permissive.add('disabled') + assert await cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) await cfg.forcepermissive.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - await cfg.unrestraint.permissive.add('disabled') - assert await cfg.unrestraint.permissive.get() == frozenset(['hidden', 'disabled']) - await cfg.forcepermissive.option('u1').value.get() - await cfg.unrestraint.permissive.pop('disabled') - props = frozenset() - try: - await cfg.forcepermissive.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + await cfg.unrestraint.permissive.pop('disabled') + props = frozenset() + try: + await cfg.forcepermissive.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_reset(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - assert await cfg.unrestraint.permissive.get() == frozenset(['hidden']) - # - await cfg.unrestraint.permissive.add('disabled') - await cfg.unrestraint.permissive.pop('hidden') - assert await cfg.unrestraint.permissive.get() == frozenset(['disabled']) - # - await cfg.unrestraint.permissive.reset() - assert await cfg.unrestraint.permissive.get() == frozenset() + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert await cfg.unrestraint.permissive.get() == frozenset(['hidden']) + # + await cfg.unrestraint.permissive.add('disabled') + await cfg.unrestraint.permissive.pop('hidden') + assert await cfg.unrestraint.permissive.get() == frozenset(['disabled']) + # + await cfg.unrestraint.permissive.reset() + assert await cfg.unrestraint.permissive.get() == frozenset() + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_mandatory(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - props = frozenset() - try: + async with await Config(descr) as cfg: + await cfg.property.read_only() + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.unrestraint.permissive.add('mandatory') + await cfg.unrestraint.permissive.add('disabled') + assert await cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled']) + await cfg.property.add('permissive') await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.unrestraint.permissive.add('mandatory') - await cfg.unrestraint.permissive.add('disabled') - assert await cfg.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled']) - await cfg.property.add('permissive') - await cfg.option('u1').value.get() - await cfg.property.pop('permissive') - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.property.pop('permissive') + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_frozen(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.unrestraint.permissive.pop('hidden') - await cfg.unrestraint.permissive.add('frozen') - await cfg.unrestraint.permissive.add('disabled') - assert await cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled']) - assert await cfg.permissive.get() == frozenset(['frozen', 'disabled']) - try: + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.unrestraint.permissive.pop('hidden') + await cfg.unrestraint.permissive.add('frozen') + await cfg.unrestraint.permissive.add('disabled') + assert await cfg.unrestraint.permissive.get() == frozenset(['frozen', 'disabled']) + assert await cfg.permissive.get() == frozenset(['frozen', 'disabled']) + try: + await cfg.option('u1').value.set(1) + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.property.add('permissive') await cfg.option('u1').value.set(1) - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.property.add('permissive') - await cfg.option('u1').value.set(1) - assert await cfg.option('u1').value.get() == 1 - await cfg.property.pop('permissive') - try: - await cfg.option('u1').value.set(1) - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + assert await cfg.option('u1').value.get() == 1 + await cfg.property.pop('permissive') + try: + await cfg.option('u1').value.set(1) + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio async def test_invalid_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - # FIXME with pytest.raises(TypeError): - # await cfg.unrestraint.permissive.set(['frozen', 'disabled'])") + async with await Config(descr) as cfg: + await cfg.property.read_write() + # FIXME with pytest.raises(TypeError): + # await cfg.unrestraint.permissive.set(['frozen', 'disabled'])") + assert not await list_sessions() @pytest.mark.asyncio async def test_forbidden_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - with pytest.raises(ConfigError): - await cfg.permissive.add('force_default_on_freeze') - with pytest.raises(ConfigError): - await cfg.permissive.add('force_metaconfig_on_freeze') + async with await Config(descr) as cfg: + await cfg.property.read_write() + with pytest.raises(ConfigError): + await cfg.permissive.add('force_default_on_freeze') + with pytest.raises(ConfigError): + await cfg.permissive.add('force_metaconfig_on_freeze') + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_option(config_type): descr = make_description() - cfg_ori = await Config(descr) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset() + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.add('permissive') + cfg = await get_config(cfg_ori, config_type) await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.add('permissive') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('u1').value.get() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.property.pop('permissive') - cfg = await get_config(cfg_ori, config_type) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.property.pop('permissive') + cfg = await get_config(cfg_ori, config_type) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset() + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_option_cache(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() + async with await Config(descr) as cfg: + await cfg.property.read_write() - props = frozenset() - try: + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + + await cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset() + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + + await cfg.property.add('permissive') await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} - await cfg.unrestraint.option('u1').permissive.set(frozenset(['disabled'])) - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - - await cfg.property.add('permissive') - await cfg.option('u1').value.get() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} - - await cfg.property.pop('permissive') - props = frozenset() - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset() - props = frozenset() - try: - await cfg.option('u2').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert set(props) == {'disabled'} + await cfg.property.pop('permissive') + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset() + props = frozenset() + try: + await cfg.option('u2').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_option_mandatory(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_only() - props = frozenset() - try: + async with await Config(descr) as cfg: + await cfg.property.read_only() + props = frozenset() + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled'])) + assert await cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled']) + await cfg.property.add('permissive') await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled'])) - assert await cfg.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled']) - await cfg.property.add('permissive') - await cfg.option('u1').value.get() - await cfg.property.pop('permissive') - try: - await cfg.option('u1').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.property.pop('permissive') + try: + await cfg.option('u1').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio async def test_permissive_option_frozen(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.unrestraint.option('u1').permissive.set(frozenset(['frozen', 'disabled'])) - await cfg.option('u1').value.set(1) - assert await cfg.option('u1').value.get() == 1 - await cfg.property.add('permissive') - assert await cfg.option('u1').value.get() == 1 - await cfg.property.pop('permissive') - assert await cfg.option('u1').value.get() == 1 + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.unrestraint.option('u1').permissive.set(frozenset(['frozen', 'disabled'])) + await cfg.option('u1').value.set(1) + assert await cfg.option('u1').value.get() == 1 + await cfg.property.add('permissive') + assert await cfg.option('u1').value.get() == 1 + await cfg.property.pop('permissive') + assert await cfg.option('u1').value.get() == 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_invalid_option_permissive(): descr = make_description() - cfg = await Config(descr) - await cfg.property.read_write() - with pytest.raises(TypeError): - await cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled']) + async with await Config(descr) as cfg: + await cfg.property.read_write() + with pytest.raises(TypeError): + await cfg.unrestraint.option('u1').permissive.set(['frozen', 'disabled']) + assert not await list_sessions() @pytest.mark.asyncio async def test_remove_option_permissive(config_type): var1 = StrOption('var1', '', u'value', properties=('hidden',)) od1 = OptionDescription('od1', '', [var1]) - rootod = OptionDescription('rootod', '', [od1]) - cfg_ori = await Config(rootod) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.var1').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) - assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('od1.var1').value.get() == 'value' - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset()) - assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.var1').value.get() + descr = OptionDescription('rootod', '', [od1]) + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.var1').value.get() + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) + assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('od1.var1').value.get() == 'value' + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset()) + assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.var1').value.get() + assert not await list_sessions() @pytest.mark.asyncio async def test_reset_option_permissive(config_type): var1 = StrOption('var1', '', u'value', properties=('hidden',)) od1 = OptionDescription('od1', '', [var1]) - rootod = OptionDescription('rootod', '', [od1]) - cfg_ori = await Config(rootod) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.var1').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) - assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) - cfg = await get_config(cfg_ori, config_type) - assert await cfg.option('od1.var1').value.get() == 'value' - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.forcepermissive.option('od1.var1').permissive.reset() - assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() - cfg = await get_config(cfg_ori, config_type) - with pytest.raises(PropertiesOptionError): - await cfg.option('od1.var1').value.get() + descr = OptionDescription('rootod', '', [od1]) + async with await Config(descr) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.var1').value.get() + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden'])) + assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden']) + cfg = await get_config(cfg_ori, config_type) + assert await cfg.option('od1.var1').value.get() == 'value' + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.forcepermissive.option('od1.var1').permissive.reset() + assert await cfg_ori.forcepermissive.option('od1.var1').permissive.get() == frozenset() + cfg = await get_config(cfg_ori, config_type) + with pytest.raises(PropertiesOptionError): + await cfg.option('od1.var1').value.get() + assert not await list_sessions() diff --git a/tests/test_requires.py b/tests/test_requires.py index bd9426c..47aa8b8 100644 --- a/tests/test_requires.py +++ b/tests/test_requires.py @@ -1,9 +1,9 @@ # coding: utf-8 from .autopath import do_autopath do_autopath() -from .config import config_type, get_config from copy import copy +from os import environ from tiramisu.i18n import _ from tiramisu.setting import groups from tiramisu import setting @@ -14,10 +14,7 @@ from tiramisu import IPOption, OptionDescription, BoolOption, IntOption, StrOpti from tiramisu.error import PropertiesOptionError, ConfigError, display_list import pytest from tiramisu.storage import list_sessions, delete_session - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import config_type, get_config, event_loop @pytest.mark.asyncio @@ -25,35 +22,36 @@ async def test_properties(config_type): a = BoolOption('activate_service', '', True) b = IPOption('ip_address_service', '', properties=('disabled',)) od = OptionDescription('service', '', [a, b]) - cfg_ori = await Config(od) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - props = [] - try: + async with await Config(od) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') + cfg = await get_config(cfg_ori, config_type) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') - cfg = await get_config(cfg_ori, config_type) - await cfg.option('ip_address_service').value.get() - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_address_service').property.add('disabled') - cfg = await get_config(cfg_ori, config_type) - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # pop twice - if config_type == 'tiramisu-api': - await cfg.send() - await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') - await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_address_service').property.add('disabled') + cfg = await get_config(cfg_ori, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # pop twice + if config_type == 'tiramisu-api': + await cfg.send() + await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') + await cfg_ori.unrestraint.option('ip_address_service').property.pop('disabled') + assert not await list_sessions() @pytest.mark.asyncio @@ -66,19 +64,20 @@ async def test_requires(config_type): b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set(False) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set(True) - await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(False) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(True) + await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -91,124 +90,131 @@ async def test_requires_inverse(config_type): 'reverse_condition': ParamValue(True)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(False) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set(False) - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set(True) - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(True) + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_requires_self(config_type): -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamSelfOption(), -# FIXME 'expected': ParamValue('b')})) -# FIXME a = StrOption('ip_address_service', '', properties=(disabled_property,)) -# FIXME od = OptionDescription('service', '', [a]) -# FIXME cfg = await Config(od) -# FIXME await cfg.property.read_write() -# FIXME cfg = await get_config(cfg, config_type) -# FIXME assert await cfg.option('ip_address_service').value.get() == None -# FIXME await cfg.option('ip_address_service').value.set('a') -# FIXME assert await cfg.option('ip_address_service').value.get() == 'a' -# FIXME await cfg.option('ip_address_service').value.set('b') -# FIXME props = [] -# FIXME try: -# FIXME await cfg.option('ip_address_service').value.get() -# FIXME except PropertiesOptionError as err: -# FIXME props = err.proptype -# FIXME assert frozenset(props) == frozenset(['disabled']) +@pytest.mark.asyncio +async def test_requires_self(config_type): + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamSelfOption(), + 'expected': ParamValue('b')})) + a = StrOption('ip_address_service', '', properties=(disabled_property,)) + od = OptionDescription('service', '', [a]) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_address_service').value.get() == None + await cfg.option('ip_address_service').value.set('a') + assert await cfg.option('ip_address_service').value.get() == 'a' + await cfg.option('ip_address_service').value.set('b') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_requires_with_requires(config_type): -# FIXME a = BoolOption('activate_service', '', True) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(a), -# FIXME 'expected': ParamValue(False)})) -# FIXME b = IPOption('ip_address_service', '', properties=(disabled_property,)) -# FIXME od = OptionDescription('service', '', [a, b]) -# FIXME cfg = await Config(od) -# FIXME await cfg.property.read_write() -# FIXME await cfg.option('ip_address_service').property.add('test') -# FIXME cfg = await get_config(cfg, config_type) -# FIXME await cfg.option('ip_address_service').value.get() -# FIXME await cfg.option('activate_service').value.set(False) -# FIXME props = [] -# FIXME try: -# FIXME await cfg.option('ip_address_service').value.get() -# FIXME except PropertiesOptionError as err: -# FIXME props = err.proptype -# FIXME assert frozenset(props) == frozenset(['disabled']) -# FIXME await cfg.option('activate_service').value.set(True) -# FIXME await cfg.option('ip_address_service').value.get() +@pytest.mark.asyncio +async def test_requires_with_requires(config_type): + a = BoolOption('activate_service', '', True) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(a), + 'expected': ParamValue(False)})) + b = IPOption('ip_address_service', '', properties=(disabled_property,)) + od = OptionDescription('service', '', [a, b]) + if environ.get('TIRAMISU_STORAGE'): + print('not implemeted yet (store calculated property)') + else: + async with await Config(od) as cfg: + await cfg.property.read_write() + await cfg.option('ip_address_service').property.add('test') + cfg = await get_config(cfg, config_type) + await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(False) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(True) + await cfg.option('ip_address_service').value.get() + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_requires_same_action(config_type): -# FIXME activate_service = BoolOption('activate_service', '', True) -# FIXME new_property = Calculation(calc_value, -# FIXME Params(ParamValue('new'), -# FIXME kwargs={'condition': ParamOption(activate_service, todict=True), -# FIXME 'expected': ParamValue(False)}), -# FIXME calc_value_property_help) -# FIXME activate_service_web = BoolOption('activate_service_web', '', True, properties=(new_property,)) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(activate_service_web, notraisepropertyerror=True, todict=True), -# FIXME 'expected': ParamValue(False)}), -# FIXME calc_value_property_help) -# FIXME ip_address_service_web = IPOption('ip_address_service_web', '', properties=(disabled_property,)) -# FIXME od1 = OptionDescription('service', '', [activate_service, activate_service_web, ip_address_service_web]) -# FIXME cfg = await Config(od1) -# FIXME await cfg.property.read_write() -# FIXME await cfg.property.add('new') -# FIXME cfg = await get_config(cfg, config_type) -# FIXME await cfg.option('activate_service').value.get() -# FIXME await cfg.option('activate_service_web').value.get() -# FIXME await cfg.option('ip_address_service_web').value.get() -# FIXME await cfg.option('activate_service').value.set(False) -# FIXME # -# FIXME props = [] -# FIXME try: -# FIXME await cfg.option('activate_service_web').value.get() -# FIXME except PropertiesOptionError as err: -# FIXME props = err.proptype -# FIXME if config_type == 'tiramisu': -# FIXME assert frozenset(props) == frozenset(['new']) -# FIXME else: -# FIXME assert frozenset(props) == frozenset(['disabled']) -# FIXME # -# FIXME props = [] -# FIXME try: -# FIXME await cfg.option('ip_address_service_web').value.get() -# FIXME except PropertiesOptionError as err: -# FIXME props = err.proptype -# FIXME submsg = '"disabled" (' + _('the value of "{0}" is {1}').format('activate_service', '"False"') + ')' -# FIXME if config_type == 'tiramisu': -# FIXME submsg = '"new" (' + _('the value of "{0}" is {1}').format('activate_service', '"False"') + ')' -# FIXME submsg = '"disabled" (' + str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('property'), submsg)) + ')' -# FIXME assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', _('property'), submsg)) -# FIXME #access to cache -# FIXME assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', _('property'), submsg)) -# FIXME else: -# FIXME # FIXME -# FIXME assert str(err) == 'error' -# FIXME assert frozenset(props) == frozenset(['disabled']) +@pytest.mark.asyncio +async def test_requires_same_action(config_type): + activate_service = BoolOption('activate_service', '', True) + new_property = Calculation(calc_value, + Params(ParamValue('new'), + kwargs={'condition': ParamOption(activate_service, todict=True), + 'expected': ParamValue(False)}), + calc_value_property_help) + activate_service_web = BoolOption('activate_service_web', '', True, properties=(new_property,)) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(activate_service_web, notraisepropertyerror=True, todict=True), + 'expected': ParamValue(False)}), + calc_value_property_help) + ip_address_service_web = IPOption('ip_address_service_web', '', properties=(disabled_property,)) + od1 = OptionDescription('service', '', [activate_service, activate_service_web, ip_address_service_web]) + async with await Config(od1) as cfg: + await cfg.property.read_write() + await cfg.property.add('new') + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('activate_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu': + assert frozenset(props) == frozenset(['new']) + else: + assert frozenset(props) == frozenset(['disabled']) + # + props = [] + try: + await cfg.option('ip_address_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + submsg = '"disabled" (' + _('the value of "{0}" is {1}').format('activate_service', '"False"') + ')' + if config_type == 'tiramisu': + submsg = '"new" (' + _('the value of "{0}" is {1}').format('activate_service', '"False"') + ')' + submsg = '"disabled" (' + str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('property'), submsg)) + ')' + assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', _('property'), submsg)) + #access to cache + assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', _('property'), submsg)) + else: + # FIXME + assert str(err) == 'error' + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -221,28 +227,29 @@ async def test_multiple_requires(config_type): 'expected_1': ParamValue('ok')})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set('yes') - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set('yes') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set('ok') - props = [] - try: + await cfg.option('activate_service').value.set('ok') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set('no') await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - - await cfg.option('activate_service').value.set('no') - await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -258,26 +265,27 @@ async def test_multiple_requires_cumulative(config_type): 'expected': ParamValue('yes')})) b = IPOption('ip_address_service', '', properties=(disabled_property, hidden_property)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set('yes') - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - if config_type == 'tiramisu': - assert set(props) == {'hidden', 'disabled'} - else: - assert set(props) == {'disabled'} + await cfg.option('activate_service').value.set('yes') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu': + assert set(props) == {'hidden', 'disabled'} + else: + assert set(props) == {'disabled'} - await cfg.option('activate_service').value.set('ok') - await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set('ok') + await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set('no') - await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set('no') + await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -295,42 +303,43 @@ async def test_multiple_requires_cumulative_inverse(config_type): 'reverse_condition': ParamValue(True)})) b = IPOption('ip_address_service', '', properties=(disabled_property, hidden_property)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu': + assert set(props) == {'hidden', 'disabled'} + else: + assert set(props) == {'disabled'} + await cfg.option('activate_service').value.set('yes') await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - if config_type == 'tiramisu': - assert set(props) == {'hidden', 'disabled'} - else: - assert set(props) == {'disabled'} - await cfg.option('activate_service').value.set('yes') - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set('ok') - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - if config_type == 'tiramisu': - assert set(props) == {'hidden', 'disabled'} - else: - assert set(props) == {'disabled'} + await cfg.option('activate_service').value.set('ok') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu': + assert set(props) == {'hidden', 'disabled'} + else: + assert set(props) == {'disabled'} - await cfg.option('activate_service').value.set('no') - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - if config_type == 'tiramisu': - assert set(props) == {'hidden', 'disabled'} - else: - assert set(props) == {'disabled'} + await cfg.option('activate_service').value.set('no') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu': + assert set(props) == {'hidden', 'disabled'} + else: + assert set(props) == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio @@ -344,29 +353,30 @@ async def test_multiple_requires_inverse(config_type): 'reverse_condition': ParamValue(True)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set('yes') await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set('yes') - await cfg.option('ip_address_service').value.get() - - await cfg.option('activate_service').value.set('ok') - await cfg.option('ip_address_service').value.get() - - await cfg.option('activate_service').value.set('no') - props = [] - try: + await cfg.option('activate_service').value.set('ok') await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set('no') + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -384,27 +394,28 @@ async def test_requires_transitive(config_type): d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() await cfg.option('activate_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - props = [] - try: await cfg.option('ip_address_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + props = [] + try: + await cfg.option('ip_address_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -421,18 +432,19 @@ async def test_requires_transitive_unrestraint(config_type): 'expected': ParamValue(False)})) d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg_ori = await Config(od) - await cfg_ori.property.read_write() - cfg = await get_config(cfg_ori, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - if config_type == 'tiramisu-api': - await cfg.send() - assert await cfg_ori.unrestraint.option('activate_service_web').property.get() == {'disabled'} - assert await cfg_ori.unrestraint.option('ip_address_service_web').property.get() == {'disabled'} + async with await Config(od) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('activate_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('activate_service').value.set(False) + # + if config_type == 'tiramisu-api': + await cfg.send() + assert await cfg_ori.unrestraint.option('activate_service_web').property.get() == {'disabled'} + assert await cfg_ori.unrestraint.option('ip_address_service_web').property.get() == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio @@ -450,21 +462,22 @@ async def test_requires_transitive_owner(config_type): d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - #no more default value - await cfg.option('ip_address_service_web').value.set('1.1.1.1') - await cfg.option('activate_service').value.set(False) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('activate_service_web').value.get() await cfg.option('ip_address_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + #no more default value + await cfg.option('ip_address_service_web').value.set('1.1.1.1') + await cfg.option('activate_service').value.set(False) + props = [] + try: + await cfg.option('ip_address_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -484,27 +497,28 @@ async def test_requires_transitive_bis(config_type): 'reverse_condition': ParamValue(True)})) d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, abis, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - # - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + # await cfg.option('activate_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - props = [] - try: await cfg.option('ip_address_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + props = [] + try: + await cfg.option('ip_address_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -521,15 +535,16 @@ async def test_requires_transitive_hidden_permissive(): 'expected': ParamValue(False)})) d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - # FIXME permissive cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - await cfg.option('ip_address_service_web').value.get() + async with await Config(od) as cfg: + await cfg.property.read_write() + # FIXME permissive cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('activate_service').value.set(False) + # + await cfg.option('ip_address_service_web').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -546,97 +561,96 @@ async def test_requires_transitive_hidden_disabled(config_type): 'expected': ParamValue(False)})) d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() await cfg.option('activate_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - if config_type == 'tiramisu-api': - assert frozenset(props) == frozenset(['disabled']) - else: - assert frozenset(props) == frozenset(['hidden']) - await cfg.option('ip_address_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + if config_type == 'tiramisu-api': + assert frozenset(props) == frozenset(['disabled']) + else: + assert frozenset(props) == frozenset(['hidden']) + await cfg.option('ip_address_service_web').value.get() + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_requires_transitive_hidden_disabled_multiple(config_type): -# FIXME a = BoolOption('activate_service', '', True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition': ParamOption(a, notraisepropertyerror=True), -# FIXME 'expected': ParamValue(False)})) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(a, notraisepropertyerror=True), -# FIXME 'expected': ParamValue(False)})) -# FIXME b = BoolOption('activate_service_web', '', True, properties=(hidden_property, disabled_property)) -# FIXME mandatory_property = Calculation(calc_value, -# FIXME Params(ParamValue('mandatory'), -# FIXME kwargs={'condition': ParamOption(b), -# FIXME 'expected': ParamValue(False)})) -# FIXME d = IPOption('ip_address_service_web', '', properties=(mandatory_property,)) -# FIXME od = OptionDescription('service', '', [a, b, d]) -# FIXME cfg_ori = await Config(od) -# FIXME await cfg_ori.property.read_write() -# FIXME cfg = await get_config(cfg_ori, config_type) -# FIXME await cfg.option('activate_service').value.get() -# FIXME await cfg.option('activate_service_web').value.get() -# FIXME await cfg.option('ip_address_service_web').value.get() -# FIXME req = None -# FIXME if config_type == 'tiramisu-api': -# FIXME try: -# FIXME await cfg.option('activate_service').value.set(False) -# FIXME except ConfigError as err: -# FIXME req = err -# FIXME error_msg = str(_('unable to transform tiramisu object to dict: {}').format(_('cannot access to option "{0}" because required option "{1}" has {2} {3}').format('ip_address_service_web', 'activate_service_web', _('property'), '"disabled"'))) -# FIXME else: -# FIXME await cfg.option('activate_service').value.set(False) -# FIXME # -# FIXME props = [] -# FIXME try: -# FIXME await cfg.option('activate_service_web').value.get() -# FIXME except PropertiesOptionError as err: -# FIXME props = err.proptype -# FIXME if config_type == 'tiramisu-api': -# FIXME assert set(props) == {'disabled',} -# FIXME else: -# FIXME assert set(props) == {'disabled', 'hidden'} -# FIXME del props -# FIXME # -# FIXME try: -# FIXME await cfg.option('ip_address_service_web').value.get() -# FIXME except ConfigError as err: -# FIXME req = err -# FIXME error_msg = str(_('unable to carry out a calculation for "{}", {}').format('ip_address_service_web', _('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('properties'), display_list(['hidden', 'disabled'], add_quote=True)))) -# FIXME assert req, "ip_address_service_web should raise ConfigError" -# FIXME assert str(req) == error_msg -# FIXME del req -# FIXME # -# FIXME await cfg_ori.permissive.reset() -# FIXME if config_type == 'tiramisu-api': -# FIXME try: -# FIXME cfg = await get_config(cfg_ori, config_type) -# FIXME except ConfigError as err: -# FIXME req = err -# FIXME error_msg = str(_('unable to transform tiramisu object to dict: {}').format(_('cannot access to option "{0}" because required option "{1}" has {2} {3}').format('ip_address_service_web', 'activate_service_web', _('properties'), '"disabled" {} "hidden"'.format(_('and'))))) -# FIXME else: -# FIXME cfg = await get_config(cfg_ori, config_type) -# FIXME try: -# FIXME await cfg.option('ip_address_service_web').value.get() -# FIXME except ConfigError as err: -# FIXME req = err -# FIXME error_msg = str(_('unable to carry out a calculation for "{}", {}').format('ip_address_service_web', _('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('properties'), display_list(['hidden', 'disabled'], add_quote=True)))) -# FIXME assert req, "ip_address_service_web should raise ConfigError" -# FIXME assert str(req) == error_msg -# FIXME del req +@pytest.mark.asyncio +async def test_requires_transitive_hidden_disabled_multiple(config_type): + a = BoolOption('activate_service', '', True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition': ParamOption(a, notraisepropertyerror=True), + 'expected': ParamValue(False)})) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(a, notraisepropertyerror=True), + 'expected': ParamValue(False)})) + b = BoolOption('activate_service_web', '', True, properties=(hidden_property, disabled_property)) + mandatory_property = Calculation(calc_value, + Params(ParamValue('mandatory'), + kwargs={'condition': ParamOption(b), + 'expected': ParamValue(False)})) + d = IPOption('ip_address_service_web', '', properties=(mandatory_property,)) + od = OptionDescription('service', '', [a, b, d]) + async with await Config(od) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('activate_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + req = None + if config_type == 'tiramisu-api': + try: + await cfg.option('activate_service').value.set(False) + except ConfigError as err: + req = err + error_msg = str(_('unable to transform tiramisu object to dict: {}').format(_('cannot access to option "{0}" because required option "{1}" has {2} {3}').format('ip_address_service_web', 'activate_service_web', _('property'), '"disabled"'))) + else: + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert set(props) == {'disabled', 'hidden'} + del props + # + try: + await cfg.option('ip_address_service_web').value.get() + except ConfigError as err: + req = err + error_msg = str(_('unable to carry out a calculation for "{}", {}').format('ip_address_service_web', _('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('property'), display_list(['disabled'], add_quote=True)))) + assert req, "ip_address_service_web should raise ConfigError" + assert str(req) == error_msg + del req + # + await cfg_ori.permissive.reset() + if config_type == 'tiramisu-api': + try: + cfg = await get_config(cfg_ori, config_type) + except ConfigError as err: + req = err + error_msg = str(_('unable to transform tiramisu object to dict: {}').format(_('cannot access to option "{0}" because required option "{1}" has {2} {3}').format('ip_address_service_web', 'activate_service_web', _('properties'), '"disabled" {} "hidden"'.format(_('and'))))) + else: + cfg = await get_config(cfg_ori, config_type) + try: + await cfg.option('ip_address_service_web').value.get() + except ConfigError as err: + req = err + error_msg = str(_('unable to carry out a calculation for "{}", {}').format('ip_address_service_web', _('cannot access to {0} "{1}" because has {2} {3}').format('option', 'activate_service_web', _('properties'), display_list(['hidden', 'disabled'], add_quote=True)))) + assert req, "ip_address_service_web should raise ConfigError" + assert str(req) == error_msg + del req + assert not await list_sessions() @pytest.mark.asyncio @@ -654,22 +668,23 @@ async def test_requires_not_transitive(config_type): 'expected': ParamValue(False)})) d = IPOption('ip_address_service_web', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - await cfg.option('activate_service').value.set(False) - # - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() await cfg.option('activate_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - await cfg.option('ip_address_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + await cfg.option('activate_service').value.set(False) + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + await cfg.option('ip_address_service_web').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -686,27 +701,28 @@ async def test_requires_not_transitive_not_same_action(config_type): 'expected': ParamValue(False)})) d = IPOption('ip_address_service_web', '', properties=(hidden_property,)) od = OptionDescription('service', '', [a, b, d]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - await cfg.option('activate_service').value.get() - await cfg.option('activate_service_web').value.get() - await cfg.option('ip_address_service_web').value.get() - if config_type == 'tiramisu-api': - with pytest.raises(ConfigError): + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('activate_service').value.get() + await cfg.option('activate_service_web').value.get() + await cfg.option('ip_address_service_web').value.get() + if config_type == 'tiramisu-api': + with pytest.raises(ConfigError): + await cfg.option('activate_service').value.set(False) + else: await cfg.option('activate_service').value.set(False) - else: - await cfg.option('activate_service').value.set(False) - # - props = [] - try: - await cfg.option('activate_service_web').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - # - with pytest.raises(ConfigError): - await cfg.option('ip_address_service_web').value.get() + # + props = [] + try: + await cfg.option('activate_service_web').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + # + with pytest.raises(ConfigError): + await cfg.option('ip_address_service_web').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -718,17 +734,18 @@ async def test_requires_none(config_type): 'expected': ParamValue(None)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - props = [] - try: + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.option('activate_service').value.set(False) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set(False) - await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -744,38 +761,39 @@ async def test_requires_multi_disabled(config_type): 'condition_operator': ParamValue('OR')})) c = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, c]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) - await cfg.option('ip_address_service').value.get() - - await cfg.option('activate_service').value.set(True) - props = [] - try: await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set(False) - await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(True) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) - await cfg.option('num_service').value.set(1) - props = [] - try: + await cfg.option('activate_service').value.set(False) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('activate_service').value.set(True) - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) + await cfg.option('num_service').value.set(1) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set(True) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -793,43 +811,44 @@ async def test_requires_multi_disabled_inverse(config_type): 'reverse_condition_1': ParamValue(True)})) c = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b, c]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) - props = [] - try: + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set(True) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set(False) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('num_service').value.set(1) + props = [] + try: + await cfg.option('ip_address_service').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + + await cfg.option('activate_service').value.set(True) await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - - await cfg.option('activate_service').value.set(True) - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - - await cfg.option('activate_service').value.set(False) - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - - await cfg.option('num_service').value.set(1) - props = [] - try: - await cfg.option('ip_address_service').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - - await cfg.option('activate_service').value.set(True) - await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -860,30 +879,31 @@ async def test_requires_multi_disabled_2(config_type): y = copy(list_bools) y.append(z) od = OptionDescription('service', '', y) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) - await cfg.option('z').value.get() - for boo in list_bools: - await cfg.option(boo.impl_getname()).value.set(True) - props = [] - try: - await cfg.option('z').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - for boo in list_bools: - await cfg.option(boo.impl_getname()).value.set(False) - if boo == m: - await cfg.option('z').value.get() - else: + await cfg.option('z').value.get() + for boo in list_bools: + await cfg.option(boo.impl_getname()).value.set(True) props = [] try: await cfg.option('z').value.get() except PropertiesOptionError as err: props = err.proptype assert frozenset(props) == frozenset(['disabled']) + for boo in list_bools: + await cfg.option(boo.impl_getname()).value.set(False) + if boo == m: + await cfg.option('z').value.get() + else: + props = [] + try: + await cfg.option('z').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + assert not await list_sessions() @pytest.mark.asyncio @@ -918,75 +938,80 @@ async def test_requires_multi_disabled_inverse_2(config_type): y = copy(list_bools) y.append(z) od = OptionDescription('service', '', y) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) - props = [] - try: - await cfg.option('z').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - for boo in list_bools: - await cfg.option(boo.impl_getname()).value.set(True) - if boo != m: - # it's disabled until last option is modified - props = [] - try: - await cfg.option('z').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert frozenset(props) == frozenset(['disabled']) - await cfg.option('z').value.get() - for boo in list_bools: - await cfg.option(boo.impl_getname()).value.set(False) props = [] try: await cfg.option('z').value.get() except PropertiesOptionError as err: props = err.proptype assert frozenset(props) == frozenset(['disabled']) - try: + for boo in list_bools: + await cfg.option(boo.impl_getname()).value.set(True) + if boo != m: + # it's disabled until last option is modified + props = [] + try: + await cfg.option('z').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) await cfg.option('z').value.get() - except PropertiesOptionError as err: - props = err.proptype - for boo in reversed(list_bools): - await cfg.option(boo.impl_getname()).value.set(True) - if boo != a: - # it's disabled until last option is modified + for boo in list_bools: + await cfg.option(boo.impl_getname()).value.set(False) props = [] try: await cfg.option('z').value.get() except PropertiesOptionError as err: props = err.proptype assert frozenset(props) == frozenset(['disabled']) - await cfg.option('z').value.get() + try: + await cfg.option('z').value.get() + except PropertiesOptionError as err: + props = err.proptype + for boo in reversed(list_bools): + await cfg.option(boo.impl_getname()).value.set(True) + if boo != a: + # it's disabled until last option is modified + props = [] + try: + await cfg.option('z').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert frozenset(props) == frozenset(['disabled']) + await cfg.option('z').value.get() + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_requires_requirement_append(config_type): -# FIXME a = BoolOption('activate_service', '', True) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(a, notraisepropertyerror=True), -# FIXME 'expected': ParamValue(False)})) -# FIXME b = IPOption('ip_address_service', '', properties=(disabled_property,)) -# FIXME od = OptionDescription('service', '', [a, b]) -# FIXME cfg_ori = await Config(od) -# FIXME await cfg_ori.property.read_write() -# FIXME cfg = await get_config(cfg_ori, config_type) -# FIXME await cfg.property.get() -# FIXME await cfg.option('ip_address_service').property.get() -# FIXME if config_type == 'tiramisu-api': -# FIXME await cfg.send() -# FIXME #raises(ValueError, "await cfg_ori.option('ip_address_service').property.add('disabled')") -# FIXME cfg = await get_config(cfg_ori, config_type) -# FIXME await cfg.option('activate_service').value.set(False) -# FIXME # disabled is now set, test to remove disabled before store in storage -# FIXME if config_type == 'tiramisu-api': -# FIXME await cfg.send() -# FIXME await cfg_ori.unrestraint.option('ip_address_service').property.add("test") +@pytest.mark.asyncio +async def test_requires_requirement_append(config_type): + a = BoolOption('activate_service', '', True) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(a, notraisepropertyerror=True), + 'expected': ParamValue(False)})) + b = IPOption('ip_address_service', '', properties=(disabled_property,)) + od = OptionDescription('service', '', [a, b]) + async with await Config(od) as cfg_ori: + await cfg_ori.property.read_write() + cfg = await get_config(cfg_ori, config_type) + await cfg.property.get() + await cfg.option('ip_address_service').property.get() + if config_type == 'tiramisu-api': + await cfg.send() + #raises(ValueError, "await cfg_ori.option('ip_address_service').property.add('disabled')") + cfg = await get_config(cfg_ori, config_type) + await cfg.option('activate_service').value.set(False) + # disabled is now set, test to remove disabled before store in storage + if config_type == 'tiramisu-api': + await cfg.send() + if environ.get('TIRAMISU_STORAGE'): + print('not implemeted yet (store calculated property)') + else: + await cfg_ori.unrestraint.option('ip_address_service').property.add("test") + assert not await list_sessions() @pytest.mark.asyncio @@ -1002,14 +1027,15 @@ async def test_requires_different_inverse(config_type): 'reverse_condition_0': ParamValue(True)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - #with pytest.raises(PropertiesOptionError): - # await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_address_service').value.get() + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + #with pytest.raises(PropertiesOptionError): + # await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1026,21 +1052,22 @@ async def test_requires_different_inverse_unicode(config_type): 'reverse_condition_0': ParamValue(True)})) b = IPOption('ip_address_service', '', properties=(disabled_property,)) od = OptionDescription('service', '', [a, d, b]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_address_service').value.get() == None - await cfg.option('activate_service').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set(True) - assert await cfg.option('ip_address_service').value.get() == None - await cfg.option('activate_other_service').value.set('val1') - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_address_service').value.get() - await cfg.option('activate_service').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_address_service').value.get() + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_address_service').value.get() == None + await cfg.option('activate_service').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(True) + assert await cfg.option('ip_address_service').value.get() == None + await cfg.option('activate_other_service').value.set('val1') + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_address_service').value.get() + await cfg.option('activate_service').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_address_service').value.get() + assert not await list_sessions() @pytest.mark.asyncio @@ -1066,59 +1093,60 @@ async def test_leadership_requires(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True, properties=(disabled_property,)) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('toto', '', [interface1]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.2']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255' - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.2'], - 'ip_admin_eth0.netmask_admin_eth0': [None, '255.255.255.255']} - assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', 'ip_admin_eth0.netmask_admin_eth0': None}, - {'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', 'ip_admin_eth0.netmask_admin_eth0': '255.255.255.255'}]} - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() - ret = await cfg.value.dict() - assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1'] - assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2 - assert ret['ip_admin_eth0.netmask_admin_eth0'][0] is None - assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError) - del ret['ip_admin_eth0.netmask_admin_eth0'][1] - del ret['ip_admin_eth0.netmask_admin_eth0'][0] - del ret['ip_admin_eth0.netmask_admin_eth0'] - assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', - 'ip_admin_eth0.netmask_admin_eth0': None}, - {'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} - # - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255') - ret = await cfg.value.dict() - assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) - assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1'] - assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2 - assert ret['ip_admin_eth0.netmask_admin_eth0'][0] == '255.255.255.255' - assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError) - del ret['ip_admin_eth0.netmask_admin_eth0'][1] - del ret['ip_admin_eth0.netmask_admin_eth0'][0] - del ret['ip_admin_eth0.netmask_admin_eth0'] - assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', - 'ip_admin_eth0.netmask_admin_eth0': '255.255.255.255'}, - {'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.2']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255' + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.2'], + 'ip_admin_eth0.netmask_admin_eth0': [None, '255.255.255.255']} + assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', 'ip_admin_eth0.netmask_admin_eth0': None}, + {'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', 'ip_admin_eth0.netmask_admin_eth0': '255.255.255.255'}]} + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() + ret = await cfg.value.dict() + assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1'] + assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2 + assert ret['ip_admin_eth0.netmask_admin_eth0'][0] is None + assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError) + del ret['ip_admin_eth0.netmask_admin_eth0'][1] + del ret['ip_admin_eth0.netmask_admin_eth0'][0] + del ret['ip_admin_eth0.netmask_admin_eth0'] + assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', + 'ip_admin_eth0.netmask_admin_eth0': None}, + {'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} + # + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255') + ret = await cfg.value.dict() + assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0']) + assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1'] + assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2 + assert ret['ip_admin_eth0.netmask_admin_eth0'][0] == '255.255.255.255' + assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError) + del ret['ip_admin_eth0.netmask_admin_eth0'][1] + del ret['ip_admin_eth0.netmask_admin_eth0'][0] + del ret['ip_admin_eth0.netmask_admin_eth0'] + assert await cfg.value.dict(leader_to_list=True) == {'ip_admin_eth0.ip_admin_eth0': [{'ip_admin_eth0.ip_admin_eth0': '192.168.1.2', + 'ip_admin_eth0.netmask_admin_eth0': '255.255.255.255'}, + {'ip_admin_eth0.ip_admin_eth0': '192.168.1.1'}]} + assert not await list_sessions() @pytest.mark.asyncio @@ -1133,30 +1161,31 @@ async def test_leadership_requires_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=(disabled_property,)) od = OptionDescription('toto', '', [activate, interface1]) - cfg = await Config(od) - await cfg.property.read_write() + async with await Config(od) as cfg: + await cfg.property.read_write() - # - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] - # - await cfg.option('activate').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - # - await cfg.option('activate').value.set(True) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - # - await cfg.option('activate').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - assert await cfg.value.dict() == {'activate': False} + # + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] + # + await cfg.option('activate').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + # + await cfg.option('activate').value.set(True) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + # + await cfg.option('activate').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + assert await cfg.value.dict() == {'activate': False} + assert not await list_sessions() @pytest.mark.asyncio @@ -1171,34 +1200,35 @@ async def test_leadership_requires_leadership(config_type): 'index': ParamIndex()})) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=(disabled_property,)) od = OptionDescription('toto', '', [activate, interface1]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - # - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] - # - await cfg.option('activate').value.set(False) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - # - await cfg.option('activate').value.set(True) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - # - await cfg.option('activate').value.set(False) - if config_type != 'tiramisu-api': - # FIXME - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - assert await cfg.value.dict() == {'activate': False} + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + # + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] + # + await cfg.option('activate').value.set(False) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + # + await cfg.option('activate').value.set(True) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + # + await cfg.option('activate').value.set(False) + if config_type != 'tiramisu-api': + # FIXME + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + assert await cfg.value.dict() == {'activate': False} + assert not await list_sessions() @pytest.mark.asyncio @@ -1212,261 +1242,264 @@ async def test_leadership_requires_no_leader(config_type): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True, properties=(disabled_property,)) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('toto', '', [activate, interface1]) - cfg = await Config(od) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] - await cfg.option('activate').value.set(False) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2', '192.168.1.1'] - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() - await cfg.option('activate').value.set(True) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255' - await cfg.option('activate').value.set(False) - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() - with pytest.raises(PropertiesOptionError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.1'], 'activate': False} + async with await Config(od) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2'] + await cfg.option('activate').value.set(False) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2', '192.168.1.1'] + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() + await cfg.option('activate').value.set(True) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255') + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255' + await cfg.option('activate').value.set(False) + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() + with pytest.raises(PropertiesOptionError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.1'], 'activate': False} + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_leadership_requires_complet(config_type): -# FIXME optiontoto = StrOption('unicodetoto', "Unicode") -# FIXME option = StrOption('unicode', "Unicode leader", multi=True) -# FIXME option1 = StrOption('unicode1', "Unicode follower 1", multi=True) -# FIXME option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition': ParamOption(option, notraisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'index': ParamIndex(), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition': ParamOption(option2, notraisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'index': ParamIndex(), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option4 = StrOption('unicode4', "Unicode follower 4", properties=(hidden_property,), multi=True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition': ParamOption(optiontoto, notraisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option5 = StrOption('unicode5', "Unicode follower 5", properties=(hidden_property,), multi=True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition_0': ParamOption(optiontoto, notraisepropertyerror=True), -# FIXME 'expected_0': ParamValue('test'), -# FIXME 'condition_1': ParamOption(option2, notraisepropertyerror=True), -# FIXME 'expected_1': ParamValue('test'), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'condition_operator': ParamValue('OR'), -# FIXME 'reverse_condition_0': ParamValue(True), -# FIXME 'reverse_condition_1': ParamValue(True)})) -# FIXME option6 = StrOption('unicode6', "Unicode follower 6", properties=(hidden_property,), multi=True) -# FIXME hidden_property = Calculation(calc_value, -# FIXME Params(ParamValue('hidden'), -# FIXME kwargs={'condition_0': ParamOption(option2, notraisepropertyerror=True), -# FIXME 'expected_0': ParamValue('test'), -# FIXME 'condition_1': ParamOption(optiontoto, notraisepropertyerror=True), -# FIXME 'expected_1': ParamValue('test'), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option7 = StrOption('unicode7', "Unicode follower 7", properties=(hidden_property,), multi=True) -# FIXME descr1 = Leadership("unicode", "Common configuration 1", -# FIXME [option, option1, option2, option3, option4, option5, option6, option7]) -# FIXME descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto]) -# FIXME descr = OptionDescription("unicode1_leadership_requires", "Leader followers with Unicode follower 3 hidden when Unicode follower 2 is test", [descr]) -# FIXME cfg = await Config(descr) -# FIXME await cfg.property.read_write() -# FIXME cfg = await get_config(cfg, config_type) -# FIXME await cfg.option('options.unicode.unicode').value.set(['test', 'trah']) -# FIXME await cfg.option('options.unicode.unicode2', 0).value.set('test') -# FIXME dico = await cfg.value.dict() -# FIXME assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto']) -# FIXME assert dico['options.unicode.unicode'] == ['test', 'trah'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None] -# FIXME assert dico['options.unicode.unicode2'] == ['test', None] -# FIXME assert dico['options.unicode.unicode3'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode4'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode6'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode6'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode7'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode7'][1], PropertiesOptionError) -# FIXME assert dico['options.unicodetoto'] is None -# FIXME del dico['options.unicode.unicode3'][1] -# FIXME del dico['options.unicode.unicode3'] -# FIXME del dico['options.unicode.unicode4'][1] -# FIXME del dico['options.unicode.unicode4'] -# FIXME del dico['options.unicode.unicode6'][1] -# FIXME del dico['options.unicode.unicode6'][0] -# FIXME del dico['options.unicode.unicode7'][1] -# FIXME del dico['options.unicode.unicode7'][0] -# FIXME # -# FIXME await cfg.option('options.unicodetoto').value.set('test') -# FIXME dico = await cfg.value.dict() -# FIXME assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode5', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto']) -# FIXME assert dico['options.unicode.unicode'] == ['test', 'trah'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None] -# FIXME assert dico['options.unicode.unicode2'] == ['test', None] -# FIXME assert dico['options.unicode.unicode3'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode4'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode5'] == [None, None] -# FIXME assert dico['options.unicode.unicode6'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode6'][1], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode7'][0] is None -# FIXME assert isinstance(dico['options.unicode.unicode7'][1], PropertiesOptionError) -# FIXME assert dico['options.unicodetoto'] == 'test' -# FIXME del dico['options.unicode.unicode3'][1] -# FIXME del dico['options.unicode.unicode3'] -# FIXME del dico['options.unicode.unicode4'][1] -# FIXME del dico['options.unicode.unicode4'] -# FIXME del dico['options.unicode.unicode6'][1] -# FIXME del dico['options.unicode.unicode6'][0] -# FIXME del dico['options.unicode.unicode7'][1] -# FIXME del dico['options.unicode.unicode7'][0] +@pytest.mark.asyncio +async def test_leadership_requires_complet(config_type): + optiontoto = StrOption('unicodetoto', "Unicode") + option = StrOption('unicode', "Unicode leader", multi=True) + option1 = StrOption('unicode1', "Unicode follower 1", multi=True) + option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition': ParamOption(option, notraisepropertyerror=True), + 'expected': ParamValue('test'), + 'index': ParamIndex(), + 'no_condition_is_invalid': ParamValue(True), + 'reverse_condition': ParamValue(True)})) + option3 = StrOption('unicode3', "Unicode follower 3", properties=(hidden_property,), multi=True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition': ParamOption(option2, notraisepropertyerror=True), + 'expected': ParamValue('test'), + 'no_condition_is_invalid': ParamValue(True), + 'index': ParamIndex(), + 'reverse_condition': ParamValue(True)})) + option4 = StrOption('unicode4', "Unicode follower 4", properties=(hidden_property,), multi=True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition': ParamOption(optiontoto, notraisepropertyerror=True), + 'expected': ParamValue('test'), + 'no_condition_is_invalid': ParamValue(True), + 'reverse_condition': ParamValue(True)})) + option5 = StrOption('unicode5', "Unicode follower 5", properties=(hidden_property,), multi=True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition_0': ParamOption(optiontoto, notraisepropertyerror=True), + 'expected_0': ParamValue('test'), + 'condition_1': ParamOption(option2, notraisepropertyerror=True), + 'expected_1': ParamValue('test'), + 'no_condition_is_invalid': ParamValue(True), + 'condition_operator': ParamValue('OR'), + 'reverse_condition_0': ParamValue(True), + 'reverse_condition_1': ParamValue(True)})) + option6 = StrOption('unicode6', "Unicode follower 6", properties=(hidden_property,), multi=True) + hidden_property = Calculation(calc_value, + Params(ParamValue('hidden'), + kwargs={'condition_0': ParamOption(option2, notraisepropertyerror=True), + 'expected_0': ParamValue('test'), + 'condition_1': ParamOption(optiontoto, notraisepropertyerror=True), + 'expected_1': ParamValue('test'), + 'no_condition_is_invalid': ParamValue(True), + 'reverse_condition': ParamValue(True)})) + option7 = StrOption('unicode7', "Unicode follower 7", properties=(hidden_property,), multi=True) + descr1 = Leadership("unicode", "Common configuration 1", + [option, option1, option2, option3, option4, option5, option6, option7]) + descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto]) + descr = OptionDescription("unicode1_leadership_requires", "Leader followers with Unicode follower 3 hidden when Unicode follower 2 is test", [descr]) + async with await Config(descr) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + await cfg.option('options.unicode.unicode').value.set(['test', 'trah']) + await cfg.option('options.unicode.unicode2', 0).value.set('test') + dico = await cfg.value.dict() + assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto']) + assert dico['options.unicode.unicode'] == ['test', 'trah'] + assert dico['options.unicode.unicode1'] == [None, None] + assert dico['options.unicode.unicode2'] == ['test', None] + assert dico['options.unicode.unicode3'][0] is None + assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) + assert dico['options.unicode.unicode4'][0] is None + assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode6'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode6'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode7'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode7'][1], PropertiesOptionError) + assert dico['options.unicodetoto'] is None + del dico['options.unicode.unicode3'][1] + del dico['options.unicode.unicode3'] + del dico['options.unicode.unicode4'][1] + del dico['options.unicode.unicode4'] + del dico['options.unicode.unicode6'][1] + del dico['options.unicode.unicode6'][0] + del dico['options.unicode.unicode7'][1] + del dico['options.unicode.unicode7'][0] + # + await cfg.option('options.unicodetoto').value.set('test') + dico = await cfg.value.dict() + assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode5', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto']) + assert dico['options.unicode.unicode'] == ['test', 'trah'] + assert dico['options.unicode.unicode1'] == [None, None] + assert dico['options.unicode.unicode2'] == ['test', None] + assert dico['options.unicode.unicode3'][0] is None + assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) + assert dico['options.unicode.unicode4'][0] is None + assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) + assert dico['options.unicode.unicode5'] == [None, None] + assert dico['options.unicode.unicode6'][0] is None + assert isinstance(dico['options.unicode.unicode6'][1], PropertiesOptionError) + assert dico['options.unicode.unicode7'][0] is None + assert isinstance(dico['options.unicode.unicode7'][1], PropertiesOptionError) + assert dico['options.unicodetoto'] == 'test' + del dico['options.unicode.unicode3'][1] + del dico['options.unicode.unicode3'] + del dico['options.unicode.unicode4'][1] + del dico['options.unicode.unicode4'] + del dico['options.unicode.unicode6'][1] + del dico['options.unicode.unicode6'][0] + del dico['options.unicode.unicode7'][1] + del dico['options.unicode.unicode7'][0] + assert not await list_sessions() -# FIXME @pytest.mark.asyncio -# FIXME async def test_leadership_requires_transitive1(config_type): -# FIXME optiontoto = StrOption('unicodetoto', "Simple unicode") -# FIXME option = StrOption('unicode', "Unicode leader", multi=True) -# FIXME option1 = StrOption('unicode1', "Unicode follower 1", multi=True) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(optiontoto, raisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option2 = StrOption('unicode2', "Unicode follower 2", properties=(disabled_property,), multi=True) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(option2, raisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'index': ParamIndex(), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option3 = StrOption('unicode3', "Unicode follower 3", properties=(disabled_property,), multi=True) -# FIXME disabled_property = Calculation(calc_value, -# FIXME Params(ParamValue('disabled'), -# FIXME kwargs={'condition': ParamOption(option3, raisepropertyerror=True), -# FIXME 'expected': ParamValue('test'), -# FIXME 'index': ParamIndex(), -# FIXME 'no_condition_is_invalid': ParamValue(True), -# FIXME 'reverse_condition': ParamValue(True)})) -# FIXME option4 = StrOption('unicode4', "Unicode follower 4", properties=(disabled_property,), multi=True) -# FIXME descr1 = Leadership("unicode", "Common configuration 1", -# FIXME [option, option1, option2, option3, option4]) -# FIXME descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto]) -# FIXME descr = OptionDescription("unicode1", "", [descr]) -# FIXME cfg = await Config(descr) -# FIXME await cfg.property.read_write() -# FIXME cfg = await get_config(cfg, config_type) -# FIXME assert await cfg.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': None} -# FIXME # -# FIXME await cfg.option('options.unicodetoto').value.set('test') -# FIXME assert await cfg.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode2': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': 'test'} -# FIXME # -# FIXME await cfg.option('options.unicode.unicode').value.set(['a', 'b', 'c']) -# FIXME dico = await cfg.value.dict() -# FIXME assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] -# FIXME assert dico['options.unicodetoto'] == 'test' -# FIXME assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None, None] -# FIXME assert dico['options.unicode.unicode2'] == [None, None, None] -# FIXME assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) -# FIXME del (dico['options.unicode.unicode3'][2]) -# FIXME del (dico['options.unicode.unicode3'][1]) -# FIXME del (dico['options.unicode.unicode3'][0]) -# FIXME del (dico['options.unicode.unicode4'][2]) -# FIXME del (dico['options.unicode.unicode4'][1]) -# FIXME del (dico['options.unicode.unicode4'][0]) -# FIXME # -# FIXME await cfg.option('options.unicode.unicode2', 1).value.set('test') -# FIXME await cfg.option('options.unicode.unicode3', 1).value.set('test') -# FIXME dico = await cfg.value.dict() -# FIXME assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] -# FIXME assert dico['options.unicodetoto'] == 'test' -# FIXME assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None, None] -# FIXME assert dico['options.unicode.unicode2'] == [None, 'test', None] -# FIXME assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode3'][1] == 'test' -# FIXME assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) -# FIXME assert dico['options.unicode.unicode4'][1] == None -# FIXME assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) -# FIXME del (dico['options.unicode.unicode3'][2]) -# FIXME del (dico['options.unicode.unicode3'][1]) -# FIXME del (dico['options.unicode.unicode3'][0]) -# FIXME del (dico['options.unicode.unicode4'][2]) -# FIXME del (dico['options.unicode.unicode4'][1]) -# FIXME del (dico['options.unicode.unicode4'][0]) -# FIXME # -# FIXME await cfg.option('options.unicode.unicode2', 1).value.set('rah') -# FIXME dico = await cfg.value.dict() -# FIXME assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] -# FIXME assert dico['options.unicodetoto'] == 'test' -# FIXME assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None, None] -# FIXME assert dico['options.unicode.unicode2'] == [None, 'rah', None] -# FIXME assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) -# FIXME del (dico['options.unicode.unicode3'][2]) -# FIXME del (dico['options.unicode.unicode3'][1]) -# FIXME del (dico['options.unicode.unicode3'][0]) -# FIXME del (dico['options.unicode.unicode4'][2]) -# FIXME del (dico['options.unicode.unicode4'][1]) -# FIXME del (dico['options.unicode.unicode4'][0]) -# FIXME # -# FIXME await cfg.option('options.unicode.unicode2', 1).value.set('test') -# FIXME await cfg.option('options.unicodetoto').value.set('rah') -# FIXME dico = await cfg.value.dict() -# FIXME assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] -# FIXME assert dico['options.unicodetoto'] == 'rah' -# FIXME assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] -# FIXME assert dico['options.unicode.unicode1'] == [None, None, None] -# FIXME assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) -# FIXME assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) -# FIXME del (dico['options.unicode.unicode3'][2]) -# FIXME del (dico['options.unicode.unicode3'][1]) -# FIXME del (dico['options.unicode.unicode3'][0]) -# FIXME del (dico['options.unicode.unicode4'][2]) -# FIXME del (dico['options.unicode.unicode4'][1]) -# FIXME del (dico['options.unicode.unicode4'][0]) -# FIXME -# FIXME -# FIXME # FIXME tester l'ajout d'un Calculation -# FIXME # FIXME permissive peut etre in calcul ! -# FIXME # FIXME Calculation sur des multis ... +@pytest.mark.asyncio +async def test_leadership_requires_transitive1(config_type): + optiontoto = StrOption('unicodetoto', "Simple unicode") + option = StrOption('unicode', "Unicode leader", multi=True) + option1 = StrOption('unicode1', "Unicode follower 1", multi=True) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(optiontoto, raisepropertyerror=True), + 'expected': ParamValue('test'), + 'reverse_condition': ParamValue(True)})) + option2 = StrOption('unicode2', "Unicode follower 2", properties=(disabled_property,), multi=True) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(option2, raisepropertyerror=True), + 'expected': ParamValue('test'), + 'index': ParamIndex(), + 'no_condition_is_invalid': ParamValue(True), + 'reverse_condition': ParamValue(True)})) + option3 = StrOption('unicode3', "Unicode follower 3", properties=(disabled_property,), multi=True) + disabled_property = Calculation(calc_value, + Params(ParamValue('disabled'), + kwargs={'condition': ParamOption(option3, raisepropertyerror=True), + 'expected': ParamValue('test'), + 'index': ParamIndex(), + 'no_condition_is_invalid': ParamValue(True), + 'reverse_condition': ParamValue(True)})) + option4 = StrOption('unicode4', "Unicode follower 4", properties=(disabled_property,), multi=True) + descr1 = Leadership("unicode", "Common configuration 1", + [option, option1, option2, option3, option4]) + descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto]) + descr = OptionDescription("unicode1", "", [descr]) + async with await Config(descr) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': None} + # + await cfg.option('options.unicodetoto').value.set('test') + assert await cfg.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode2': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': 'test'} + # + await cfg.option('options.unicode.unicode').value.set(['a', 'b', 'c']) + dico = await cfg.value.dict() + assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] + assert dico['options.unicodetoto'] == 'test' + assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] + assert dico['options.unicode.unicode1'] == [None, None, None] + assert dico['options.unicode.unicode2'] == [None, None, None] + assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) + del (dico['options.unicode.unicode3'][2]) + del (dico['options.unicode.unicode3'][1]) + del (dico['options.unicode.unicode3'][0]) + del (dico['options.unicode.unicode4'][2]) + del (dico['options.unicode.unicode4'][1]) + del (dico['options.unicode.unicode4'][0]) + + await cfg.option('options.unicode.unicode2', 1).value.set('test') + await cfg.option('options.unicode.unicode3', 1).value.set('test') + dico = await cfg.value.dict() + assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] + assert dico['options.unicodetoto'] == 'test' + assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] + assert dico['options.unicode.unicode1'] == [None, None, None] + assert dico['options.unicode.unicode2'] == [None, 'test', None] + assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) + assert dico['options.unicode.unicode3'][1] == 'test' + assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) + assert dico['options.unicode.unicode4'][1] == None + assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) + del (dico['options.unicode.unicode3'][2]) + del (dico['options.unicode.unicode3'][1]) + del (dico['options.unicode.unicode3'][0]) + del (dico['options.unicode.unicode4'][2]) + del (dico['options.unicode.unicode4'][1]) + del (dico['options.unicode.unicode4'][0]) + # + await cfg.option('options.unicode.unicode2', 1).value.set('rah') + dico = await cfg.value.dict() + assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] + assert dico['options.unicodetoto'] == 'test' + assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] + assert dico['options.unicode.unicode1'] == [None, None, None] + assert dico['options.unicode.unicode2'] == [None, 'rah', None] + assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) + del (dico['options.unicode.unicode3'][2]) + del (dico['options.unicode.unicode3'][1]) + del (dico['options.unicode.unicode3'][0]) + del (dico['options.unicode.unicode4'][2]) + del (dico['options.unicode.unicode4'][1]) + del (dico['options.unicode.unicode4'][0]) + # + await cfg.option('options.unicode.unicode2', 1).value.set('test') + await cfg.option('options.unicodetoto').value.set('rah') + dico = await cfg.value.dict() + assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto'] + assert dico['options.unicodetoto'] == 'rah' + assert dico['options.unicode.unicode'] == ['a', 'b', 'c'] + assert dico['options.unicode.unicode1'] == [None, None, None] + assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError) + assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError) + del (dico['options.unicode.unicode3'][2]) + del (dico['options.unicode.unicode3'][1]) + del (dico['options.unicode.unicode3'][0]) + del (dico['options.unicode.unicode4'][2]) + del (dico['options.unicode.unicode4'][1]) + del (dico['options.unicode.unicode4'][0]) + assert not await list_sessions() + + +# FIXME tester l'ajout d'un Calculation +# FIXME permissive peut etre in calcul ! +# FIXME Calculation sur des multis ... diff --git a/tests/test_slots.py b/tests/test_slots.py index 3d8496d..c9398d9 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -3,7 +3,6 @@ from .autopath import do_autopath do_autopath() import pytest -from py.test import raises import warnings try: @@ -18,60 +17,72 @@ from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption,\ PortOption, NetworkOption, NetmaskOption, DomainnameOption, EmailOption, \ URLOption, FilenameOption from tiramisu.storage import list_sessions, delete_session - - -def teardown_function(function): - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop def test_slots_option(): c = ChoiceOption('a', '', ('a',)) - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = BoolOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = IntOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = FloatOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = StrOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 c = SymLinkOption('b', c) - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = StrOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = IPOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = OptionDescription('a', '', []) - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = PortOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = NetworkOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = NetmaskOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = DomainnameOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = EmailOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = URLOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c c = FilenameOption('a', '') - raises(AttributeError, "c.x = 1") + with pytest.raises(AttributeError): + c.x = 1 del c @@ -107,22 +118,39 @@ async def test_slots_option_readonly(): o._name = 'o' p._name = 'p' q._name = 'q' - await Config(m) - raises(AttributeError, "a._requires = 'a'") - raises(AttributeError, "b._requires = 'b'") - raises(AttributeError, "c._requires = 'c'") - raises(AttributeError, "d._requires = 'd'") - raises(AttributeError, "e._requires = 'e'") - raises(AttributeError, "g._requires = 'g'") - raises(AttributeError, "h._requires = 'h'") - raises(AttributeError, "i._requires = 'i'") - raises(AttributeError, "j._requires = 'j'") - raises(AttributeError, "k._requires = 'k'") - raises(AttributeError, "l._requires = 'l'") - raises(AttributeError, "m._requires = 'm'") - raises(AttributeError, "o._requires = 'o'") - raises(AttributeError, "p._requires = 'p'") - raises(AttributeError, "q._requires = 'q'") + async with await Config(m) as cfg: + pass + with pytest.raises(AttributeError): + a._requires = 'a' + with pytest.raises(AttributeError): + b._requires = 'b' + with pytest.raises(AttributeError): + c._requires = 'c' + with pytest.raises(AttributeError): + d._requires = 'd' + with pytest.raises(AttributeError): + e._requires = 'e' + with pytest.raises(AttributeError): + g._requires = 'g' + with pytest.raises(AttributeError): + h._requires = 'h' + with pytest.raises(AttributeError): + i._requires = 'i' + with pytest.raises(AttributeError): + j._requires = 'j' + with pytest.raises(AttributeError): + k._requires = 'k' + with pytest.raises(AttributeError): + l._requires = 'l' + with pytest.raises(AttributeError): + m._requires = 'm' + with pytest.raises(AttributeError): + o._requires = 'o' + with pytest.raises(AttributeError): + p._requires = 'p' + with pytest.raises(AttributeError): + q._requires = 'q' + assert not await list_sessions() #def test_slots_description(): @@ -138,34 +166,43 @@ async def test_slots_option_readonly(): async def test_slots_config(): od1 = OptionDescription('a', '', []) od2 = OptionDescription('a', '', [od1]) - c = await Config(od2) - raises(AttributeError, "c._config_bag.context.x = 1") - raises(AttributeError, "c._config_bag.context.cfgimpl_x = 1") - option_bag = OptionBag() - option_bag.set_option(od2, - 'a', - ConfigBag(c._config_bag.context, None, None)) - sc = await c._config_bag.context.get_subconfig(option_bag) - assert isinstance(sc, SubConfig) - raises(AttributeError, "sc.x = 1") - raises(AttributeError, "sc.cfgimpl_x = 1") + async with await Config(od2) as c: + with pytest.raises(AttributeError): + c._config_bag.context.x = 1 + with pytest.raises(AttributeError): + c._config_bag.context.cfgimpl_x = 1 + option_bag = OptionBag() + option_bag.set_option(od2, + 'a', + ConfigBag(c._config_bag.context, None, None)) + sc = await c._config_bag.context.get_subconfig(option_bag) + assert isinstance(sc, SubConfig) + with pytest.raises(AttributeError): + sc.x = 1 + with pytest.raises(AttributeError): + sc.cfgimpl_x = 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_slots_setting(): od1 = OptionDescription('a', '', []) od2 = OptionDescription('a', '', [od1]) - c = await Config(od2) - s = c._config_bag.context.cfgimpl_get_settings() - s - raises(AttributeError, "s.x = 1") + async with await Config(od2) as c: + s = c._config_bag.context.cfgimpl_get_settings() + s + with pytest.raises(AttributeError): + s.x = 1 + assert not await list_sessions() @pytest.mark.asyncio async def test_slots_value(): od1 = OptionDescription('a', '', []) od2 = OptionDescription('a', '', [od1]) - c = await Config(od2) - v = c._config_bag.context.cfgimpl_get_values() - v - raises(AttributeError, "v.x = 1") + async with await Config(od2) as c: + v = c._config_bag.context.cfgimpl_get_values() + v + with pytest.raises(AttributeError): + v.x = 1 + assert not await list_sessions() diff --git a/tests/test_state.py b/tests/test_state.py index 01001df..0d09575 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -1,215 +1,12 @@ -#from autopath import do_autopath -#do_autopath() -# +from .autopath import do_autopath +do_autopath() from tiramisu import BoolOption, StrOption, SymLinkOption, OptionDescription, DynOptionDescription, \ Calculation, Params, ParamOption, ParamValue, calc_value, Config from pickle import dumps -from py.test import raises import pytest import sys, warnings from tiramisu.storage import list_sessions - - -def teardown_function(function): - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) - - -def _get_slots(opt): - slots = set() - for subclass in opt.__class__.__mro__: - if subclass is not object and '__slots__' in dir(subclass): - slots.update(subclass.__slots__) - return slots - - -def _no_state(opt): - for attr in _get_slots(opt): - if 'state' in attr: - try: - getattr(opt, attr) - except: - pass - else: - raise Exception('opt should have already attribute {0}'.format(attr)) - - -def _diff_opt(opt1, opt2): - attr1 = set(_get_slots(opt1)) - attr2 = set(_get_slots(opt2)) - diff1 = attr1 - attr2 - diff2 = attr2 - attr1 - if diff1 != set(): - raise Exception('more attribute in opt1 {0}'.format(list(diff1))) - if diff2 != set(): - raise Exception('more attribute in opt2 {0}'.format(list(diff2))) - for attr in attr1: - if attr in ['_cache_paths', '_cache_consistencies']: - continue - err1 = False - err2 = False - val1 = None - val2 = None - try: - val1 = getattr(opt1, attr) - msg1 = "exists" - tval = val1 - except: - err1 = True - msg1 = "not exists" - - try: - val2 = getattr(opt2, attr) - msg2 = "exists" - tval = val2 - except: - err2 = True - msg2 = "not exists" - - if not err1 == err2: - raise ValueError("{0} {1} before but {2} after for {3}: {4}".format(attr, msg1, msg2, opt1.impl_getname(), tval)) - if val1 is None: - assert val1 == val2 - elif attr == '_children': - assert val1[0] == val2[0] - for index, _opt in enumerate(val1[1]): - assert _opt._name == val2[1][index]._name - elif attr == '_requires': - if val1 == val2 == []: - pass - else: - for idx1, req1 in enumerate(val1): - for idx2, req2 in enumerate(val1[idx1]): - for idx3, req3 in enumerate(val1[idx1][idx2][0]): - assert val1[idx1][idx2][0][idx3][0].impl_getname() == val2[idx1][idx2][0][idx3][0].impl_getname() - assert val1[idx1][idx2][0][idx3][1] == val2[idx1][idx2][0][idx3][1] - assert val1[idx1][idx2][1:] == val2[idx1][idx2][1:], '{} - {}\n{} - {}'.format(val1, val2, val1[0][0][1:], val2[0][0][1:]) - elif attr == '_opt': - assert val1._name == val2._name - elif attr == '_consistencies': - # dict is only a cache - if isinstance(val1, list): - for index, consistency in enumerate(val1): - assert consistency[0] == val2[index][0] - for idx, opt in enumerate(consistency[1]): - assert opt._name == val2[index][1][idx]._name - elif attr == '_val_call': - for idx, v in enumerate(val1): - if v is None: - assert val2[idx] is None - else: - assert v[0] == val2[idx][0] - if len(v) == 2: - if v[1] is not None: - for key, values in v[1].items(): - for i, value in enumerate(values): - if isinstance(value, tuple) and value[0] is not None: - assert v[1][key][i][0].impl_getname() == val2[idx][1][key][i][0].impl_getname() - assert v[1][key][i][1] == val2[idx][1][key][i][1] - else: - assert v[1][key][i] == val2[idx][1][key][i] - else: - assert v[1] == val2[idx][1] - elif attr == '_leadership': - assert val1._p_._sm_get_leader().impl_getname() == val2._p_._sm_get_leader().impl_getname() - sval1 = [opt.impl_getname() for opt in val1._p_._sm_get_followers()] - sval2 = [opt.impl_getname() for opt in val2._p_._sm_get_followers()] - assert sval1 == sval2 - elif attr == '_subdyn': - try: - assert val1.impl_getname() == val2.impl_getname() - except AttributeError: - assert val1 == val2 - elif attr == '_dependencies': - assert len(val1) == len(val2), "_dependencies has not same len: {} - {}".format(val1, val2) - lst1 = [] - lst2 = [] - for idx, val in enumerate(val1): - if isinstance(val, Leadership): - lst1.append(val._p_.leader.impl_getname()) - else: - lst1.append(val.impl_getname()) - for idx, val in enumerate(val2): - if isinstance(val, Leadership): - lst2.append(val._p_.leader.impl_getname()) - else: - lst2.append(val.impl_getname()) - assert set(lst1) == set(lst2), '{} - {}'.format(lst1, lst2) - elif attr == '_cache_force_store_values': - for idx, tup in enumerate(val1): - assert tup[0] == val2[idx][0] - assert tup[1].impl_getname() == val2[idx][1].impl_getname() - elif attr in ['_extra', '_information']: - dico1 = {} - dico2 = {} - assert len(val1[0]) == len(val2[0]) - assert set(val1[0]) == set(val2[0]) - for idx, val in enumerate(val1[0]): - idx2 = val1[0].index(val) - assert val1[1][idx] == val1[1][idx2] - else: - #print(attr, val1, val2) - assert val1 == val2, "error for {}".format(attr) - - -def _diff_opts(opt1, opt2): - _diff_opt(opt1, opt2) - if isinstance(opt1, OptionDescription) or isinstance(opt1, DynOptionDescription): - children1 = set([opt.impl_getname() for opt in opt1.impl_getchildren(dyn=False)]) - children2 = set([opt.impl_getname() for opt in opt2.impl_getchildren(dyn=False)]) - diff1 = children1 - children2 - diff2 = children2 - children1 - if diff1 != set(): - raise Exception('more attribute in opt1 {0}'.format(list(diff1))) - if diff2 != set(): - raise Exception('more attribute in opt2 {0}'.format(list(diff2))) - for child in children1: - _diff_opts(opt1._getattr(child, dyn=False), opt2._getattr(child, dyn=False)) - - -def _diff_conf(cfg1, cfg2): - attr1 = set(_get_slots(cfg1)) - attr2 = set(_get_slots(cfg2)) - diff1 = attr1 - attr2 - diff2 = attr2 - attr1 - if diff1 != set(): - raise Exception('more attribute in cfg1 {0}'.format(list(diff1))) - if diff2 != set(): - raise Exception('more attribute in cfg2 {0}'.format(list(diff2))) - for attr in attr1: - if attr in ('_impl_context', '__weakref__'): - continue - err1 = False - err2 = False - val1 = None - val2 = None - try: - val1 = getattr(cfg1, attr) - except: - err1 = True - - try: - val2 = getattr(cfg2, attr) - except: - err2 = True - assert err1 == err2 - if val1 is None: - assert val1 == val2 - elif attr == '_impl_values': - assert cfg1.cfgimpl_get_values().get_modified_values() == cfg2.cfgimpl_get_values().get_modified_values() - elif attr == '_impl_settings': - assert cfg1.cfgimpl_get_settings().get_modified_properties() == cfg2.cfgimpl_get_settings().get_modified_properties() - assert cfg1.cfgimpl_get_settings().get_modified_permissives() == cfg2.cfgimpl_get_settings().get_modified_permissives() - elif attr == '_impl_descr': - _diff_opt(cfg1.cfgimpl_get_description(), cfg2.cfgimpl_get_description()) - elif attr == '_impl_children': - for index, _opt in enumerate(val1): - _diff_conf(_opt, val2[index]) - elif attr == '_impl_name': - #FIXME - pass - else: - assert val1 == val2 +from .config import event_loop def test_diff_opt(): @@ -224,7 +21,8 @@ def test_diff_opt(): o = OptionDescription('o', '', [b, u, s]) o1 = OptionDescription('o1', '', [o]) - raises(NotImplementedError, "dumps(o1)") + with pytest.raises(NotImplementedError): + dumps(o1) @pytest.mark.asyncio @@ -235,12 +33,15 @@ async def test_diff_information_config(): b.impl_set_information('info2', 'oh') o = OptionDescription('o', '', [b]) o1 = OptionDescription('o1', '', [o]) - d = await Config(o1) - c = d._config_bag.context - raises(NotImplementedError, "dumps(c)") + async with await Config(o1) as cfg: + c = cfg._config_bag.context + with pytest.raises(NotImplementedError): + dumps(c) + assert not await list_sessions() def test_only_optiondescription(): b = BoolOption('b', '') b - raises(NotImplementedError, "a = dumps(b)") + with pytest.raises(NotImplementedError): + dumps(b) diff --git a/tests/test_storage.py b/tests/test_storage.py index bda3814..25b49ca 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -9,150 +9,127 @@ from tiramisu.error import ConfigError from tiramisu import Config, BoolOption, OptionDescription, Leadership, \ list_sessions, delete_session, default_storage, MetaConfig from tiramisu.setting import groups, owners - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop @pytest.mark.asyncio async def test_non_persistent(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - await Config(o, session_id='test_non_persistent') + async with await Config(o, session_id='test_non_persistent', delete_old_session=True) as cfg: + pass + assert not await list_sessions() @pytest.mark.asyncio async def test_list(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - cfg = await Config(o, session_id='test_non_persistent') - await cfg.option('b').value.set(True) - assert 'test_non_persistent' in list_sessions() - del(cfg) - assert 'test_non_persistent' not in list_sessions() - - -@pytest.mark.asyncio -async def test_delete_not_persistent(): - b = BoolOption('b', '') - o = OptionDescription('od', '', [b]) - if not default_storage.is_persistent(): - cfg = await Config(o, session_id='not_test_persistent') - assert 'not_test_persistent' in list_sessions() - del cfg - assert 'not_test_persistent' not in list_sessions() - # - cfg = await Config(o, session_id='not_test_persistent') - raises(ValueError, "delete_session('not_test_persistent')") + async with await Config(o, session_id='test_non_persistent') as cfg: + await cfg.option('b').value.set(True) + assert 'test_non_persistent' in await list_sessions() + assert 'test_non_persistent' not in await list_sessions() + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - await Config(o, session_id='test_persistent', persistent=True) - delete_session('test_persistent') - - -@pytest.mark.asyncio -async def test_create_delete_not_persistent(): - b = BoolOption('b', '') - o = OptionDescription('od', '', [b]) - if not default_storage.is_persistent(): - raises(ValueError, "delete_session('test_persistent')") + await Config(o, session_id='test_persistent') + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_list_sessions_persistent(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.option('b').value.set(True) - assert 'test_persistent' in list_sessions() - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + await cfg.option('b').value.set(True) + assert 'test_persistent' in await list_sessions() + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_delete_session_persistent(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - await Config(o, session_id='test_persistent', persistent=True) - assert 'test_persistent' in list_sessions() - delete_session('test_persistent') - assert 'test_persistent' not in list_sessions() + await Config(o, session_id='test_persistent') + assert 'test_persistent' in await list_sessions() + await delete_session('test_persistent') + assert 'test_persistent' not in await list_sessions() + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent_retrieve(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.option('b').value.get() is None - await cfg.option('b').value.set(True) - assert await cfg.option('b').value.get() is True - del cfg - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.option('b').value.get() is True - assert 'test_persistent' in list_sessions() - delete_session(await cfg.config.name()) - del cfg - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.option('b').value.get() is None - delete_session(await cfg.config.name()) - del cfg + cfg = await Config(o, session_id='test_persistent') + assert await cfg.option('b').value.get() is None + await cfg.option('b').value.set(True) + assert await cfg.option('b').value.get() is True + del cfg + cfg = await Config(o, session_id='test_persistent') + assert await cfg.option('b').value.get() is True + assert 'test_persistent' in await list_sessions() + await delete_session(await cfg.session.id()) + del cfg + cfg = await Config(o, session_id='test_persistent') + assert await cfg.option('b').value.get() is None + await delete_session(await cfg.session.id()) + del cfg + assert not await list_sessions() @pytest.mark.asyncio async def test_two_persistent(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - cfg2 = await Config(o, session_id='test_persistent', persistent=True) - await cfg2.property.pop('cache') - assert await cfg.option('b').value.get() is None - assert await cfg2.option('b').value.get() is None - # - await cfg.option('b').value.set(False) - assert await cfg.option('b').value.get() is False - assert await cfg2.option('b').value.get() is False - # - await cfg.option('b').value.set(True) - assert await cfg.option('b').value.get() is True - assert await cfg2.option('b').value.get() is True - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + cfg2 = await Config(o, session_id='test_persistent') + await cfg2.property.pop('cache') + assert await cfg.option('b').value.get() is None + assert await cfg2.option('b').value.get() is None + # + await cfg.option('b').value.set(False) + assert await cfg.option('b').value.get() is False + assert await cfg2.option('b').value.get() is False + # + await cfg.option('b').value.set(True) + assert await cfg.option('b').value.get() is True + assert await cfg2.option('b').value.get() is True + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent_retrieve_owner(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.option('b').owner.isdefault() - await cfg.option('b').value.set(True) - assert await cfg.option('b').value.get() - assert await cfg.option('b').owner.get() == 'user' - ##owners.addowner('persistentowner') - await cfg.option('b').owner.set('persistentowner') - assert await cfg.option('b').owner.get() == 'persistentowner' - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.option('b').owner.set('persistentowner') - delete_session(await cfg.config.name()) - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.option('b').value.get() is None - assert await cfg.option('b').owner.isdefault() - delete_session(await cfg.config.name()) - del cfg + cfg = await Config(o, session_id='test_persistent') + assert await cfg.option('b').owner.isdefault() + await cfg.option('b').value.set(True) + assert await cfg.option('b').value.get() + assert await cfg.option('b').owner.get() == 'user' + ##owners.addowner('persistentowner') + await cfg.option('b').owner.set('persistentowner') + assert await cfg.option('b').owner.get() == 'persistentowner' + del cfg + # + cfg = await Config(o, session_id='test_persistent') + await cfg.option('b').owner.set('persistentowner') + await delete_session(await cfg.session.id()) + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert await cfg.option('b').value.get() is None + assert await cfg.option('b').owner.isdefault() + await delete_session(await cfg.session.id()) + del cfg + assert not await list_sessions() @pytest.mark.asyncio @@ -161,213 +138,196 @@ async def test_create_persistent_retrieve_owner_leadership(): b = BoolOption('b', '', multi=True) o = Leadership('a', '', [a, b]) o1 = OptionDescription('a', '', [o]) - if default_storage.is_persistent(): - cfg = await Config(o1, session_id='test_persistent', persistent=True) - assert await cfg.option('a.a').owner.isdefault() - await cfg.option('a.a').value.set([True, False]) - await cfg.option('a.b', 1).value.set(True) - assert await cfg.option('a.a').owner.get() == 'user' - assert await cfg.option('a.b', 0).owner.isdefault() - assert await cfg.option('a.b', 1).owner.get() == 'user' - #owners.addowner('persistentowner2') - await cfg.option('a.b', 1).owner.set('persistentowner2') - await cfg.option('a.b', 0).value.set(True) - assert await cfg.option('a.b', 0).owner.get() == 'user' - assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2' - assert await cfg.option('a.a').value.get() == [True, False] - del cfg - # - cfg = await Config(o1, session_id='test_persistent', persistent=True) - assert await cfg.option('a.a').value.get() == [True, False] - assert await cfg.option('a.b', 0).owner.get() == 'user' - assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2' - delete_session(await cfg.config.name()) - del cfg - # - cfg = await Config(o1, session_id='test_persistent', persistent=True) - assert await cfg.option('a.a').value.get() == [] - delete_session(await cfg.config.name()) - del cfg + cfg = await Config(o1, session_id='test_persistent') + assert await cfg.option('a.a').owner.isdefault() + await cfg.option('a.a').value.set([True, False]) + await cfg.option('a.b', 1).value.set(True) + assert await cfg.option('a.a').owner.get() == 'user' + assert await cfg.option('a.b', 0).owner.isdefault() + assert await cfg.option('a.b', 1).owner.get() == 'user' + #owners.addowner('persistentowner2') + await cfg.option('a.b', 1).owner.set('persistentowner2') + await cfg.option('a.b', 0).value.set(True) + assert await cfg.option('a.b', 0).owner.get() == 'user' + assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2' + assert await cfg.option('a.a').value.get() == [True, False] + del cfg + # + cfg = await Config(o1, session_id='test_persistent') + assert await cfg.option('a.a').value.get() == [True, False] + assert await cfg.option('a.b', 0).owner.get() == 'user' + assert await cfg.option('a.b', 1).owner.get() == 'persistentowner2' + await delete_session(await cfg.session.id()) + del cfg + # + cfg = await Config(o1, session_id='test_persistent') + assert await cfg.option('a.a').value.get() == [] + await delete_session(await cfg.session.id()) + del cfg + assert not await list_sessions() @pytest.mark.asyncio async def test_two_persistent_owner(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.property.pop('cache') - cfg2 = await Config(o, session_id='test_persistent', persistent=True) - await cfg2.property.pop('cache') - assert await cfg.option('b').owner.isdefault() - assert await cfg2.option('b').owner.isdefault() - await cfg.option('b').value.set(False) - assert await cfg.option('b').owner.get() == 'user' - assert await cfg2.option('b').owner.get() == 'user' - await cfg.option('b').owner.set('persistent') - assert await cfg.option('b').owner.get() == 'persistent' - assert await cfg2.option('b').owner.get() == 'persistent' - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + await cfg.property.pop('cache') + cfg2 = await Config(o, session_id='test_persistent') + await cfg2.property.pop('cache') + assert await cfg.option('b').owner.isdefault() + assert await cfg2.option('b').owner.isdefault() + await cfg.option('b').value.set(False) + assert await cfg.option('b').owner.get() == 'user' + assert await cfg2.option('b').owner.get() == 'user' + await cfg.option('b').owner.set('persistent') + assert await cfg.option('b').owner.get() == 'persistent' + assert await cfg2.option('b').owner.get() == 'persistent' + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent_retrieve_information(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.information.set('info', 'string') - assert await cfg.information.get('info') == 'string' - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.information.get('info') == 'string' - delete_session(await cfg.config.name()) - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.information.get('info', None) is None - delete_session(await cfg.config.name()) - del cfg + cfg = await Config(o, session_id='test_persistent') + await cfg.information.set('info', 'string') + assert await cfg.information.get('info') == 'string' + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert await cfg.information.get('info') == 'string' + await delete_session(await cfg.session.id()) + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert await cfg.information.get('info', None) is None + await delete_session(await cfg.session.id()) + del cfg + assert not await list_sessions() @pytest.mark.asyncio async def test_two_persistent_information(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.property.pop('cache') - await cfg.information.set('info', 'string') - assert await cfg.information.get('info') == 'string' - cfg2 = await Config(o, session_id='test_persistent', persistent=True) - await cfg2.property.pop('cache') - assert await cfg2.information.get('info') == 'string' - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + await cfg.property.pop('cache') + await cfg.information.set('info', 'string') + assert await cfg.information.get('info') == 'string' + cfg2 = await Config(o, session_id='test_persistent') + await cfg2.property.pop('cache') + assert await cfg2.information.get('info') == 'string' + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_two_different_persistents(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.property.pop('cache') - cfg2 = await Config(o, session_id='test_persistent2', persistent=True) - await cfg2.property.pop('cache') - await cfg.option('b').property.add('test') - assert await cfg.option('b').property.get() == {'test'} - assert await cfg2.option('b').property.get() == set() - assert await cfg.option('b').value.get() is None - assert await cfg2.option('b').value.get() is None - await cfg.option('b').value.set(True) - assert await cfg.option('b').value.get() == True - assert await cfg2.option('b').value.get() is None + cfg = await Config(o, session_id='test_persistent') + await cfg.property.pop('cache') + cfg2 = await Config(o, session_id='test_persistent2') + await cfg2.property.pop('cache') + await cfg.option('b').property.add('test') + assert await cfg.option('b').property.get() == {'test'} + assert await cfg2.option('b').property.get() == set() + assert await cfg.option('b').value.get() is None + assert await cfg2.option('b').value.get() is None + await cfg.option('b').value.set(True) + assert await cfg.option('b').value.get() == True + assert await cfg2.option('b').value.get() is None - delete_session('test_persistent') - delete_session('test_persistent2') + await delete_session('test_persistent') + await delete_session('test_persistent2') + assert not await list_sessions() @pytest.mark.asyncio async def test_two_different_information(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.information.set('a', 'a') - cfg2 = await Config(o, session_id='test_persistent2', persistent=True) - await cfg2.information.set('a', 'b') - assert await cfg.information.get('a') == 'a' - assert await cfg2.information.get('a') == 'b' + cfg = await Config(o, session_id='test_persistent') + await cfg.information.set('a', 'a') + cfg2 = await Config(o, session_id='test_persistent2') + await cfg2.information.set('a', 'b') + assert await cfg.information.get('a') == 'a' + assert await cfg2.information.get('a') == 'b' - delete_session('test_persistent') - delete_session('test_persistent2') + await delete_session('test_persistent') + await delete_session('test_persistent2') + assert not await list_sessions() @pytest.mark.asyncio async def test_exportation_importation(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - cfg2 = await Config(o, session_id='test_persistent2', persistent=True) - cfg3 = await Config(o, session_id='test_persistent3', persistent=True) - await cfg.owner.set('export') - assert await cfg.option('b').value.get() is None - await cfg.option('b').value.set(True) - assert await cfg.option('b').value.get() is True - assert await cfg.owner.get() == 'export' - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert await cfg.owner.get() == 'export' - assert await cfg.value.exportation() == [['b'], [None], [True], ['export']] - await cfg2.value.importation(await cfg.value.exportation()) - assert await cfg.value.exportation() == [['b'], [None], [True], ['export']] - assert await cfg.owner.get() == 'export' - assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']] - assert await cfg2.owner.get() == 'user' - del cfg2 - # - cfg2 = await Config(o, session_id='test_persistent2', persistent=True) - assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']] - assert await cfg2.owner.get() == 'user' - # - await cfg3.value.importation(await cfg.value.exportation(with_default_owner=True)) - assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']] - assert await cfg3.owner.get() == 'export' - del cfg3 - # - cfg3 = await Config(o, session_id='test_persistent3', persistent=True) - assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']] - assert await cfg3.owner.get() == 'export' - # - delete_session('test_persistent') - delete_session('test_persistent2') - delete_session('test_persistent3') + cfg = await Config(o, session_id='test_persistent') + cfg2 = await Config(o, session_id='test_persistent2') + cfg3 = await Config(o, session_id='test_persistent3') + await cfg.owner.set('export') + assert await cfg.option('b').value.get() is None + await cfg.option('b').value.set(True) + assert await cfg.option('b').value.get() is True + assert await cfg.owner.get() == 'export' + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert await cfg.owner.get() == 'export' + assert await cfg.value.exportation() == [['b'], [None], [True], ['export']] + await cfg2.value.importation(await cfg.value.exportation()) + assert await cfg.value.exportation() == [['b'], [None], [True], ['export']] + assert await cfg.owner.get() == 'export' + assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']] + assert await cfg2.owner.get() == 'user' + del cfg2 + # + cfg2 = await Config(o, session_id='test_persistent2') + assert await cfg2.value.exportation() == [['b'], [None], [True], ['export']] + assert await cfg2.owner.get() == 'user' + # + await cfg3.value.importation(await cfg.value.exportation(with_default_owner=True)) + assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']] + assert await cfg3.owner.get() == 'export' + del cfg3 + # + cfg3 = await Config(o, session_id='test_persistent3') + assert await cfg3.value.exportation() == [['b'], [None], [True], ['export']] + assert await cfg3.owner.get() == 'export' + # + await delete_session('test_persistent') + await delete_session('test_persistent2') + await delete_session('test_persistent3') + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent_context_property(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.property.add('persistent') - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert 'persistent' in await cfg.property.get() - del cfg - delete_session('test_persistent') - - -@pytest.mark.asyncio -async def test_create_persistent_context_property_metaconfig(): - b = BoolOption('b', '') - o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.property.add('persistent') - del cfg - # - meta = await MetaConfig([], optiondescription=o) - cfg = await meta.config.new(session_id='test_persistent', persistent=True) - assert 'persistent' in await cfg.property.get() - del cfg - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + await cfg.property.add('persistent') + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert 'persistent' in await cfg.property.get() + del cfg + await delete_session('test_persistent') + assert not await list_sessions() @pytest.mark.asyncio async def test_create_persistent_property(): b = BoolOption('b', '') o = OptionDescription('od', '', [b]) - if default_storage.is_persistent(): - cfg = await Config(o, session_id='test_persistent', persistent=True) - await cfg.option('b').property.add('persistent') - del cfg - # - cfg = await Config(o, session_id='test_persistent', persistent=True) - assert 'persistent' in await cfg.option('b').property.get() - del cfg - delete_session('test_persistent') + cfg = await Config(o, session_id='test_persistent') + await cfg.option('b').property.add('persistent') + del cfg + # + cfg = await Config(o, session_id='test_persistent') + assert 'persistent' in await cfg.option('b').property.get() + del cfg + await delete_session('test_persistent') diff --git a/tests/test_submulti.py b/tests/test_submulti.py index 7ce7abf..2479aaf 100644 --- a/tests/test_submulti.py +++ b/tests/test_submulti.py @@ -1,7 +1,6 @@ # coding: utf-8 from .autopath import do_autopath do_autopath() -from py.test import raises import pytest import warnings @@ -12,11 +11,7 @@ from tiramisu import StrOption, IntOption, OptionDescription, submulti, Leadersh MetaConfig, undefined, Params, ParamOption, Calculation from tiramisu.error import LeadershipError from tiramisu.storage import list_sessions - - -def teardown_function(function): - with warnings.catch_warnings(record=True) as w: - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop def return_val(val=None): @@ -36,7 +31,8 @@ def return_list2(value=None): @pytest.mark.asyncio async def test_unknown_multi(): - raises(ValueError, "StrOption('multi', '', multi='unknown')") + with pytest.raises(ValueError): + StrOption('multi', '', multi='unknown') @pytest.mark.asyncio @@ -49,20 +45,22 @@ async def test_submulti(): multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) od = OptionDescription('od', '', [multi, multi2, multi3]) - cfg = await Config(od) - assert await cfg.option('multi').option.ismulti() - assert await cfg.option('multi').option.issubmulti() - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi3').value.get() == [['yes']] - assert await cfg.option('multi').owner.get() == owners.default + async with await Config(od) as cfg: + assert await cfg.option('multi').option.ismulti() + assert await cfg.option('multi').option.issubmulti() + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi3').value.get() == [['yes']] + assert await cfg.option('multi').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio async def test_submulti_default_multi_not_list(): - raises(ValueError, "StrOption('multi2', '', default_multi='yes', multi=submulti)") + with pytest.raises(ValueError): + StrOption('multi2', '', default_multi='yes', multi=submulti) @pytest.mark.asyncio @@ -75,31 +73,32 @@ async def test_append_submulti(): multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) od = OptionDescription('od', '', [multi, multi2, multi3]) - cfg = await Config(od) - owner = await cfg.owner.get() - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi').owner.get() == owners.default - await cfg.option('multi').value.set([undefined]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi').value.get() == [[]] - await cfg.option('multi').value.set([undefined, ['no']]) - assert await cfg.option('multi').value.get() == [[], ['no']] - # - assert await cfg.option('multi2').value.get() == [] - assert await cfg.option('multi2').owner.get() == owners.default - await cfg.option('multi2').value.set([undefined]) - assert await cfg.option('multi2').owner.get() == owner - assert await cfg.option('multi2').value.get() == [['yes']] - await cfg.option('multi2').value.set([undefined, ['no']]) - assert await cfg.option('multi2').value.get() == [['yes'], ['no']] - # - assert await cfg.option('multi3').value.get() == [['yes']] - assert await cfg.option('multi3').owner.get() == owners.default - await cfg.option('multi3').value.set([undefined, undefined]) - assert await cfg.option('multi3').owner.get() == owner - assert await cfg.option('multi3').value.get() == [['yes'], []] - await cfg.option('multi3').value.set([undefined, undefined, ['no']]) - assert await cfg.option('multi3').value.get() == [['yes'], [], ['no']] + async with await Config(od) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi').owner.get() == owners.default + await cfg.option('multi').value.set([undefined]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi').value.get() == [[]] + await cfg.option('multi').value.set([undefined, ['no']]) + assert await cfg.option('multi').value.get() == [[], ['no']] + # + assert await cfg.option('multi2').value.get() == [] + assert await cfg.option('multi2').owner.get() == owners.default + await cfg.option('multi2').value.set([undefined]) + assert await cfg.option('multi2').owner.get() == owner + assert await cfg.option('multi2').value.get() == [['yes']] + await cfg.option('multi2').value.set([undefined, ['no']]) + assert await cfg.option('multi2').value.get() == [['yes'], ['no']] + # + assert await cfg.option('multi3').value.get() == [['yes']] + assert await cfg.option('multi3').owner.get() == owners.default + await cfg.option('multi3').value.set([undefined, undefined]) + assert await cfg.option('multi3').owner.get() == owner + assert await cfg.option('multi3').value.get() == [['yes'], []] + await cfg.option('multi3').value.set([undefined, undefined, ['no']]) + assert await cfg.option('multi3').value.get() == [['yes'], [], ['no']] + assert not await list_sessions() @pytest.mark.asyncio @@ -112,26 +111,27 @@ async def test_append_unvalide_submulti(): multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) od = OptionDescription('od', '', [multi, multi2, multi3]) - cfg = await Config(od) - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi').owner.get() == owners.default - with pytest.raises(ValueError): - await cfg.option('multi').value.set([[1]]) - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi').owner.get() == owners.default - # - assert await cfg.option('multi2').value.get() == [] - with pytest.raises(ValueError): - await cfg.option('multi2').value.set(['no']) - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi2').value.get() == [] - # - assert await cfg.option('multi3').value.get() == [['yes']] - assert await cfg.option('multi3').owner.get() == owners.default - with pytest.raises(ValueError): - await cfg.option('multi3').value.set([[1]]) - assert await cfg.option('multi3').value.get() == [['yes']] - assert await cfg.option('multi3').owner.get() == owners.default + async with await Config(od) as cfg: + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi').owner.get() == owners.default + with pytest.raises(ValueError): + await cfg.option('multi').value.set([[1]]) + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi').owner.get() == owners.default + # + assert await cfg.option('multi2').value.get() == [] + with pytest.raises(ValueError): + await cfg.option('multi2').value.set(['no']) + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi2').value.get() == [] + # + assert await cfg.option('multi3').value.get() == [['yes']] + assert await cfg.option('multi3').owner.get() == owners.default + with pytest.raises(ValueError): + await cfg.option('multi3').value.set([[1]]) + assert await cfg.option('multi3').value.get() == [['yes']] + assert await cfg.option('multi3').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio @@ -144,74 +144,78 @@ async def test_pop_submulti(): multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti) multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti) od = OptionDescription('od', '', [multi, multi2, multi3]) - cfg = await Config(od) - owner = await cfg.owner.get() - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi3').owner.get() == owners.default - await cfg.option('multi').value.set([['no', 'yes'], ['peharps']]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi').value.get() == [['no', 'yes'], ['peharps']] - # - assert await cfg.option('multi3').value.get() == [['yes']] - assert await cfg.option('multi3').owner.get() == owners.default - await cfg.option('multi3').value.set([]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi3').value.get() == [] - await cfg.option('multi3').value.reset() - assert await cfg.option('multi3').owner.get() == owners.default - await cfg.option('multi3').value.set([[]]) - assert await cfg.option('multi3').owner.get() == owner - assert await cfg.option('multi3').value.get() == [[]] + async with await Config(od) as cfg: + owner = await cfg.owner.get() + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi3').owner.get() == owners.default + await cfg.option('multi').value.set([['no', 'yes'], ['peharps']]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi').value.get() == [['no', 'yes'], ['peharps']] + # + assert await cfg.option('multi3').value.get() == [['yes']] + assert await cfg.option('multi3').owner.get() == owners.default + await cfg.option('multi3').value.set([]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi3').value.get() == [] + await cfg.option('multi3').value.reset() + assert await cfg.option('multi3').owner.get() == owners.default + await cfg.option('multi3').value.set([[]]) + assert await cfg.option('multi3').owner.get() == owner + assert await cfg.option('multi3').value.get() == [[]] + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_submulti_str(): multi = StrOption('multi', '', [[Calculation(return_val)]], multi=submulti, default_multi=[Calculation(return_val)]) od = OptionDescription('od', '', [multi]) - cfg = await Config(od) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi').value.get() == [['val']] - await cfg.option('multi').value.set([['val'], undefined]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi').value.get() == [['val'], ['val']] - await cfg.option('multi').value.reset() - assert await cfg.option('multi').owner.get() == owners.default + async with await Config(od) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi').value.get() == [['val']] + await cfg.option('multi').value.set([['val'], undefined]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi').value.get() == [['val'], ['val']] + await cfg.option('multi').value.reset() + assert await cfg.option('multi').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_submulti_list(): multi = StrOption('multi', '', [Calculation(return_list)], multi=submulti, default_multi=Calculation(return_list), properties=('notunique',)) od = OptionDescription('od', '', [multi]) - cfg = await Config(od) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert await cfg.option('multi').value.get() == [['val', 'val']] - assert await cfg.option('multi').owner.get() == owners.default - await cfg.option('multi').value.set([['val', 'val'], undefined]) - #assert await cfg.option('multi').owner.get() == owner - #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val']] - #await cfg.option('multi').value.set([['val', 'val'], undefined, undefined]) - #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']] - #await cfg.option('multi').value.reset() - #assert await cfg.option('multi').owner.get() == owners.default + async with await Config(od) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert await cfg.option('multi').value.get() == [['val', 'val']] + assert await cfg.option('multi').owner.get() == owners.default + await cfg.option('multi').value.set([['val', 'val'], undefined]) + #assert await cfg.option('multi').owner.get() == owner + #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val']] + #await cfg.option('multi').value.set([['val', 'val'], undefined, undefined]) + #assert await cfg.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']] + #await cfg.option('multi').value.reset() + #assert await cfg.option('multi').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio async def test_callback_submulti_list_list(): multi = StrOption('multi', '', Calculation(return_list2), multi=submulti, properties=('notunique',)) od = OptionDescription('od', '', [multi]) - cfg = await Config(od) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert await cfg.option('multi').value.get() == [['val', 'val']] - assert await cfg.option('multi').owner.get() == owners.default - await cfg.option('multi').value.set([['val', 'val'], undefined]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi').value.get() == [['val', 'val'], []] - await cfg.option('multi').value.reset() - assert await cfg.option('multi').owner.get() == owners.default + async with await Config(od) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert await cfg.option('multi').value.get() == [['val', 'val']] + assert await cfg.option('multi').owner.get() == owners.default + await cfg.option('multi').value.set([['val', 'val'], undefined]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi').value.get() == [['val', 'val'], []] + await cfg.option('multi').value.reset() + assert await cfg.option('multi').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio @@ -228,8 +232,10 @@ async def test_groups_with_leader_in_config_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) od = OptionDescription('root', '', [interface1]) - await Config(od) + async with await Config(od) as cfg: + pass assert interface1.impl_get_group_type() == groups.leadership + assert not await list_sessions() @pytest.mark.asyncio @@ -238,26 +244,27 @@ async def test_values_with_leader_and_followers_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert interface1.impl_get_group_type() == groups.leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] - with pytest.raises(ValueError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') - with pytest.raises(ValueError): - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']]) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert interface1.impl_get_group_type() == groups.leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"]) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == [] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] + with pytest.raises(ValueError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0') + with pytest.raises(ValueError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']]) + assert not await list_sessions() @pytest.mark.asyncio @@ -266,25 +273,26 @@ async def test_reset_values_with_leader_and_followers_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert interface1.impl_get_group_type() == groups.leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] - # - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert interface1.impl_get_group_type() == groups.leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + # + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -293,19 +301,20 @@ async def test_values_with_leader_and_followers_follower_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - with pytest.raises(LeadershipError): + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + with pytest.raises(LeadershipError): + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0', '255.255.255.0']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0', '255.255.255.0']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == [] + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + assert not await list_sessions() @pytest.mark.asyncio @@ -314,19 +323,20 @@ async def test_values_with_leader_and_leadership_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"]) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0']) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0'] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"]) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"]) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0']) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0'] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0'] + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [] + assert not await list_sessions() @pytest.mark.asyncio @@ -335,15 +345,16 @@ async def test_values_with_leader_owner_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.reset() + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default + assert not await list_sessions() @pytest.mark.asyncio @@ -352,24 +363,25 @@ async def test_values_with_leader_disabled_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=submulti) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() - await cfg.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset() + await cfg.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145']) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(1) + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) - #delete with value in disabled var - await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) - await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + #delete with value in disabled var + await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145']) + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145']) + await cfg.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled') + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.pop(0) + assert not await list_sessions() @pytest.mark.asyncio @@ -378,23 +390,24 @@ async def test_leader_is_submulti(): netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-rĂ©seau", multi=True) interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) maconfig = OptionDescription('toto', '', [interface1]) - cfg = await Config(maconfig) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert interface1.impl_get_group_type() == groups.leadership - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"]]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]] - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]]) - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]) - assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]] - with pytest.raises(ValueError): - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1']) + async with await Config(maconfig) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert interface1.impl_get_group_type() == groups.leadership + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"]]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]] + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault() + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]]) + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]) + assert await cfg.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]] + with pytest.raises(ValueError): + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1']) + assert not await list_sessions() @pytest.mark.asyncio @@ -402,53 +415,56 @@ async def test_callback_submulti(): multi = StrOption('multi', '', multi=submulti) multi2 = StrOption('multi2', '', Calculation(return_val, Params(ParamOption(multi))), multi=submulti) od = OptionDescription('multi', '', [multi, multi2]) - cfg = await Config(od) - await cfg.property.read_write() - owner = await cfg.owner.get() - assert await cfg.option('multi').owner.get() == owners.default - assert await cfg.option('multi').value.get() == [] - assert await cfg.option('multi2').value.get() == [] - await cfg.option('multi').value.set([['val']]) - assert await cfg.option('multi').owner.get() == owner - assert await cfg.option('multi2').owner.get() == owners.default - assert await cfg.option('multi').value.get() == [['val']] - assert await cfg.option('multi2').value.get() == [['val']] + async with await Config(od) as cfg: + await cfg.property.read_write() + owner = await cfg.owner.get() + assert await cfg.option('multi').owner.get() == owners.default + assert await cfg.option('multi').value.get() == [] + assert await cfg.option('multi2').value.get() == [] + await cfg.option('multi').value.set([['val']]) + assert await cfg.option('multi').owner.get() == owner + assert await cfg.option('multi2').owner.get() == owners.default + assert await cfg.option('multi').value.get() == [['val']] + assert await cfg.option('multi2').value.get() == [['val']] + assert not await list_sessions() @pytest.mark.asyncio async def test_submulti_unique(): i = IntOption('int', '', multi=submulti, properties=('unique',)) o = OptionDescription('od', '', [i]) - cfg = await Config(o) - assert await cfg.option('int').value.get() == [] - await cfg.option('int').value.set([[0]]) - assert await cfg.option('int').value.get() == [[0]] - with pytest.raises(ValueError): - await cfg.option('int').value.set([[0, 0]]) - await cfg.option('int').value.set([[0], [0]]) - with pytest.raises(ValueError): - await cfg.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]]) - await cfg.option('int').value.set([[0, 4, 5, 6], [0]]) + async with await Config(o) as cfg: + assert await cfg.option('int').value.get() == [] + await cfg.option('int').value.set([[0]]) + assert await cfg.option('int').value.get() == [[0]] + with pytest.raises(ValueError): + await cfg.option('int').value.set([[0, 0]]) + await cfg.option('int').value.set([[0], [0]]) + with pytest.raises(ValueError): + await cfg.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]]) + await cfg.option('int').value.set([[0, 4, 5, 6], [0]]) + assert not await list_sessions() @pytest.mark.asyncio async def test_multi_submulti_meta(): multi = StrOption('multi', '', multi=submulti) od = OptionDescription('od', '', [multi]) - cfg = await Config(od, session_id='cfg') - await cfg.property.read_write() - cfg2 = await Config(od, session_id='cfg2') - await cfg2.property.read_write() - meta = await MetaConfig([cfg, cfg2]) - await meta.property.read_write() - await meta.option('multi').value.set([['val']]) - assert await meta.option('multi').value.get() == [['val']] - newcfg = await meta.config('cfg') - await newcfg.option('multi').value.set([['val', None]]) - assert await cfg.option('multi').value.get() == [['val', None]] - newcfg = await meta.config('cfg') - assert await newcfg.option('multi').value.get() == [['val', None]] - assert await meta.option('multi').value.get() == [['val']] + async with await Config(od, session_id='cfg') as cfg: + await cfg.property.read_write() + async with await Config(od, session_id='cfg2') as cfg2: + await cfg2.property.read_write() + async with await MetaConfig([cfg, cfg2]) as meta: + await meta.property.read_write() + await meta.option('multi').value.set([['val']]) + assert await meta.option('multi').value.get() == [['val']] + newcfg = await meta.config('cfg') + await newcfg.option('multi').value.set([['val', None]]) + assert await cfg.option('multi').value.get() == [['val', None]] + newcfg = await meta.config('cfg') + assert await newcfg.option('multi').value.get() == [['val', None]] + assert await meta.option('multi').value.get() == [['val']] + assert not await list_sessions() @pytest.mark.asyncio @@ -456,18 +472,19 @@ async def test_multi_submulti_meta_no_cache(): multi = StrOption('multi', '', multi=submulti) multi = StrOption('multi', '', multi=submulti) od = OptionDescription('od', '', [multi]) - cfg = await Config(od, session_id='cfg') - await cfg.property.read_write() - cfg2 = await Config(od, session_id='cfg2') - await cfg.property.read_write() - meta = await MetaConfig([cfg, cfg2]) - await meta.property.read_write() - await meta.property.pop('cache') - await meta.option('multi').value.set([['val']]) - assert await meta.option('multi').value.get() == [['val']] - newcfg = await meta.config('cfg') - await newcfg.option('multi').value.set([['val', None]]) - assert await cfg.option('multi').value.get() == [['val', None]] - newcfg = await meta.config('cfg') - assert await newcfg.option('multi').value.get() == [['val', None]] - assert await meta.option('multi').value.get() == [['val']] + async with await Config(od, session_id='cfg') as cfg: + await cfg.property.read_write() + async with await Config(od, session_id='cfg2') as cfg2: + await cfg.property.read_write() + async with await MetaConfig([cfg, cfg2]) as meta: + await meta.property.read_write() + await meta.property.pop('cache') + await meta.option('multi').value.set([['val']]) + assert await meta.option('multi').value.get() == [['val']] + newcfg = await meta.config('cfg') + await newcfg.option('multi').value.set([['val', None]]) + assert await cfg.option('multi').value.get() == [['val', None]] + newcfg = await meta.config('cfg') + assert await newcfg.option('multi').value.get() == [['val', None]] + assert await meta.option('multi').value.get() == [['val']] + assert not await list_sessions() diff --git a/tests/test_symlink.py b/tests/test_symlink.py index 59ff586..fe8a1de 100644 --- a/tests/test_symlink.py +++ b/tests/test_symlink.py @@ -9,10 +9,7 @@ from tiramisu import BoolOption, StrOption, SymLinkOption, \ from tiramisu.error import PropertiesOptionError, ConfigError from tiramisu.setting import groups, owners from tiramisu.storage import list_sessions - - -def teardown_function(function): - assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__) +from .config import event_loop def return_value(): @@ -26,19 +23,20 @@ async def test_symlink_option(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('s1.b').value.get() is False - await cfg.option("s1.b").value.set(True) - await cfg.option("s1.b").value.set(False) - assert await cfg.option('s1.b').value.get() is False - assert await cfg.option('c').value.get() is False - await cfg.option('s1.b').value.set(True) - assert await cfg.option('s1.b').value.get() is True - assert await cfg.option('c').value.get() is True - await cfg.option('s1.b').value.set(False) - assert await cfg.option('s1.b').value.get() is False - assert await cfg.option('c').value.get() is False + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('s1.b').value.get() is False + await cfg.option("s1.b").value.set(True) + await cfg.option("s1.b").value.set(False) + assert await cfg.option('s1.b').value.get() is False + assert await cfg.option('c').value.get() is False + await cfg.option('s1.b').value.set(True) + assert await cfg.option('s1.b').value.get() is True + assert await cfg.option('c').value.get() is True + await cfg.option('s1.b').value.set(False) + assert await cfg.option('s1.b').value.get() is False + assert await cfg.option('c').value.get() is False + assert not await list_sessions() @pytest.mark.asyncio @@ -47,10 +45,11 @@ async def test_symlink_assign_option(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - with pytest.raises(ConfigError): - await cfg.option('c').value.set(True) + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + with pytest.raises(ConfigError): + await cfg.option('c').value.set(True) + assert not await list_sessions() @pytest.mark.asyncio @@ -59,10 +58,11 @@ async def test_symlink_del_option(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - with pytest.raises(ConfigError): - await cfg.option('c').value.reset() + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + with pytest.raises(ConfigError): + await cfg.option('c').value.reset() + assert not await list_sessions() @pytest.mark.asyncio @@ -70,16 +70,17 @@ async def test_symlink_addproperties(): boolopt = BoolOption('b', '', default=True, properties=('test',)) linkopt = SymLinkOption("c", boolopt) descr = OptionDescription('opt', '', [boolopt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - with pytest.raises(TypeError): - await cfg.option('c').property.add('new') - try: - await cfg.option('c').property.reset() - except AssertionError: - pass - else: - raise Exception('must raise') + async with await Config(descr) as cfg: + await cfg.property.read_write() + with pytest.raises(TypeError): + await cfg.option('c').property.add('new') + try: + await cfg.option('c').property.reset() + except AssertionError: + pass + else: + raise Exception('must raise') + assert not await list_sessions() @pytest.mark.asyncio @@ -87,10 +88,11 @@ async def test_symlink_getpermissive(): boolopt = BoolOption('b', '', default=True, properties=('test',)) linkopt = SymLinkOption("c", boolopt) descr = OptionDescription('opt', '', [boolopt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - await cfg.option('b').permissive.set(frozenset(['perm'])) - await cfg.option('c').permissive.get() == frozenset(['perm']) + async with await Config(descr) as cfg: + await cfg.property.read_write() + await cfg.option('b').permissive.set(frozenset(['perm'])) + await cfg.option('c').permissive.get() == frozenset(['perm']) + assert not await list_sessions() @pytest.mark.asyncio @@ -98,16 +100,17 @@ async def test_symlink_addpermissives(): boolopt = BoolOption('b', '', default=True, properties=('test',)) linkopt = SymLinkOption("c", boolopt) descr = OptionDescription('opt', '', [boolopt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - with pytest.raises(TypeError): - await cfg.option('c').permissive.set(frozenset(['new'])) - try: - await cfg.option('c').permissive.reset() - except AssertionError: - pass - else: - raise Exception('must raise') + async with await Config(descr) as cfg: + await cfg.property.read_write() + with pytest.raises(TypeError): + await cfg.option('c').permissive.set(frozenset(['new'])) + try: + await cfg.option('c').permissive.reset() + except AssertionError: + pass + else: + raise Exception('must raise') + assert not await list_sessions() @pytest.mark.asyncio @@ -115,10 +118,11 @@ async def test_symlink_getproperties(): boolopt = BoolOption('b', '', default=True, properties=('test',)) linkopt = SymLinkOption("c", boolopt) descr = OptionDescription('opt', '', [boolopt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == {'test'} - assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False + async with await Config(descr) as cfg: + await cfg.property.read_write() + assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == {'test'} + assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False + assert not await list_sessions() @pytest.mark.asyncio @@ -126,11 +130,12 @@ async def test_symlink_getcallback(): boolopt = BoolOption('b', '', Calculation(return_value)) linkopt = SymLinkOption("c", boolopt) descr = OptionDescription('opt', '', [boolopt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - #assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == True - #assert boolopt.impl_get_callback() == linkopt.impl_get_callback() == (return_value, None) - assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False + async with await Config(descr) as cfg: + await cfg.property.read_write() + #assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == True + #assert boolopt.impl_get_callback() == linkopt.impl_get_callback() == (return_value, None) + assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False + assert not await list_sessions() @pytest.mark.asyncio @@ -143,27 +148,28 @@ async def test_symlink_requires(config_type): stropt = StrOption('s', '', properties=(disabled_property,)) linkopt = SymLinkOption("c", stropt) descr = OptionDescription('opt', '', [boolopt, stropt, linkopt]) - cfg = await Config(descr) - await cfg.property.read_write() - cfg = await get_config(cfg, config_type) - assert await cfg.option('b').value.get() is True - assert await cfg.option('s').value.get() is None - assert await cfg.option('c').value.get() is None - await cfg.option('b').value.set(False) - # - props = [] - try: - await cfg.option('s').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert props == {'disabled'} - # - props = [] - try: - await cfg.option('c').value.get() - except PropertiesOptionError as err: - props = err.proptype - assert props == {'disabled'} + async with await Config(descr) as cfg: + await cfg.property.read_write() + cfg = await get_config(cfg, config_type) + assert await cfg.option('b').value.get() is True + assert await cfg.option('s').value.get() is None + assert await cfg.option('c').value.get() is None + await cfg.option('b').value.set(False) + # + props = [] + try: + await cfg.option('s').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert props == {'disabled'} + # + props = [] + try: + await cfg.option('c').value.get() + except PropertiesOptionError as err: + props = err.proptype + assert props == {'disabled'} + assert not await list_sessions() @pytest.mark.asyncio @@ -172,21 +178,22 @@ async def test_symlink_multi(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('s1.b').value.get() == [False] - assert await cfg.option('c').value.get() == [False] - await cfg.option('s1.b').value.set([True]) - assert await cfg.option('s1.b').value.get() == [True] - assert await cfg.option('c').value.get() == [True] - await cfg.option('s1.b').value.set([False]) - assert await cfg.option('s1.b').value.get() == [False] - assert await cfg.option('c').value.get() == [False] - await cfg.option('s1.b').value.set([False, True]) - assert await cfg.option('s1.b').value.get() == [False, True] - assert await cfg.option('c').value.get() == [False, True] - assert boolopt.impl_is_multi() is True - assert linkopt.impl_is_multi() is True + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('s1.b').value.get() == [False] + assert await cfg.option('c').value.get() == [False] + await cfg.option('s1.b').value.set([True]) + assert await cfg.option('s1.b').value.get() == [True] + assert await cfg.option('c').value.get() == [True] + await cfg.option('s1.b').value.set([False]) + assert await cfg.option('s1.b').value.get() == [False] + assert await cfg.option('c').value.get() == [False] + await cfg.option('s1.b').value.set([False, True]) + assert await cfg.option('s1.b').value.get() == [False, True] + assert await cfg.option('c').value.get() == [False, True] + assert boolopt.impl_is_multi() is True + assert linkopt.impl_is_multi() is True + assert not await list_sessions() @pytest.mark.asyncio @@ -195,10 +202,11 @@ async def test_symlink_assign(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - with pytest.raises(ConfigError): - await cfg.option('c').value.set(True) + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + with pytest.raises(ConfigError): + await cfg.option('c').value.set(True) + assert not await list_sessions() @pytest.mark.asyncio @@ -207,13 +215,14 @@ async def test_symlink_owner(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.option('s1.b').owner.isdefault() - assert await cfg.option('c').owner.isdefault() - await cfg.option('s1.b').value.set(True) - assert not await cfg.option('s1.b').owner.isdefault() - assert not await cfg.option('c').owner.isdefault() + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.option('s1.b').owner.isdefault() + assert await cfg.option('c').owner.isdefault() + await cfg.option('s1.b').value.set(True) + assert not await cfg.option('s1.b').owner.isdefault() + assert not await cfg.option('c').owner.isdefault() + assert not await list_sessions() @pytest.mark.asyncio @@ -233,7 +242,7 @@ async def test_symlink_leader(): a = StrOption('a', "", multi=True) ip_admin_eth0 = SymLinkOption('ip_admin_eth0', a) netmask_admin_eth0 = StrOption('netmask_admin_eth0', "", multi=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) @@ -242,7 +251,7 @@ async def test_symlink_followers(): a = StrOption('a', "", multi=True) ip_admin_eth0 = StrOption('ip_admin_eth0', "ip rĂ©seau autorisĂ©", multi=True) netmask_admin_eth0 = SymLinkOption('netmask_admin_eth0', a) - with pytest.raises(ValueError): + with pytest.raises(ValueError): Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) @@ -253,11 +262,12 @@ async def test_symlink_with_leader(config_type): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) leader = SymLinkOption('leader', ip_admin_eth0) od = OptionDescription('root', '', [interface1, leader]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []} - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'leader': ['val1', 'val2']} + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []} + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'leader': ['val1', 'val2']} + assert not await list_sessions() @pytest.mark.asyncio @@ -267,24 +277,25 @@ async def test_symlink_with_follower(config_type): interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0]) follower = SymLinkOption('follower', netmask_admin_eth0) od = OptionDescription('root', '', [interface1, follower]) - cfg = await Config(od) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []} - await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]} - # - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None - assert await cfg.option('follower', 0).value.get() == None - assert await cfg.option('follower', 1).value.get() == None - # - await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3') - assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, 'val3'], 'follower': [None, 'val3']} - # - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None - assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3' - assert await cfg.option('follower', 0).value.get() == None - assert await cfg.option('follower', 1).value.get() == 'val3' + async with await Config(od) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []} + await cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2']) + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]} + # + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None + assert await cfg.option('follower', 0).value.get() == None + assert await cfg.option('follower', 1).value.get() == None + # + await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3') + assert await cfg.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, 'val3'], 'follower': [None, 'val3']} + # + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None + assert await cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3' + assert await cfg.option('follower', 0).value.get() == None + assert await cfg.option('follower', 1).value.get() == 'val3' + assert not await list_sessions() #____________________________________________________________ @@ -294,11 +305,12 @@ async def test_symlink_dependency(): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - assert await cfg.option('s1.b').option.has_dependency() is False - assert await cfg.option('c').option.has_dependency() is True - assert await cfg.option('s1.b').option.has_dependency(False) is True - assert await cfg.option('c').option.has_dependency(False) is False + async with await Config(descr) as cfg: + assert await cfg.option('s1.b').option.has_dependency() is False + assert await cfg.option('c').option.has_dependency() is True + assert await cfg.option('s1.b').option.has_dependency(False) is True + assert await cfg.option('c').option.has_dependency(False) is False + assert not await list_sessions() @pytest.mark.asyncio @@ -307,11 +319,12 @@ async def test_symlink_makedict(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - assert await cfg.value.dict() == {'c': False, 's1.b': False} - await cfg.option('s1.b').value.set(True) - assert await cfg.value.dict() == {'c': True, 's1.b': True} + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + assert await cfg.value.dict() == {'c': False, 's1.b': False} + await cfg.option('s1.b').value.set(True) + assert await cfg.value.dict() == {'c': True, 's1.b': True} + assert not await list_sessions() @pytest.mark.asyncio @@ -320,14 +333,15 @@ async def test_symlink_list(config_type): linkopt = SymLinkOption("c", boolopt) descr = OptionDescription("opt", "", [linkopt, OptionDescription("s1", "", [boolopt])]) - cfg = await Config(descr) - cfg = await get_config(cfg, config_type) - list_opt = [] - for opt in await cfg.option.list(): - list_opt.append(await opt.option.path()) - assert list_opt == ['c'] - # - list_opt = [] - for opt in await cfg.option.list(recursive=True): - list_opt.append(await opt.option.path()) - assert list_opt == ['c', 's1.b'] + async with await Config(descr) as cfg: + cfg = await get_config(cfg, config_type) + list_opt = [] + for opt in await cfg.option.list(): + list_opt.append(await opt.option.path()) + assert list_opt == ['c'] + # + list_opt = [] + for opt in await cfg.option.list(recursive=True): + list_opt.append(await opt.option.path()) + assert list_opt == ['c', 's1.b'] + assert not await list_sessions() diff --git a/tiramisu/__init__.py b/tiramisu/__init__.py index bea3601..359fd51 100644 --- a/tiramisu/__init__.py +++ b/tiramisu/__init__.py @@ -1,4 +1,4 @@ -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/api.py b/tiramisu/api.py index d23a384..d7bc472 100644 --- a/tiramisu/api.py +++ b/tiramisu/api.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -25,6 +25,7 @@ from .error import APIError, ConfigError, LeadershipError, PropertiesOptionError from .i18n import _ from .setting import ConfigBag, OptionBag, owners, groups, Undefined, undefined, \ FORBIDDEN_SET_PROPERTIES, SPECIAL_PROPERTIES, EXPIRATION_TIME +from .storage import default_storage from .config import KernelConfig, SubConfig, KernelGroupConfig, KernelMetaConfig, KernelMixConfig from .option import RegexpOption, OptionDescription from .todict import TiramisuDict @@ -84,7 +85,8 @@ class CommonTiramisu(TiramisuHelp): _allow_optiondescription = True _validate_properties = True - async def _get_option(self) -> Any: + async def _get_option(self, + connection) -> Any: if not self._subconfig: config_bag = self._option_bag.config_bag try: @@ -103,6 +105,7 @@ class CommonTiramisu(TiramisuHelp): config_bag, self._subconfig.cfgimpl_get_path()) self._option_bag.option = option + self._option_bag.config_bag.connection = connection # Calculate option's properties settings = config_bag.context.cfgimpl_get_settings() @@ -141,6 +144,18 @@ class CommonTiramisuOption(CommonTiramisu): raise APIError(_('unknown method "{}" in "{}"').format(name, self.__class__.__name__)) +def option_and_connection(func): + async def wrapped(self, *args, **kwargs): + config_bag = self._option_bag.config_bag + async with config_bag.context.getconnection() as connection: + config_bag.connection = connection + option = await self._get_option(connection) + ret = await func(self, *args, **kwargs) + del config_bag.connection + return ret + return wrapped + + class _TiramisuOptionOptionDescription(CommonTiramisuOption): """Manage option""" _allow_optiondescription = True @@ -152,60 +167,62 @@ class _TiramisuOptionOptionDescription(CommonTiramisuOption): super().__init__(option_bag) self._config = option_bag.config_bag.context + @option_and_connection async def get(self): """Get Tiramisu option""" - return await self._get_option() + return self._option_bag.option + @option_and_connection async def type(self): - option = await self._get_option() - return option.impl_get_group_type() + return self._option_bag.option.impl_get_group_type() + @option_and_connection async def isleadership(self): """Test if option is a leader or a follower""" - option = await self._get_option() - return option.impl_is_leadership() + return self._option_bag.option.impl_is_leadership() + @option_and_connection async def doc(self): """Get option document""" - option = await self._get_option() - return option.impl_get_display_name() + return self._option_bag.option.impl_get_display_name() + @option_and_connection async def description(self): """Get option description""" - option = await self._get_option() - return option.impl_get_information('doc', None) + return self._option_bag.option.impl_get_information('doc', None) + @option_and_connection async def name(self, follow_symlink: bool=False) -> str: """Get option name""" - option = await self._get_option() if not follow_symlink or \ - await self.isoptiondescription() or \ - not await self.issymlinkoption(): - return option.impl_getname() + self._option_bag.option.impl_is_optiondescription() or \ + not self._option_bag.option.impl_is_symlinkoption(): + return self._option_bag.option.impl_getname() else: - return option.impl_getopt().impl_getname() + return self._option_bag.option.impl_getopt().impl_getname() + @option_and_connection async def path(self) -> str: """Get option path""" return self._option_bag.path + @option_and_connection async def has_dependency(self, self_is_dep=True): """Test if option has dependency""" - option = await self._get_option() - return option.impl_has_dependency(self_is_dep) + return self._option_bag.option.impl_has_dependency(self_is_dep) + @option_and_connection async def isoptiondescription(self): """Test if option is an optiondescription""" - option = await self._get_option() - return option.impl_is_optiondescription() + return self._option_bag.option.impl_is_optiondescription() + @option_and_connection async def properties(self, only_raises=False, uncalculated=False): """Get properties for an option""" settings = self._option_bag.config_bag.context.cfgimpl_get_settings() - option = await self._get_option() if uncalculated: return await settings.getproperties(self._option_bag, uncalculated=True) @@ -229,38 +246,39 @@ class _TiramisuOptionOptionDescription(CommonTiramisuOption): class TiramisuOptionOption(_TiramisuOptionOptionDescription): """Manage option""" + @option_and_connection async def ismulti(self): """Test if option could have multi value""" - option = await self._get_option() - return option.impl_is_multi() + return self._option_bag.option.impl_is_multi() + @option_and_connection async def issubmulti(self): """Test if option could have submulti value""" - option = await self._get_option() - return option.impl_is_submulti() + return self._option_bag.option.impl_is_submulti() + @option_and_connection async def isleader(self): """Test if option is a leader""" - option = await self._get_option() - return option.impl_is_leader() + return self._option_bag.option.impl_is_leader() + @option_and_connection async def isfollower(self): """Test if option is a follower""" - option = await self._get_option() - return option.impl_is_follower() + return self._option_bag.option.impl_is_follower() + @option_and_connection async def issymlinkoption(self) -> bool: - option = await self._get_option() - return option.impl_is_symlinkoption() + return self._option_bag.option.impl_is_symlinkoption() + @option_and_connection async def default(self): """Get default value for an option (not for optiondescription)""" - option = await self._get_option() - return option.impl_getdefault() + return self._option_bag.option.impl_getdefault() + @option_and_connection async def defaultmulti(self): """Get default value when added a value for a multi option (not for optiondescription)""" - option = await self._get_option() + option = self._option_bag.option ret = option.impl_getdefault_multi() if ret is None and option.impl_is_multi() and option.impl_has_callback() and not self.isfollower(): callback, callback_params = option.impl_get_callback() @@ -272,22 +290,23 @@ class TiramisuOptionOption(_TiramisuOptionOptionDescription): ret = value return ret + @option_and_connection async def callbacks(self): """Get callbacks for an option (not for optiondescription)""" - option = await self._get_option() - return option.impl_get_callback() + return self._option_bag.option.impl_get_callback() + @option_and_connection async def validator(self): """Get validator for an option (not for optiondescription)""" - option = await self._get_option() - return option.impl_get_validator() + return self._option_bag.option.impl_get_validator() + @option_and_connection async def type(self): - option = await self._get_option() - return option.get_type() + return self._option_bag.option.get_type() + @option_and_connection async def pattern(self) -> str: - option = await self._get_option() + option = self._option_bag.option type = option.get_type() if isinstance(option, RegexpOption): return option._regexp.pattern @@ -313,19 +332,19 @@ class TiramisuOptionOwner(CommonTiramisuOption): # for help() self._values = self._option_bag.config_bag.context.cfgimpl_get_values() + @option_and_connection async def get(self): """Get owner for a specified option""" - await self._get_option() return await self._values.getowner(self._option_bag) + @option_and_connection async def isdefault(self): """Is option has defaut value""" - await self._get_option() return await self._values.is_default_owner(self._option_bag) + @option_and_connection async def set(self, owner): """Get owner for a specified option""" - await self._get_option() try: obj_owner = getattr(owners, owner) except AttributeError: @@ -347,47 +366,50 @@ class TiramisuOptionProperty(CommonTiramisuOption): if option_bag and option_bag.config_bag: self._settings = option_bag.config_bag.context.cfgimpl_get_settings() + @option_and_connection async def get(self, only_raises=False, uncalculated=False): """Get properties for an option""" - await self._get_option() if not only_raises: return self._option_bag.properties # do not check cache properties/permissives which are not save (unrestraint, ...) - return await self._settings.calc_raises_properties(self._option_bag, - uncalculated=uncalculated) + ret = await self._settings.calc_raises_properties(self._option_bag, + uncalculated=uncalculated) + return ret + @option_and_connection async def add(self, prop): """Add new property for an option""" - option = await self._get_option() if prop in FORBIDDEN_SET_PROPERTIES: raise ConfigError(_('cannot add this property: "{0}"').format( ' '.join(prop))) - props = await self._settings._p_.getproperties(self._option_bag.path, + props = await self._settings._p_.getproperties(self._option_bag.config_bag.connection, + self._option_bag.path, self._option_bag.index, - option.impl_getproperties()) + self._option_bag.option.impl_getproperties()) await self._settings.setproperties(self._option_bag.path, props | {prop}, self._option_bag, self._option_bag.config_bag.context) + @option_and_connection async def pop(self, prop): """Remove new property for an option""" - option = await self._get_option() - props = await self._settings._p_.getproperties(self._option_bag.path, + props = await self._settings._p_.getproperties(self._option_bag.config_bag.connection, + self._option_bag.path, self._option_bag.index, - option.impl_getproperties()) + self._option_bag.option.impl_getproperties()) await self._settings.setproperties(self._option_bag.path, props - {prop}, self._option_bag, self._option_bag.config_bag.context) + @option_and_connection async def reset(self): """Reset all personalised properties""" - await self._get_option() await self._settings.reset(self._option_bag, - self._option_bag.config_bag.context) + self._option_bag.config_bag) class TiramisuOptionPermissive(CommonTiramisuOption): @@ -401,22 +423,22 @@ class TiramisuOptionPermissive(CommonTiramisuOption): if option_bag and option_bag.config_bag: self._settings = option_bag.config_bag.context.cfgimpl_get_settings() + @option_and_connection async def get(self): """Get permissives value""" - await self._get_option() return await self._settings.getpermissives(self._option_bag) + @option_and_connection async def set(self, permissives): """Set permissives value""" - await self._get_option() await self._settings.setpermissives(self._option_bag, permissives=permissives) + @option_and_connection async def reset(self): """Reset all personalised permissive""" - await self._get_option() await self._settings.reset_permissives(self._option_bag, - self._option_bag.config_bag.context) + self._option_bag.config_bag) class TiramisuOptionInformation(CommonTiramisuOption): @@ -428,45 +450,53 @@ class TiramisuOptionInformation(CommonTiramisuOption): option_bag: OptionBag) -> None: super().__init__(option_bag) + @option_and_connection async def get(self, key, default=undefined): """Get information""" path = self._option_bag.path values = self._option_bag.config_bag.context.cfgimpl_get_values() try: - return await values.get_information(key, + return await values.get_information(self._option_bag.config_bag.connection, + key, path=path) except ValueError: - option = await self._get_option() - return option.impl_get_information(key, default) + return self._option_bag.option.impl_get_information(key, default) + @option_and_connection async def set(self, key, value): """Set information""" path = self._option_bag.path values = self._option_bag.config_bag.context.cfgimpl_get_values() - await values.set_information(key, value, path=path) + await values.set_information(self._option_bag.config_bag.connection, + key, + value, + path=path) + @option_and_connection async def reset(self, key): """Remove information""" path = self._option_bag.path values = self._option_bag.config_bag.context.cfgimpl_get_values() - await values.del_information(key, + await values.del_information(self._option_bag.config_bag.connection, + key, path=path) + @option_and_connection async def list(self): """List information's keys""" - await self._get_option() path = self._option_bag.path values = self._option_bag.config_bag.context.cfgimpl_get_values() - return await values.list_information(path) - - async def len(self): - """Length of leadership""" - option = await self._get_option() - # for example if index is None - if '_length' not in vars(self): - self._length = self._subconfig.cfgimpl_get_length() - return self._length + return await values.list_information(self._option_bag.config_bag.connection, + path) +# +# async def len(self): +# """Length of leadership""" +# option = await self._get_option() +# # for example if index is None +# if '_length' not in vars(self): +# self._length = self._subconfig.cfgimpl_get_length() +# return self._length def option_type(typ): @@ -478,28 +508,41 @@ def option_type(typ): def wrapper(func): @wraps(func) async def wrapped(*args, **kwargs): - for typ in types: - if typ == 'group': - if args[0]._option_bag.config_bag.context.impl_type == 'group': - return await func(*args, **kwargs, is_group=True) - else: - option = await args[0]._get_option() - if typ == 'option': - if option.impl_is_optiondescription(): - raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) - elif typ == 'optiondescription': - if not option.impl_is_optiondescription(): - raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) - elif typ == 'leader': - if not option.impl_is_leader(): - raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) - elif typ == 'follower': - if not option.impl_is_follower() and not option.impl_is_leader(): - raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) - elif typ == 'choice': - if not option.get_type() == 'choice': - raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) - return await func(*args, **kwargs) + config_bag = args[0]._option_bag.config_bag + async with config_bag.context.getconnection() as connection: + for typ in types: + if typ == 'group': + if args[0]._option_bag.config_bag.context.impl_type == 'group': + config_bag.connection = connection + ret = await func(*args, **kwargs, is_group=True) + del config_bag.connection + return ret + else: + config_bag.connection = connection + option = await args[0]._get_option(connection) + if typ == 'option': + if option.impl_is_optiondescription(): + del config_bag.connection + raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) + elif typ == 'optiondescription': + if not option.impl_is_optiondescription(): + del config_bag.connection + raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) + elif typ == 'leader': + if not option.impl_is_leader(): + del config_bag.connection + raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) + elif typ == 'follower': + if not option.impl_is_follower() and not option.impl_is_leader(): + del config_bag.connection + raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) + elif typ == 'choice': + if not option.get_type() == 'choice': + del config_bag.connection + raise APIError(_('please specify a valid sub function ({})').format(func.__name__)) + ret = await func(*args, **kwargs) + del config_bag.connection + return ret return wrapped return wrapper @@ -559,7 +602,8 @@ class TiramisuOptionValue(CommonTiramisuOption): is_group: bool=False): """Reset value for an option""" if is_group: - await self._option_bag.config_bag.context.reset(self._option_bag.path) + await self._option_bag.config_bag.context.reset(self._option_bag.config_bag.connection, + self._option_bag.path) else: if self._option_bag.option.impl_is_follower() and self._option_bag.index is None: raise APIError('index must be set with a follower option') @@ -568,7 +612,7 @@ class TiramisuOptionValue(CommonTiramisuOption): @option_type('option') async def default(self): """Get default value (default of option or calculated value)""" - option = await self._get_option() + option = self._option_bag.option values = self._option_bag.config_bag.context.cfgimpl_get_values() if option.impl_is_follower() and self._option_bag.index is None: value = [] @@ -601,8 +645,7 @@ class TiramisuOptionValue(CommonTiramisuOption): @option_type('choice') async def list(self): """All values available for a ChoiceOption""" - option = await self._get_option() - return await option.impl_get_values(self._option_bag) + return await self._option_bag.option.impl_get_values(self._option_bag) @option_type('leader') async def pop(self, index): @@ -618,7 +661,6 @@ class TiramisuOptionValue(CommonTiramisuOption): @option_type('follower') async def len(self): """Length of follower option""" - option = await self._get_option() # for example if index is None if '_length' not in vars(self): self._length = await self._subconfig.cfgimpl_get_length_leadership(self._option_bag) @@ -645,22 +687,30 @@ class TiramisuConfig(TiramisuHelp): self._orig_config_bags = orig_config_bags async def _return_config(self, - config): + config, + storage): if isinstance(config, KernelConfig): - return await Config(config) + return await Config(config, + storage=storage) if isinstance(config, KernelMetaConfig): - return await MetaConfig(config) + return await MetaConfig(config, + storage=storage) if isinstance(config, KernelMixConfig): - return await MixConfig([], config) + return await MixConfig([], + config, + storage=storage) if isinstance(config, KernelGroupConfig): - return await GroupConfig(config) + return await GroupConfig(config, + storage=storage) raise Exception(_('unknown config type {}').format(type(config))) - async def _reset_config_properties(self): + async def _reset_config_properties(self, + connection): config = self._config_bag.context settings = config.cfgimpl_get_settings() - properties = await settings.get_context_properties(config._impl_properties_cache) - permissives = await settings.get_context_permissives() + properties = await settings.get_context_properties(connection, + config._impl_properties_cache) + permissives = await settings.get_context_permissives(connection) self._config_bag.properties = properties self._config_bag.permissives = permissives if self._orig_config_bags: @@ -700,7 +750,7 @@ class TiramisuOption(CommonTiramisu, TiramisuConfig): """find an option by name (only for optiondescription)""" if not first: ret = [] - option = await self._get_option() + option = self._option_bag.option config_bag = self._option_bag.config_bag oname = option.impl_getname() path = self._subconfig._get_subpath(oname) @@ -725,8 +775,7 @@ class TiramisuOption(CommonTiramisu, TiramisuConfig): @option_type('optiondescription') async def group_type(self): """Get type for an optiondescription (only for optiondescription)""" - option = await self._get_option() - return option.impl_get_group_type() + return self._option_bag.option.impl_get_group_type() async def _filter(self, opt, @@ -756,7 +805,7 @@ class TiramisuOption(CommonTiramisu, TiramisuConfig): if config_bag.properties and 'warnings' in config_bag.properties: config_bag = config_bag.copy() config_bag.remove_warnings() - option = await self._get_option() + option = self._option_bag.option option_bag = OptionBag() option_bag.set_option(option, None, @@ -784,9 +833,10 @@ class TiramisuOption(CommonTiramisu, TiramisuConfig): async def _load_dict(self, clearable: str="all", remotable: str="minimum"): - option = await self._get_option() - root = option.impl_getpath() - self._tiramisu_dict = TiramisuDict(await self._return_config(self._option_bag.config_bag.context), + root = self._option_bag.option.impl_getpath() + config = self._option_bag.config_bag.context + self._tiramisu_dict = TiramisuDict(await self._return_config(config, + config._storage), root=root, clearable=clearable, remotable=remotable) @@ -811,27 +861,48 @@ class TiramisuOption(CommonTiramisu, TiramisuConfig): return await self._tiramisu_dict.set_updates(body) +def connection(func): + async def wrapped(self, *args, **kwargs): + config_bag = self._config_bag + async with config_bag.context.getconnection() as connection: + config_bag.connection = connection + ret = await func(self, *args, **kwargs) + del config_bag.connection + return ret + return wrapped + + class TiramisuContextInformation(TiramisuConfig): """Manage config informations""" + @connection async def get(self, name, default=undefined): """Get an information""" - return await self._config_bag.context.impl_get_information(name, default) + return await self._config_bag.context.impl_get_information(self._config_bag.connection, + name, + default) + @connection async def set(self, name, value): """Set an information""" - await self._config_bag.context.impl_set_information(name, value) + await self._config_bag.context.impl_set_information(self._config_bag.connection, + name, + value) + @connection async def reset(self, name): """Remove an information""" - await self._config_bag.context.impl_del_information(name) + await self._config_bag.context.impl_del_information(self._config_bag.connection, + name) + @connection async def list(self): """List information's keys""" - return await self._config_bag.context.impl_list_information() + return await self._config_bag.context.impl_list_information(self._config_bag.connection) class TiramisuContextValue(TiramisuConfig): """Manage config value""" + @connection async def mandatory(self): """Return path of options with mandatory property without any value""" options = [] @@ -840,6 +911,7 @@ class TiramisuContextValue(TiramisuConfig): return options # FIXME should be only for group/meta + @connection async def set(self, path: str, value, @@ -865,6 +937,7 @@ class TiramisuContextValue(TiramisuConfig): **kwargs) # FIXME should be only for group/meta + @connection async def reset(self, path: str, only_children: bool=False): @@ -873,6 +946,7 @@ class TiramisuContextValue(TiramisuConfig): only_children, self._config_bag) + @connection async def dict(self, flatten=False, withwarning: bool=False, @@ -888,10 +962,11 @@ class TiramisuContextValue(TiramisuConfig): fullpath=fullpath, leader_to_list=leader_to_list) + @connection async def exportation(self, with_default_owner: bool=False): """Export all values""" - exportation = await self._config_bag.context.cfgimpl_get_values()._p_.exportation() + exportation = await self._config_bag.context.cfgimpl_get_values()._p_.exportation(self._config_bag.connection) if not with_default_owner: exportation = [list(exportation[0]), list(exportation[1]), list(exportation[2]), list(exportation[3])] index = exportation[0].index(None) @@ -901,29 +976,49 @@ class TiramisuContextValue(TiramisuConfig): exportation[3].pop(index) return exportation + @connection async def importation(self, values): """Import values""" + cvalues = self._config_bag.context.cfgimpl_get_values() + connection = self._config_bag.connection if None not in values[0]: - context_owner = await self._config_bag.context.cfgimpl_get_values().get_context_owner() + context_owner = await cvalues.get_context_owner(connection) else: context_owner = None - await self._config_bag.context.cfgimpl_get_values()._p_.importation(values) + await cvalues._p_.importation(connection, + values) await self._config_bag.context.cfgimpl_reset_cache(None, None) if context_owner is not None: - await self._config_bag.context.cfgimpl_get_values()._p_.setvalue(None, - None, - context_owner, - None, - True) + await cvalues._p_.setvalue(connection, + None, + None, + context_owner, + None, + True) + + +class TiramisuContextSession(TiramisuConfig): + """Manage Config session""" + async def reset(self): + await self._config_bag.context.cfgimpl_get_values()._p_._storage.delete_session() + await self._config_bag.context.cfgimpl_get_settings()._p_._storage.delete_session() + + async def list(self): + return await self._config_bag.context.cfgimpl_get_values()._p_._storage.list_sessions() + + async def id(self): + """Get config name""" + return self._config_bag.context.impl_getname() class TiramisuContextOwner(TiramisuConfig): """Global owner""" - + @connection async def get(self): """Get owner""" - return await self._config_bag.context.cfgimpl_get_values().get_context_owner() + return await self._config_bag.context.cfgimpl_get_values().get_context_owner(self._config_bag.connection) + @connection async def set(self, owner): """Set owner""" try: @@ -931,85 +1026,109 @@ class TiramisuContextOwner(TiramisuConfig): except AttributeError: owners.addowner(owner) obj_owner = getattr(owners, owner) - await self._config_bag.context.cfgimpl_get_values().set_context_owner(obj_owner) + values = self._config_bag.context.cfgimpl_get_values() + await values.set_context_owner(self._config_bag.connection, + obj_owner) class TiramisuContextProperty(TiramisuConfig): """Manage config properties""" - + @connection async def read_only(self): """Set config to read only mode""" old_props = self._config_bag.properties settings = self._config_bag.context.cfgimpl_get_settings() - await settings.read_only(self._config_bag.context) - await self._reset_config_properties() + await settings.read_only(self._config_bag) + await self._reset_config_properties(self._config_bag.connection) if 'force_store_value' not in old_props and \ 'force_store_value' in self._config_bag.properties: await self._force_store_value() + @connection async def read_write(self): """Set config to read and write mode""" old_props = self._config_bag.properties settings = self._config_bag.context.cfgimpl_get_settings() - await settings.read_write(self._config_bag.context) + connection = self._config_bag.connection + await settings.read_write(self._config_bag) or_properties = settings.rw_append - settings.ro_append - SPECIAL_PROPERTIES - permissives = frozenset(await settings.get_context_permissives() | or_properties) - await settings.set_context_permissives(permissives) - await self._reset_config_properties() + permissives = frozenset(await settings.get_context_permissives(connection) | or_properties) + await settings.set_context_permissives(connection, + permissives) + await self._reset_config_properties(connection) if 'force_store_value' not in old_props and \ 'force_store_value' in self._config_bag.properties: await self._force_store_value() + @connection async def add(self, prop): """Add a config property""" + settings = self._config_bag.context.cfgimpl_get_settings() props = set(await self.get()) - props.add(prop) - await self._set(frozenset(props)) + if prop not in props: + props.add(prop) + await self._set(self._config_bag.connection, frozenset(props)) + @connection async def pop(self, prop): """Remove a config property""" props = set(await self.get()) if prop in props: props.remove(prop) - await self._set(frozenset(props)) + await self._set(self._config_bag.connection, frozenset(props)) - async def get(self): + async def get(self, + default=False): """Get all config properties""" + if default: + config = self._config_bag.context + async with config.getconnection() as connection: + properties = await config.cfgimpl_get_settings().get_context_properties(connection, + config._impl_properties_cache) return self._config_bag.properties - async def _set(self, props): + async def _set(self, + connection, + props): """Personalise config properties""" if 'force_store_value' in props: force_store_value = 'force_store_value' not in self._config_bag.properties else: force_store_value = False context = self._config_bag.context - await context.cfgimpl_get_settings().set_context_properties(props, - context) - await self._reset_config_properties() + await context.cfgimpl_get_settings().set_context_properties(self._config_bag.connection, + props, + self._config_bag.context) + await self._reset_config_properties(connection) if force_store_value: await self._force_store_value() + @connection async def reset(self): """Remove config properties""" context = self._config_bag.context await context.cfgimpl_get_settings().reset(None, - context) - await self._reset_config_properties() + self._config_bag) + await self._reset_config_properties(self._config_bag.connection) + @connection async def exportation(self): """Export config properties""" - return await self._config_bag.context.cfgimpl_get_settings()._p_.exportation() + return await self._config_bag.context.cfgimpl_get_settings()._p_.exportation(self._config_bag.connection) + @connection async def importation(self, properties): """Import config properties""" if 'force_store_value' in properties.get(None, {}).get(None, []): force_store_value = 'force_store_value' not in self._config_bag.properties else: force_store_value = False - await self._config_bag.context.cfgimpl_get_settings()._p_.importation(properties) + settings = self._config_bag.context.cfgimpl_get_settings() + connection = self._config_bag.connection + await self._config_bag.context.cfgimpl_get_settings()._p_.importation(connection, + properties) await self._config_bag.context.cfgimpl_reset_cache(None, None) - await self._reset_config_properties() + await self._reset_config_properties(connection) if force_store_value: await self._force_store_value() @@ -1067,43 +1186,58 @@ class TiramisuContextProperty(TiramisuConfig): class TiramisuContextPermissive(TiramisuConfig): """Manage config permissives""" - + @connection async def get(self): """Get config permissives""" - return await self._config_bag.context.cfgimpl_get_settings().get_context_permissives() + return await self._get() - async def _set(self, permissives): + async def _get(self): + return await self._config_bag.context.cfgimpl_get_settings().get_context_permissives(self._config_bag.connection) + + async def _set(self, + permissives): """Set config permissives""" - await self._config_bag.context.cfgimpl_get_settings().set_context_permissives(permissives) - await self._reset_config_properties() + connection = self._config_bag.connection + await self._config_bag.context.cfgimpl_get_settings().set_context_permissives(connection, permissives) + await self._reset_config_properties(connection) + @connection async def exportation(self): """Export config permissives""" - return await self._config_bag.context.cfgimpl_get_settings()._pp_.exportation() + return await self._config_bag.context.cfgimpl_get_settings()._pp_.exportation(self._config_bag.connection) + @connection async def importation(self, permissives): """Import config permissives""" - await self._config_bag.context.cfgimpl_get_settings()._pp_.importation(permissives) + settings = self._config_bag.context.cfgimpl_get_settings() + connection = self._config_bag.connection + await settings._pp_.importation(connection, + permissives) await self._config_bag.context.cfgimpl_reset_cache(None, None) - await self._reset_config_properties() + await self._reset_config_properties(connection) + @connection async def reset(self): """Remove config permissives""" context = self._config_bag.context - await context.cfgimpl_get_settings().reset_permissives(None, - context) - await self._reset_config_properties() + settings = context.cfgimpl_get_settings() + connection = self._config_bag.connection + await settings.reset_permissives(None, + self._config_bag) + await self._reset_config_properties(connection) + @connection async def add(self, prop): """Add a config permissive""" - props = set(await self.get()) + props = set(await self._get()) props.add(prop) await self._set(frozenset(props)) + @connection async def pop(self, prop): """Remove a config permissive""" - props = set(await self.get()) + props = set(await self._get()) if prop in props: props.remove(prop) await self._set(frozenset(props)) @@ -1116,17 +1250,19 @@ class TiramisuContextOption(TiramisuConfig): self._tiramisu_dict = None super().__init__(*args, **kwargs) + @connection async def find(self, - name, - value=undefined, - type=None, - first=False): + name, + value=undefined, + type=None, + first=False): """Find an or a list of options""" options = [] - async for path in self._config_bag.context.find(byname=name, - byvalue=value, - bytype=type, - config_bag=self._config_bag): + context = self._config_bag.context + async for path in context.find(byname=name, + byvalue=value, + bytype=type, + config_bag=self._config_bag): option = TiramisuOption(path, None, self._config_bag) @@ -1184,10 +1320,11 @@ class TiramisuContextOption(TiramisuConfig): self._config_bag)) return options + @connection async def list(self, - type='option', - group_type=None, - recursive=False): + type='option', + group_type=None, + recursive=False): """List options (by default list only option)""" assert type in ('all', 'option', 'optiondescription'), _('unknown list type {}').format(type) assert group_type is None or isinstance(group_type, groups.GroupType), \ @@ -1210,7 +1347,8 @@ class TiramisuContextOption(TiramisuConfig): async def _load_dict(self, clearable="all", remotable="minimum"): - self._tiramisu_dict = TiramisuDict(await self._return_config(self._config_bag.context), + self._tiramisu_dict = TiramisuDict(await self._return_config(self._config_bag.context, + self._config_bag.context._storage), root=None, clearable=clearable, remotable=remotable) @@ -1234,51 +1372,64 @@ class TiramisuContextOption(TiramisuConfig): class _TiramisuContextConfigReset(): + @connection async def reset(self): """Remove all datas to current config (informations, values, properties, ...)""" # Option's values - context_owner = await self._config_bag.context.cfgimpl_get_values().get_context_owner() - await self._config_bag.context.cfgimpl_get_values()._p_.importation(([], [], [], [])) - await self._config_bag.context.cfgimpl_get_values()._p_.setvalue(None, + settings = self._config_bag.context.cfgimpl_get_settings() + connection = self._config_bag.connection + context_owner = await self._config_bag.context.cfgimpl_get_values().get_context_owner(connection) + await self._config_bag.context.cfgimpl_get_values()._p_.importation(connection, ([], [], [], [])) + await self._config_bag.context.cfgimpl_get_values()._p_.setvalue(connection, + None, None, context_owner, None, True) # Option's informations - await self._config_bag.context.cfgimpl_get_values()._p_.del_informations() + await self._config_bag.context.cfgimpl_get_values()._p_.del_informations(connection) # Option's properties - await self._config_bag.context.cfgimpl_get_settings()._p_.importation({}) + await self._config_bag.context.cfgimpl_get_settings()._p_.importation(connection, {}) # Option's permissives - await self._config_bag.context.cfgimpl_get_settings()._pp_.importation({}) + await self._config_bag.context.cfgimpl_get_settings()._pp_.importation(connection, {}) # Remove cache await self._config_bag.context.cfgimpl_reset_cache(None, None) class _TiramisuContextConfig(TiramisuConfig, _TiramisuContextConfigReset): """Actions to Config""" - async def name(self): - return self._config_bag.context.impl_getname() + async def type(self): + """Type a Config""" + return 'config' async def copy(self, session_id=None, - persistent=False, storage=None): """Copy current config""" - return await self._return_config(await self._config_bag.context.duplicate(session_id, - persistent=persistent, - storage=storage)) + if storage is None: + storage = self._config_bag.context._storage + async with self._config_bag.context.getconnection() as connection: + config = await self._config_bag.context.duplicate(connection, + session_id, + storage=storage) + return await self._return_config(config, + storage) async def deepcopy(self, session_id=None, - persistent=False, storage=None, metaconfig_prefix=None): """Copy current config with all parents""" - return await self._return_config(await self._config_bag.context.duplicate(session_id, - persistent=persistent, - storage=storage, - metaconfig_prefix=metaconfig_prefix, - deep=[])) + if storage is None: + storage = self._config_bag.context._storage + async with self._config_bag.context.getconnection() as connection: + config = await self._config_bag.context.duplicate(connection, + session_id, + storage=storage, + metaconfig_prefix=metaconfig_prefix, + deep=[]) + return await self._return_config(config, + storage) async def metaconfig(self): """Get first meta configuration (obsolete please use parents)""" @@ -1291,7 +1442,8 @@ class _TiramisuContextConfig(TiramisuConfig, _TiramisuContextConfigReset): """Get all parents of current config""" ret = [] for parent in self._config_bag.context.get_parents(): - ret.append(await self._return_config(parent)) + ret.append(await self._return_config(parent, + parent._storage)) return ret async def path(self): @@ -1301,17 +1453,19 @@ class _TiramisuContextConfig(TiramisuConfig, _TiramisuContextConfigReset): class _TiramisuContextGroupConfig(TiramisuConfig): """Actions to GroupConfig""" - async def name(self): - """Get config name""" - return self._config_bag.context.impl_getname() + async def type(self): + """Type a Config""" + return 'groupconfig' async def list(self): """List children's config""" ret = [] for child in self._config_bag.context.cfgimpl_get_children(): - ret.append(await self._return_config(child)) + ret.append(await self._return_config(child, + child._storage)) return ret + @connection async def find(self, name: str, value=undefined): @@ -1327,37 +1481,52 @@ class _TiramisuContextGroupConfig(TiramisuConfig): config = self._config_bag.context for spath in spaths: config = config.getconfig(spath) - return self._return_config(config) + return self._return_config(config, + config._storage) async def copy(self, session_id=None, - persistent=False, storage=None): - return await self._return_config(await self._config_bag.context.duplicate(session_id, - persistent=persistent, - storage=storage)) + if storage is None: + storage = self._config_bag.context._storage + async with self._config_bag.context.getconnection() as connection: + config = await self._config_bag.context.duplicate(connection, + session_id, + storage=storage) + return await self._return_config(config, + storage) async def deepcopy(self, session_id=None, - persistent=False, storage=None, metaconfig_prefix=None): - return await self._return_config(await self._config_bag.context.duplicate(session_id, - persistent=persistent, - storage=storage, - metaconfig_prefix=metaconfig_prefix, - deep=[])) + if storage is None: + storage = self._config_bag.config._storage + async with self._config_bag.context.getconnection() as connection: + config = await self._config_bag.context.duplicate(connection, + session_id, + storage=storage, + metaconfig_prefix=metaconfig_prefix, + deep=[]) + return await self._return_config(config, + storage) async def path(self): return self._config_bag.context.cfgimpl_get_config_path() async def get(self, name: str) -> 'Config': - return await self._return_config(self._config_bag.context.getconfig(name)) + config = self._config_bag.context.getconfig(name) + return await self._return_config(config, + config._storage) class _TiramisuContextMixConfig(_TiramisuContextGroupConfig, _TiramisuContextConfigReset): """Actions to MixConfig""" + async def type(self): + """Type a Config""" + return 'mixconfig' + async def pop(self, session_id=None, config=None): @@ -1365,7 +1534,8 @@ class _TiramisuContextMixConfig(_TiramisuContextGroupConfig, _TiramisuContextCon if __debug__ and None not in [session_id, config]: raise APIError(_('cannot set session_id and config together')) pop_config = await self._config_bag.context.pop_config(session_id=session_id, config=config) - return await self._return_config(pop_config) + return await self._return_config(pop_config, + pop_config._storage) async def add(self, config): @@ -1376,23 +1546,33 @@ class _TiramisuContextMixConfig(_TiramisuContextGroupConfig, _TiramisuContextCon """Get all parents of current config""" ret = [] for parent in self._config_bag.context.get_parents(): - ret.append(await self._return_config(parent)) + ret.append(await self._return_config(parent, + parent._storage)) return ret class _TiramisuContextMetaConfig(_TiramisuContextMixConfig): """Actions to MetaConfig""" + async def type(self): + """Type a Config""" + return 'metaconfig' + async def new(self, session_id, - persistent=False, storage=None, type='config'): """Create and add a new config""" - new_config = await self._config_bag.context.new_config(session_id=session_id, - persistent=persistent, - storage=storage, - type_=type) - return await self._return_config(new_config) + config = self._config_bag.context + if storage is None: + storage = config._storage + storage_obj = await storage.get() + async with storage_obj.Connection() as connection: + new_config = await config.new_config(connection, + session_id=session_id, + storage=storage, + type_=type) + return await self._return_config(new_config, + new_config._storage) @@ -1414,9 +1594,6 @@ class TiramisuAPI(TiramisuHelp): def __init__(self, config_bag, orig_config_bags=None) -> None: - if not isinstance(config_bag, ConfigBag): - raise Exception('pfffff') - # config = await ConfigBag(context=config) self._config_bag = config_bag self._orig_config_bags = orig_config_bags if not self._registers: @@ -1492,25 +1669,46 @@ class Config(TiramisuAPI): async def __init__(self, descr: OptionDescription, session_id: str=None, - persistent: bool=False, + delete_old_session: bool=False, storage=None, display_name=None) -> None: - if isinstance(descr, KernelConfig): - config = descr - else: - config = await KernelConfig(descr, - session_id=session_id, - persistent=persistent, - storage=storage, - display_name=display_name) - settings = config.cfgimpl_get_settings() - properties = await settings.get_context_properties(config._impl_properties_cache) - permissives = await settings.get_context_permissives() + if storage is None: + storage = default_storage + storage_obj = await storage.get() + async with storage_obj.Connection() as connection: + if isinstance(descr, KernelConfig): + config = descr + else: + config = await KernelConfig(descr, + connection=connection, + session_id=session_id, + delete_old_session=delete_old_session, + storage=storage, + display_name=display_name) + settings = config.cfgimpl_get_settings() + properties = await settings.get_context_properties(connection, + config._impl_properties_cache) + permissives = await settings.get_context_permissives(connection) config_bag = ConfigBag(config, properties=properties, permissives=permissives) super().__init__(config_bag) + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self._config_bag.context.cfgimpl_get_values()._p_._storage.delete_session() + await self._config_bag.context.cfgimpl_get_settings()._p_._storage.delete_session() + + def __del__(self): + try: + del self._config_bag.context + del self._config_bag + del self._orig_config_bags + except: + pass + @asyncinit class MetaConfig(TiramisuAPI): @@ -1518,34 +1716,47 @@ class MetaConfig(TiramisuAPI): async def __init__(self, children: 'Config'=[], session_id: Union[str, None]=None, - persistent: bool=False, + delete_old_session: bool=False, optiondescription: Optional[OptionDescription]=None, storage=None, display_name=None) -> None: - if isinstance(children, KernelMetaConfig): - config = children - else: - _children = [] - for child in children: - if isinstance(child, TiramisuAPI): - _children.append(child._config_bag.context) - else: - _children.append(child) + if storage is None: + storage = default_storage + storage_obj = await storage.get() + async with storage_obj.Connection() as connection: + if isinstance(children, KernelMetaConfig): + config = children + else: + _children = [] + for child in children: + if isinstance(child, TiramisuAPI): + _children.append(child._config_bag.context) + else: + _children.append(child) - config = await KernelMetaConfig(_children, - session_id=session_id, - persistent=persistent, - optiondescription=optiondescription, - display_name=display_name, - storage=storage) - settings = config.cfgimpl_get_settings() - properties = await settings.get_context_properties(config._impl_properties_cache) - permissives = await settings.get_context_permissives() + config = await KernelMetaConfig(_children, + connection=connection, + session_id=session_id, + delete_old_session=delete_old_session, + optiondescription=optiondescription, + display_name=display_name, + storage=storage) + settings = config.cfgimpl_get_settings() + properties = await settings.get_context_properties(connection, + config._impl_properties_cache) + permissives = await settings.get_context_permissives(connection) config_bag = ConfigBag(config, properties=properties, permissives=permissives) super().__init__(config_bag) + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self._config_bag.context.cfgimpl_get_values()._p_._storage.delete_session() + await self._config_bag.context.cfgimpl_get_settings()._p_._storage.delete_session() + @asyncinit class MixConfig(TiramisuAPI): @@ -1554,33 +1765,46 @@ class MixConfig(TiramisuAPI): optiondescription: OptionDescription, children: List[Config], session_id: Optional[str]=None, - persistent: bool=False, + delete_old_session: bool=False, storage=None, display_name: Callable=None) -> None: - if isinstance(children, KernelMixConfig): - config = children - else: - _children = [] - for child in children: - if isinstance(child, TiramisuAPI): - _children.append(child._config_bag.context) - else: - _children.append(child) + if storage is None: + storage = default_storage + storage_obj = await storage.get() + async with storage_obj.Connection() as connection: + if isinstance(children, KernelMixConfig): + config = children + else: + _children = [] + for child in children: + if isinstance(child, TiramisuAPI): + _children.append(child._config_bag.context) + else: + _children.append(child) - config = await KernelMixConfig(optiondescription, - _children, - session_id=session_id, - persistent=persistent, - storage=storage, - display_name=display_name) - settings = config.cfgimpl_get_settings() - properties = await settings.get_context_properties(config._impl_properties_cache) - permissives = await settings.get_context_permissives() + config = await KernelMixConfig(optiondescription, + _children, + session_id=session_id, + delete_old_session=delete_old_session, + storage=storage, + connection=connection, + display_name=display_name) + settings = config.cfgimpl_get_settings() + properties = await settings.get_context_properties(connection, + config._impl_properties_cache) + permissives = await settings.get_context_permissives(connection) config_bag = ConfigBag(config, properties=properties, permissives=permissives) super().__init__(config_bag) + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self._config_bag.context.cfgimpl_get_values()._p_._storage.delete_session() + await self._config_bag.context.cfgimpl_get_settings()._p_._storage.delete_session() + @asyncinit class GroupConfig(TiramisuAPI): diff --git a/tiramisu/asyncinit.py b/tiramisu/asyncinit.py index b73183b..2d121f8 100644 --- a/tiramisu/asyncinit.py +++ b/tiramisu/asyncinit.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2019-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -20,10 +20,10 @@ from functools import wraps def asyncinit(obj): - @wraps(obj.__new__) + @wraps(obj.__new__) async def new(cls, *args, **kwargs): - instance = object.__new__(cls) # (cls, *args, **kwargs) + instance = object.__new__(cls) # (cls, *args, **kwargs) await instance.__init__(*args, **kwargs) - return instance + return instance obj.__new__ = new return obj diff --git a/tiramisu/autolib.py b/tiramisu/autolib.py index d1f7fad..9361518 100644 --- a/tiramisu/autolib.py +++ b/tiramisu/autolib.py @@ -1,4 +1,4 @@ -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -150,8 +150,8 @@ class Calculation: option_bag: OptionBag, leadership_must_have_index: bool=False) -> str: if not self.help_function: - return self.execute(option_bag, - leadership_must_have_index=leadership_must_have_index) + return await self.execute(option_bag, + leadership_must_have_index=leadership_must_have_index) return await carry_out_calculation(option_bag.option, callback=self.help_function, callback_params=self.params, @@ -204,12 +204,8 @@ async def manager_callback(callbk: Union[ParamOption, ParamValue], path = option.impl_getpath() option_bag = await get_option_bag(config_bag, option, - apply_index) - option_bag.config_bag.unrestraint() - option_bag.config_bag.remove_validation() - # if we are in properties calculation, cannot calculated properties - option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag, - apply_requires=False) + apply_index, + True) new_value = await get_value(callbk, option_bag, path) if apply_index is None and is_follower: new_value[index] = value @@ -235,7 +231,8 @@ async def manager_callback(callbk: Union[ParamOption, ParamValue], async def get_option_bag(config_bag, opt, - index_): + index_, + self_calc): # don't validate if option is option that we tried to validate config_bag = config_bag.copy() config_bag.properties = config_bag.true_properties - {'warnings'} @@ -245,7 +242,14 @@ async def manager_callback(callbk: Union[ParamOption, ParamValue], option_bag.set_option(opt, index_, config_bag) - option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag) + if not self_calc: + option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag) + else: + option_bag.config_bag.unrestraint() + option_bag.config_bag.remove_validation() + # if we are in properties calculation, cannot calculated properties + option_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(option_bag, + apply_requires=False) return option_bag if isinstance(callbk, ParamValue): @@ -294,7 +298,8 @@ async def manager_callback(callbk: Union[ParamOption, ParamValue], path = callbk_option.impl_getpath() option_bag = await get_option_bag(config_bag, callbk_option, - index_) + index_, + False) value = await get_value(callbk, option_bag, path) if with_index: value = value[index] diff --git a/tiramisu/config.py b/tiramisu/config.py index 0efaed5..9e957a1 100644 --- a/tiramisu/config.py +++ b/tiramisu/config.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -148,7 +148,7 @@ class SubConfig: doption_bag.set_option(option, option_bag.index, option_bag.config_bag) - doption_bag.properties = await self.cfgimpl_get_settings().getproperties(doption_bag) + doption_bag.properties = None await self.reset_one_option_cache(desc, resetted_opts, doption_bag) @@ -212,9 +212,7 @@ class SubConfig: async def setattr(self, value, - option_bag, - _commit=True): - + option_bag): if option_bag.option.impl_is_symlinkoption(): raise ConfigError(_("can't set value to a SymLinkOption")) context = option_bag.config_bag.context @@ -223,22 +221,18 @@ class SubConfig: raise LeadershipError(_('cannot reduce length of the leader "{}"' '').format(option_bag.option.impl_get_display_name())) return await context.cfgimpl_get_values().setvalue(value, - option_bag, - _commit) + option_bag) async def delattr(self, - option_bag, - _commit=True): + option_bag): option = option_bag.option if option.impl_is_symlinkoption(): raise ConfigError(_("can't delete a SymLinkOption")) values = self.cfgimpl_get_values() if option_bag.index is not None: - await values.reset_follower(option_bag, - _commit) + await values.reset_follower(option_bag) else: - await values.reset(option_bag, - _commit) + await values.reset(option_bag) def _get_subpath(self, name): if self._impl_path is None: @@ -261,7 +255,8 @@ class SubConfig: name, option_bag, from_follower=False, - needs_re_verify_follower_properties=False): + needs_re_verify_follower_properties=False, + need_help=True): """ :return: option's value if name is an option name, OptionDescription otherwise @@ -289,17 +284,20 @@ class SubConfig: if not option.impl_is_follower() or \ (needs_re_verify_follower_properties and option_bag.index is not None) or \ (not needs_re_verify_follower_properties and (not from_follower or option_bag.index is None)): - await self.cfgimpl_get_settings().validate_properties(option_bag) + await self.cfgimpl_get_settings().validate_properties(option_bag, + need_help=need_help) if option.impl_is_follower() and not from_follower: length = await self.cfgimpl_get_length_leadership(option_bag) - follower_len = await self.cfgimpl_get_values()._p_.get_max_length(option_bag.path) + follower_len = await self.cfgimpl_get_values()._p_.get_max_length(option_bag.config_bag.connection, + option_bag.path) if follower_len > length: raise LeadershipError(_('the follower option "{}" has greater length ({}) than the leader ' 'length ({})').format(option.impl_get_display_name(), follower_len, length, option_bag.index)) + if option.impl_is_follower() and option_bag.index is None: value = [] for idx in range(length): @@ -307,8 +305,8 @@ class SubConfig: soption_bag.set_option(option, idx, config_bag) - soption_bag.properties = await self.cfgimpl_get_settings().getproperties(soption_bag) try: + soption_bag.properties = await self.cfgimpl_get_settings().getproperties(soption_bag) value.append(await self.getattr(name, soption_bag, from_follower=True, @@ -422,7 +420,8 @@ class SubConfig: pathsvalues, leader_to_list): for opt in await self.cfgimpl_get_description().get_children(config_bag): - if opt.impl_is_optiondescription() and leader_to_list and opt.impl_is_leadership(): + if leader_to_list and opt.impl_is_optiondescription() and opt.impl_is_leadership(): + # leader children = await opt.get_children(config_bag) leader = children[0] loption_bag = OptionBag() @@ -453,27 +452,36 @@ class SubConfig: foption_bag.set_option(follower_opt, idx, config_bag) - foption_bag.properties = await self.cfgimpl_get_settings().getproperties(foption_bag) - await subconfig._make_sub_dict(leadership_pathsvalues, - leader_currpath, - foption_bag, - flatten, - fullpath, - leader_to_list) + try: + foption_bag.properties = await self.cfgimpl_get_settings().getproperties(foption_bag) + await subconfig._make_sub_dict(leadership_pathsvalues, + leader_currpath, + foption_bag, + flatten, + fullpath, + leader_to_list) + except PropertiesOptionError as err: + if err.proptype in (['mandatory'], ['empty']): + raise err + continue pathsvalues[leader_name].append(leadership_pathsvalues) else: soption_bag = OptionBag() soption_bag.set_option(opt, None, config_bag) - soption_bag.properties = await self.cfgimpl_get_settings().getproperties(soption_bag) - await self._make_sub_dict(pathsvalues, - _currpath, - soption_bag, - flatten, - fullpath, - leader_to_list) - return pathsvalues + try: + soption_bag.properties = await self.cfgimpl_get_settings().getproperties(soption_bag) + await self._make_sub_dict(pathsvalues, + _currpath, + soption_bag, + flatten, + fullpath, + leader_to_list) + except PropertiesOptionError as err: + if err.proptype in (['mandatory'], ['empty']): + raise err + continue async def _make_sub_dict(self, pathsvalues, @@ -485,31 +493,22 @@ class SubConfig: option = option_bag.option name = option.impl_getname() if option.impl_is_optiondescription(): - try: - await self.cfgimpl_get_settings().validate_properties(option_bag) - subconfig = await SubConfig(option_bag.option, - self._impl_context, - option_bag.config_bag, - option_bag.path) - await subconfig._make_dict(option_bag.config_bag, - _currpath + [name], - flatten, - fullpath, - pathsvalues, - leader_to_list) - except PropertiesOptionError as err: - if err.proptype in (['mandatory'], ['empty']): - raise err + await self.cfgimpl_get_settings().validate_properties(option_bag, + need_help=False) + subconfig = await SubConfig(option_bag.option, + self._impl_context, + option_bag.config_bag, + option_bag.path) + await subconfig._make_dict(option_bag.config_bag, + _currpath + [name], + flatten, + fullpath, + pathsvalues, + leader_to_list) else: - try: - ret = await self.getattr(name, - option_bag) - except PropertiesOptionError as err: - # import traceback - # traceback.print_exc() - if err.proptype in (['mandatory'], ['empty']): - raise err - return + ret = await self.getattr(name, + option_bag, + need_help=False) if flatten: name_ = option.impl_getname() elif fullpath: @@ -551,6 +550,7 @@ class _CommonConfig(SubConfig): # information async def impl_set_information(self, + connection, key, value): """updates the information's attribute @@ -558,48 +558,56 @@ class _CommonConfig(SubConfig): :param key: information's key (ex: "help", "doc" :param value: information's value (ex: "the help string") """ - await self._impl_values.set_information(key, + await self._impl_values.set_information(connection, + key, value) async def impl_get_information(self, + connection, key, default=undefined): """retrieves one information's item :param key: the item string (ex: "help") """ - return await self._impl_values.get_information(key, + return await self._impl_values.get_information(connection, + key, default) async def impl_del_information(self, + connection, key, raises=True): - await self._impl_values.del_information(key, + await self._impl_values.del_information(connection, + key, raises) - async def impl_list_information(self): - return await self._impl_values.list_information() + async def impl_list_information(self, + connection): + return await self._impl_values.list_information(connection) def __getstate__(self): raise NotImplementedError() - async def _gen_fake_values(self): + async def _gen_fake_values(self, + connection): fake_config = await KernelConfig(self._impl_descr, - persistent=False, - force_values=await get_default_values_storages(), + force_values=await get_default_values_storages(connection), force_settings=self.cfgimpl_get_settings(), - display_name=self._display_name) - export = await self.cfgimpl_get_values()._p_.exportation() - await fake_config.cfgimpl_get_values()._p_.importation(export) + display_name=self._display_name, + connection=connection) + export = await self.cfgimpl_get_values()._p_.exportation(connection) + await fake_config.cfgimpl_get_values()._p_.importation(connection, + export) fake_config.parents = self.parents return fake_config async def duplicate(self, + connection, session_id=None, force_values=None, force_settings=None, storage=None, - persistent=False, metaconfig_prefix=None, child=None, deep=None): @@ -610,8 +618,8 @@ class _CommonConfig(SubConfig): session_id=session_id, force_values=force_values, force_settings=force_settings, - persistent=persistent, storage=storage, + connection=connection, display_name=self._display_name) else: if session_id is None and metaconfig_prefix is not None: @@ -620,15 +628,18 @@ class _CommonConfig(SubConfig): _duplicate=True, optiondescription=self._impl_descr, session_id=session_id, - persistent=persistent, storage=storage, + connection=connection, display_name=self._display_name) duplicated_values = duplicated_config.cfgimpl_get_values() duplicated_settings = duplicated_config.cfgimpl_get_settings() - await duplicated_values._p_.importation(await self.cfgimpl_get_values()._p_.exportation()) - properties = await self.cfgimpl_get_settings()._p_.exportation() - await duplicated_settings._p_.importation(properties) - await duplicated_settings._pp_.importation(await self.cfgimpl_get_settings()._pp_.exportation()) + await duplicated_values._p_.importation(connection, + await self.cfgimpl_get_values()._p_.exportation(connection)) + properties = await self.cfgimpl_get_settings()._p_.exportation(connection) + await duplicated_settings._p_.importation(connection, + properties) + await duplicated_settings._pp_.importation(connection, + await self.cfgimpl_get_settings()._pp_.exportation(connection)) duplicated_settings.ro_append = self.cfgimpl_get_settings().ro_append duplicated_settings.rw_append = self.cfgimpl_get_settings().rw_append duplicated_settings.ro_remove = self.cfgimpl_get_settings().ro_remove @@ -644,11 +655,11 @@ class _CommonConfig(SubConfig): wparent = parent() if wparent not in deep: deep.append(wparent) - duplicated_config = await wparent.duplicate(deep=deep, + duplicated_config = await wparent.duplicate(connection, + deep=deep, storage=storage, metaconfig_prefix=metaconfig_prefix, - child=duplicated_config, - persistent=persistent) + child=duplicated_config) else: duplicated_config.parents = self.parents for parent in self.parents: @@ -672,13 +683,15 @@ class KernelConfig(_CommonConfig): __slots__ = ('__weakref__', '_impl_name', '_display_name', - '_impl_symlink') + '_impl_symlink', + '_storage') impl_type = 'config' async def __init__(self, descr, + connection, session_id=None, - persistent=False, + delete_old_session=False, force_values=None, force_settings=None, display_name=None, @@ -690,11 +703,8 @@ class KernelConfig(_CommonConfig): :type descr: an instance of ``option.OptionDescription`` :param context: the current root config :type context: `Config` - :param session_id: session ID is import with persistent Config to - retrieve good session + :param session_id: name of the session :type session_id: `str` - :param persistent: if persistent, don't delete storage when leaving - :type persistent: `boolean` """ self.parents = [] self._impl_symlink = [] @@ -711,21 +721,25 @@ class KernelConfig(_CommonConfig): self._impl_settings = force_settings self._impl_permissives_cache = Cache() self._impl_properties_cache = Cache() - self._impl_values = await Values(force_values) + self._impl_values = await Values(force_values, + connection) self._impl_values_cache = Cache() else: - properties, permissives, values, session_id = await get_storages(self, - session_id, - persistent, - storage=storage) + storage, properties, permissives, values, session_id = await get_storages(self, + session_id, + delete_old_session, + storage, + connection) if not valid_name(session_id): raise ValueError(_("invalid session ID: {0} for config").format(session_id)) self._impl_settings = Settings(properties, permissives) self._impl_permissives_cache = Cache() self._impl_properties_cache = Cache() - self._impl_values = await Values(values) + self._impl_values = await Values(values, + connection) self._impl_values_cache = Cache() + self._storage = storage self._impl_context = weakref.ref(self) await super().__init__(descr, self._impl_context, @@ -738,6 +752,9 @@ class KernelConfig(_CommonConfig): def impl_getname(self): return self._impl_name + def getconnection(self): + return self.cfgimpl_get_settings()._p_.getconnection() + @asyncinit class KernelGroupConfig(_CommonConfig): @@ -803,17 +820,10 @@ class KernelGroupConfig(_CommonConfig): index, value, config_bag, - only_config=False, - _commit=True): + only_config=False): """Setattr not in current KernelGroupConfig, but in each children """ ret = [] - if self.impl_type == 'group': - # No value so cannot commit only one time - commit = True - else: - # Commit only one time - commit = False for child in self._impl_children: cconfig_bag = config_bag.copy() cconfig_bag.context = child @@ -822,12 +832,12 @@ class KernelGroupConfig(_CommonConfig): index, value, cconfig_bag, - only_config=only_config, - _commit=commit)) + only_config=only_config)) else: settings = child.cfgimpl_get_settings() - properties = await settings.get_context_properties(child._impl_properties_cache) - permissives = await settings.get_context_permissives() + properties = await settings.get_context_properties(config_bag.connection, + child._impl_properties_cache) + permissives = await settings.get_context_permissives(config_bag.connection) cconfig_bag.properties = properties cconfig_bag.permissives = permissives try: @@ -842,8 +852,7 @@ class KernelGroupConfig(_CommonConfig): cconfig_bag) option_bag.properties = await settings.getproperties(option_bag) await child.setattr(value, - option_bag, - _commit=commit) + option_bag) except PropertiesOptionError as err: ret.append(PropertiesOptionError(err._option_bag, err.proptype, @@ -853,8 +862,6 @@ class KernelGroupConfig(_CommonConfig): err._orig_opt)) except (ValueError, LeadershipError, AttributeError) as err: ret.append(err) - if _commit and self.impl_type != 'group': - await self.cfgimpl_get_values()._p_.commit() return ret @@ -896,8 +903,9 @@ class KernelGroupConfig(_CommonConfig): cconfig_bag = config_bag.copy() cconfig_bag.context = child settings = child.cfgimpl_get_settings() - properties = await settings.get_context_properties(child._impl_properties_cache) - permissives = await settings.get_context_permissives() + properties = await settings.get_context_properties(config_bag.connection, + child._impl_properties_cache) + permissives = await settings.get_context_permissives(config_bag.connection) cconfig_bag.properties = properties cconfig_bag.permissives = permissives async for path in child.find(None, @@ -918,15 +926,17 @@ class KernelGroupConfig(_CommonConfig): return self._impl_name async def reset(self, - path, - _commit=True): + connection, + path): for child in self._impl_children: settings = child.cfgimpl_get_settings() - properties = await settings.get_context_properties(child._impl_properties_cache) - permissives = await settings.get_context_permissives() + properties = await settings.get_context_properties(connection, + child._impl_properties_cache) + permissives = await settings.get_context_permissives(connection) config_bag = ConfigBag(child, properties=properties, permissives=permissives) + config_bag.connection = connection config_bag.remove_validation() subconfig, name = await child.cfgimpl_get_home_by_path(path, config_bag) @@ -939,8 +949,7 @@ class KernelGroupConfig(_CommonConfig): config_bag) option_bag.properties = await child.cfgimpl_get_settings().getproperties(option_bag) option_bag.config_bag.context = child - await child.cfgimpl_get_values().reset(option_bag, - _commit=_commit) + await child.cfgimpl_get_values().reset(option_bag) def getconfig(self, name): @@ -949,18 +958,26 @@ class KernelGroupConfig(_CommonConfig): return child raise ConfigError(_('unknown config "{}"').format(name)) + def getconnection(self): + if self.impl_type == 'group': + # Get the first storage, assume that all children have same storage + return self._impl_children[0].getconnection() + return self.cfgimpl_get_settings()._p_.getconnection() + @asyncinit class KernelMixConfig(KernelGroupConfig): __slots__ = ('_display_name', - '_impl_symlink') + '_impl_symlink', + '_storage') impl_type = 'mix' async def __init__(self, optiondescription, children, + connection, session_id=None, - persistent=False, + delete_old_session=False, storage=None, display_name=None, _duplicate=False): @@ -971,16 +988,19 @@ class KernelMixConfig(KernelGroupConfig): if not isinstance(child, (KernelConfig, KernelMixConfig)): raise TypeError(_("child must be a Config, MixConfig or MetaConfig")) child.parents.append(weakref.ref(self)) - properties, permissives, values, session_id = await get_storages(self, - session_id, - persistent, - storage=storage) + storage, properties, permissives, values, session_id = await get_storages(self, + session_id, + delete_old_session, + storage, + connection) self._impl_settings = Settings(properties, permissives) self._impl_permissives_cache = Cache() self._impl_properties_cache = Cache() - self._impl_values = await Values(values) + self._impl_values = await Values(values, + connection) self._impl_values_cache = Cache() + self._storage = storage await super().__init__(children, session_id=session_id, _descr=optiondescription) @@ -994,8 +1014,7 @@ class KernelMixConfig(KernelGroupConfig): force_default=False, force_dont_change_value=False, force_default_if_same=False, - only_config=False, - _commit=True): + only_config=False): """only_config: could be set if you want modify value in all Config included in this KernelMetaConfig """ @@ -1008,8 +1027,7 @@ class KernelMixConfig(KernelGroupConfig): index, value, config_bag, - only_config=only_config, - _commit=_commit) + only_config=only_config) ret = [] subconfig, name = await self.cfgimpl_get_home_by_path(path, config_bag) @@ -1029,8 +1047,9 @@ class KernelMixConfig(KernelGroupConfig): cconfig_bag = config_bag.copy() cconfig_bag.context = child settings = child.cfgimpl_get_settings() - properties = await settings.get_context_properties(child._impl_properties_cache) - permissives = await settings.get_context_permissives() + properties = await settings.get_context_properties(config_bag.connection, + child._impl_properties_cache) + permissives = await settings.get_context_permissives(config_bag.connection) cconfig_bag.properties = properties cconfig_bag.permissives = permissives try: @@ -1053,22 +1072,21 @@ class KernelMixConfig(KernelGroupConfig): cconfig_bag) moption_bag.properties = await settings.getproperties(moption_bag) if force_default_if_same: - if not await child.cfgimpl_get_values()._p_.hasvalue(path): + if not await child.cfgimpl_get_values()._p_.hasvalue(config_bag.connection, + path): child_value = undefined else: child_value = await subconfig2.getattr(name, moption_bag) if force_default or (force_default_if_same and value == child_value): - await child.cfgimpl_get_values().reset(moption_bag, - _commit=False) + await child.cfgimpl_get_values().reset(moption_bag) continue if force_dont_change_value: child_value = await child.getattr(name, moption_bag) if value != child_value: await subconfig2.setattr(child_value, - moption_bag, - _commit=False) + moption_bag) except PropertiesOptionError as err: ret.append(PropertiesOptionError(err._option_bag, err.proptype, @@ -1089,8 +1107,7 @@ class KernelMixConfig(KernelGroupConfig): else: moption_bag = option_bag await subconfig.setattr(value, - moption_bag, - _commit=False) + moption_bag) except (PropertiesOptionError, ValueError, LeadershipError) as err: ret.append(err) return ret @@ -1098,8 +1115,7 @@ class KernelMixConfig(KernelGroupConfig): async def reset(self, path, only_children, - config_bag, - commit=True): + config_bag): rconfig_bag = config_bag.copy() rconfig_bag.remove_validation() if self.impl_type == 'meta': @@ -1144,21 +1160,16 @@ class KernelMixConfig(KernelGroupConfig): None, rconfig_bag) moption_bag.properties = await self.cfgimpl_get_settings().getproperties(moption_bag) - await child.cfgimpl_get_values().reset(moption_bag, - _commit=False) + await child.cfgimpl_get_values().reset(moption_bag) except AttributeError: pass if isinstance(child, KernelMixConfig): await child.reset(path, False, - rconfig_bag, - commit=False) + rconfig_bag) if not only_children: option_bag.config_bag = config_bag - await self.cfgimpl_get_values().reset(option_bag, - _commit=False) - if commit: - await self.cfgimpl_get_values()._p_.commit() + await self.cfgimpl_get_values().reset(option_bag) async def add_config(self, apiconfig): @@ -1201,8 +1212,9 @@ class KernelMetaConfig(KernelMixConfig): async def __init__(self, children, + connection, session_id=None, - persistent=False, + delete_old_session=False, optiondescription=None, storage=None, display_name=None, @@ -1217,7 +1229,8 @@ class KernelMetaConfig(KernelMixConfig): ' must have string has child, ' 'not {}').format(child_session_id) new_children.append(await KernelConfig(optiondescription, - persistent=persistent, + connection, + delete_old_session=delete_old_session, session_id=child_session_id, display_name=self._display_name)) children = new_children @@ -1233,46 +1246,51 @@ class KernelMetaConfig(KernelMixConfig): 'have the same optiondescription')) await super().__init__(descr, children, - persistent=persistent, + connection, + delete_old_session=delete_old_session, storage=storage, session_id=session_id) async def new_config(self, + connection, session_id, type_='config', - persistent=False, storage=None): if session_id in [child.impl_getname() for child in self._impl_children]: raise ConflictError(_('config name must be uniq in ' 'groupconfig for {0}').format(session_id)) assert type_ in ('config', 'metaconfig', 'mixconfig'), _('unknown type {}').format(type_) - new = not persistent or session_id not in list_sessions() + new = session_id not in await list_sessions() if type_ == 'config': config = await KernelConfig(self._impl_descr, session_id=session_id, - persistent=persistent, storage=storage, + connection=connection, display_name=self._display_name) elif type_ == 'metaconfig': config = await KernelMetaConfig([], optiondescription=self._impl_descr, session_id=session_id, - persistent=persistent, storage=storage, + connection=connection, display_name=self._display_name) elif type_ == 'mixconfig': config = await KernelMixConfig(children=[], optiondescription=self._impl_descr, session_id=session_id, - persistent=persistent, storage=storage, + connection=connection, display_name=self._display_name) # Copy context properties/permissives if new: settings = config.cfgimpl_get_settings() - properties = await self.cfgimpl_get_settings().get_context_properties(config._impl_properties_cache) - await settings.set_context_properties(properties, config) - await settings.set_context_permissives(await self.cfgimpl_get_settings().get_context_permissives()) + properties = await self.cfgimpl_get_settings().get_context_properties(connection, + config._impl_properties_cache) + await settings.set_context_properties(connection, + properties, + config) + await settings.set_context_permissives(connection, + await self.cfgimpl_get_settings().get_context_permissives(connection)) settings.ro_append = self.cfgimpl_get_settings().ro_append settings.rw_append = self.cfgimpl_get_settings().rw_append settings.ro_remove = self.cfgimpl_get_settings().ro_remove diff --git a/tiramisu/error.py b/tiramisu/error.py index 4bb14ff..d97e0ab 100644 --- a/tiramisu/error.py +++ b/tiramisu/error.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -57,7 +57,8 @@ class PropertiesOptionError(AttributeError): settings, opt_type=None, name=None, - orig_opt=None): + orig_opt=None, + help_properties=None): if opt_type: self._opt_type = opt_type self._name = name @@ -71,6 +72,7 @@ class PropertiesOptionError(AttributeError): self._orig_opt = None self._option_bag = option_bag self.proptype = proptype + self.help_properties = help_properties self._settings = settings self.msg = None super().__init__(None) @@ -84,12 +86,10 @@ class PropertiesOptionError(AttributeError): return self.msg if self._settings is None: return 'error' - #for property_ in self._settings.get_calculated_properties(self._option_bag): - # prop = property_.help(self._option_bag) - # if prop is not None: - # properties.append(prop) - - properties = list(self.proptype) + if self.help_properties: + properties = list(self.help_properties) + else: + properties = list(self.proptype) only_one = len(properties) == 1 properties_msg = display_list(properties, add_quote=True) if only_one: diff --git a/tiramisu/function.py b/tiramisu/function.py index 8ff5671..23e0da1 100644 --- a/tiramisu/function.py +++ b/tiramisu/function.py @@ -1,4 +1,4 @@ -# Copyright (C) 2018-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2018-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -510,8 +510,8 @@ class CalcValuePropertyHelp(CalcValue): msgs.append(self.build_arg(name, f'"{value}"')) msg = display_list(msgs, self.condition_operator.lower()) else: - return [f'"{action}"'] - return [f'"{action}" ({msg})'] + return [(action, f'"{action}"')] + return [(action, f'"{action}" ({msg})')] return ## calc_properties.setdefault(action, []).append(msg) diff --git a/tiramisu/i18n.py b/tiramisu/i18n.py index 756a1c0..f4d4e0e 100644 --- a/tiramisu/i18n.py +++ b/tiramisu/i18n.py @@ -1,5 +1,5 @@ # -*- coding: UTF-8 -*- -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/log.py b/tiramisu/log.py index 31aae0a..6b2e1f2 100644 --- a/tiramisu/log.py +++ b/tiramisu/log.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "logger for tiramisu" -# Copyright (C) 2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2019-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/baseoption.py b/tiramisu/option/baseoption.py index 6b4b6aa..902a60d 100644 --- a/tiramisu/option/baseoption.py +++ b/tiramisu/option/baseoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2014-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2014-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/booloption.py b/tiramisu/option/booloption.py index 2a8cb64..5a6da8f 100644 --- a/tiramisu/option/booloption.py +++ b/tiramisu/option/booloption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/broadcastoption.py b/tiramisu/option/broadcastoption.py index f071542..3e1b736 100644 --- a/tiramisu/option/broadcastoption.py +++ b/tiramisu/option/broadcastoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/choiceoption.py b/tiramisu/option/choiceoption.py index e4392d0..babf658 100644 --- a/tiramisu/option/choiceoption.py +++ b/tiramisu/option/choiceoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/dateoption.py b/tiramisu/option/dateoption.py index 64b21e6..eb52777 100644 --- a/tiramisu/option/dateoption.py +++ b/tiramisu/option/dateoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/domainnameoption.py b/tiramisu/option/domainnameoption.py index c246231..a313b70 100644 --- a/tiramisu/option/domainnameoption.py +++ b/tiramisu/option/domainnameoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/dynoptiondescription.py b/tiramisu/option/dynoptiondescription.py index 1866692..324b031 100644 --- a/tiramisu/option/dynoptiondescription.py +++ b/tiramisu/option/dynoptiondescription.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/emailoption.py b/tiramisu/option/emailoption.py index 5fd3e14..2878008 100644 --- a/tiramisu/option/emailoption.py +++ b/tiramisu/option/emailoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/filenameoption.py b/tiramisu/option/filenameoption.py index a75934f..ad0d2cb 100644 --- a/tiramisu/option/filenameoption.py +++ b/tiramisu/option/filenameoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/floatoption.py b/tiramisu/option/floatoption.py index 43faef8..fa881bf 100644 --- a/tiramisu/option/floatoption.py +++ b/tiramisu/option/floatoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/intoption.py b/tiramisu/option/intoption.py index 22e96de..c7b1d93 100644 --- a/tiramisu/option/intoption.py +++ b/tiramisu/option/intoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/ipoption.py b/tiramisu/option/ipoption.py index 0741e31..cde3283 100644 --- a/tiramisu/option/ipoption.py +++ b/tiramisu/option/ipoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/leadership.py b/tiramisu/option/leadership.py index 5a943f3..81aebe4 100644 --- a/tiramisu/option/leadership.py +++ b/tiramisu/option/leadership.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "Leadership support" -# Copyright (C) 2014-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2014-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -113,8 +113,7 @@ class Leadership(OptionDescription): async def reset(self, values: Values, - option_bag: OptionBag, - _commit: bool=True) -> None: + option_bag: OptionBag) -> None: config_bag = option_bag.config_bag.copy() config_bag.remove_validation() for follower in self.get_followers(): @@ -123,15 +122,13 @@ class Leadership(OptionDescription): None, config_bag) soption_bag.properties = await config_bag.context.cfgimpl_get_settings().getproperties(soption_bag) - await values.reset(soption_bag, - _commit=_commit) + await values.reset(soption_bag) async def follower_force_store_value(self, values, value, option_bag, owner, - _commit, dyn=None) -> None: settings = option_bag.config_bag.context.cfgimpl_get_settings() if value: @@ -152,8 +149,7 @@ class Leadership(OptionDescription): foption_bag.properties = await settings.getproperties(foption_bag) await values._setvalue(foption_bag, await values.getvalue(foption_bag), - owner, - commit=False) + owner) async def pop(self, values: Values, @@ -167,7 +163,8 @@ class Leadership(OptionDescription): config_bag.remove_validation() for follower in followers: follower_path = follower.impl_getpath() - followerlen = await values._p_.get_max_length(follower_path) + followerlen = await values._p_.get_max_length(config_bag.connection, + follower_path) soption_bag = OptionBag() soption_bag.set_option(follower, index, @@ -177,13 +174,16 @@ class Leadership(OptionDescription): is_default = await values.is_default_owner(soption_bag, validate_meta=False) if not is_default and followerlen > index: - await values._p_.resetvalue_index(follower_path, - index, - True) + await values._p_.resetvalue_index(config_bag.connection, + follower_path, + index) if followerlen > index + 1: for idx in range(index + 1, followerlen): - if await values._p_.hasvalue(follower_path, idx): - await values._p_.reduce_index(follower_path, + if await values._p_.hasvalue(config_bag.connection, + follower_path, + idx): + await values._p_.reduce_index(config_bag.connection, + follower_path, idx) def reset_cache(self, diff --git a/tiramisu/option/netmaskoption.py b/tiramisu/option/netmaskoption.py index a61c7ad..a4f5d95 100644 --- a/tiramisu/option/netmaskoption.py +++ b/tiramisu/option/netmaskoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/networkoption.py b/tiramisu/option/networkoption.py index 54d3da4..9f30148 100644 --- a/tiramisu/option/networkoption.py +++ b/tiramisu/option/networkoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/option.py b/tiramisu/option/option.py index f330709..39fd1f2 100644 --- a/tiramisu/option/option.py +++ b/tiramisu/option/option.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "option types and option description" -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/optiondescription.py b/tiramisu/option/optiondescription.py index 6252cef..7492e6a 100644 --- a/tiramisu/option/optiondescription.py +++ b/tiramisu/option/optiondescription.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2014-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2014-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -109,10 +109,10 @@ class CacheOptionDescription(BaseOption): config_bag: ConfigBag) -> None: if 'force_store_value' not in config_bag.properties: return - commit = False values = config_bag.context.cfgimpl_get_values() for subpath, option in self._cache_force_store_values: - if not await values._p_.hasvalue(subpath): + if not await values._p_.hasvalue(config_bag.connection, + subpath): if option.impl_is_follower(): option_bag = OptionBag() leader = option.impl_get_leadership().get_leader() @@ -127,7 +127,8 @@ class CacheOptionDescription(BaseOption): index, config_bag) option_bag.properties = frozenset() - await values._p_.setvalue(subpath, + await values._p_.setvalue(config_bag.connection, + subpath, await values.getvalue(option_bag), owners.forced, index, @@ -138,15 +139,12 @@ class CacheOptionDescription(BaseOption): None, config_bag) option_bag.properties = frozenset() - await values._p_.setvalue(subpath, + await values._p_.setvalue(config_bag.connection, + subpath, await values.getvalue(option_bag), owners.forced, None, False) - commit = True - - if commit: - await values._p_.commit() class OptionDescriptionWalk(CacheOptionDescription): diff --git a/tiramisu/option/passwordoption.py b/tiramisu/option/passwordoption.py index 62d4004..008385f 100644 --- a/tiramisu/option/passwordoption.py +++ b/tiramisu/option/passwordoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/portoption.py b/tiramisu/option/portoption.py index b8c7927..af0ddf9 100644 --- a/tiramisu/option/portoption.py +++ b/tiramisu/option/portoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/stroption.py b/tiramisu/option/stroption.py index a6c636c..58941c4 100644 --- a/tiramisu/option/stroption.py +++ b/tiramisu/option/stroption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/symlinkoption.py b/tiramisu/option/symlinkoption.py index 7eac410..22e8c5d 100644 --- a/tiramisu/option/symlinkoption.py +++ b/tiramisu/option/symlinkoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/syndynoption.py b/tiramisu/option/syndynoption.py index 7dcbca2..b72bbca 100644 --- a/tiramisu/option/syndynoption.py +++ b/tiramisu/option/syndynoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2018-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2018-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/syndynoptiondescription.py b/tiramisu/option/syndynoptiondescription.py index 0773896..8bf7c9f 100644 --- a/tiramisu/option/syndynoptiondescription.py +++ b/tiramisu/option/syndynoptiondescription.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -103,7 +103,7 @@ class SynDynOptionDescription: config_bag, self): yield option - + def impl_getpath(self) -> str: subpath = self._subpath if subpath != '': @@ -150,11 +150,9 @@ class SynDynLeadership(SynDynOptionDescription): values, value, option_bag, - owner, - _commit) -> None: + owner) -> None: await self._opt.follower_force_store_value(values, value, option_bag, owner, - _commit, dyn=self) diff --git a/tiramisu/option/urloption.py b/tiramisu/option/urloption.py index 2b0c298..64b45b7 100644 --- a/tiramisu/option/urloption.py +++ b/tiramisu/option/urloption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/option/usernameoption.py b/tiramisu/option/usernameoption.py index 02e98c8..2c25ba9 100644 --- a/tiramisu/option/usernameoption.py +++ b/tiramisu/option/usernameoption.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2017-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/setting.py b/tiramisu/setting.py index b10f9cb..04d3c48 100644 --- a/tiramisu/setting.py +++ b/tiramisu/setting.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "sets the options of the configuration objects Config object itself" -# Copyright (C) 2012-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2012-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -192,7 +192,8 @@ class ConfigBag: 'true_properties', # properties for current context 'is_unrestraint', 'permissives', # permissives for current context - 'expiration_time' # EXPIRATION_TIME + 'expiration_time', # EXPIRATION_TIME + 'connection', ) def __init__(self, @@ -236,7 +237,10 @@ class ConfigBag: def copy(self): kwargs = {} for key in self.__slots__: - kwargs[key] = getattr(self, key) + try: + kwargs[key] = getattr(self, key) + except KeyError: + pass return ConfigBag(**kwargs) @@ -374,9 +378,6 @@ class Settings(object): :param context: the root config :param storage: the storage type - - - dictionary -> in memory - - sqlite3 -> persistent """ # generic owner self._p_ = properties @@ -391,6 +392,7 @@ class Settings(object): # get properties and permissive methods async def get_context_properties(self, + connection, cache): is_cached, props, validated = cache.getcache(None, None, @@ -399,7 +401,8 @@ class Settings(object): {}, 'context_props') if not is_cached: - props = await self._p_.getproperties(None, + props = await self._p_.getproperties(connection, + None, None, self.default_properties) cache.setcache(None, @@ -413,7 +416,8 @@ class Settings(object): async def getproperties(self, option_bag, apply_requires=True, - uncalculated=False): + uncalculated=False, + help_property=False): """ """ option = option_bag.option @@ -422,44 +426,58 @@ class Settings(object): option = option.impl_getopt() path = option.impl_getpath() index = option_bag.index - if apply_requires and not uncalculated: + if apply_requires and not uncalculated and not help_property: cache = config_bag.context._impl_properties_cache - config_bag_props = config_bag.properties is_cached, props, validated = cache.getcache(path, config_bag.expiration_time, index, - config_bag_props, + config_bag.properties, {}, 'self_props') else: is_cached = False if not is_cached: props = set() - p_props = await self._p_.getproperties(path, + # if index, get option's properties (without index) too + p_props = await self._p_.getproperties(config_bag.connection, + path, None, option.impl_getproperties()) if index is not None: p_props = chain(p_props, - await self._p_.getproperties(path, + await self._p_.getproperties(config_bag.connection, + path, index, option.impl_getproperties())) for prop in p_props: if uncalculated or isinstance(prop, str): - props.add(prop) + if not help_property: + props.add(prop) + else: + props.add((prop, prop)) elif apply_requires: - new_prop = await prop.execute(option_bag, - leadership_must_have_index=True) + if not help_property: + new_prop = await prop.execute(option_bag, + leadership_must_have_index=True) + else: + new_prop = await prop.help(option_bag, + leadership_must_have_index=True) + if isinstance(new_prop, str): + new_prop = (new_prop, new_prop) if new_prop is None: continue - elif not isinstance(new_prop, str): + elif (not help_property and not isinstance(new_prop, str)) or \ + (help_property and not isinstance(new_prop, tuple)): raise ValueError(_('invalid property type {} for {} with {} function').format(type(new_prop), option_bag.option.impl_getname(), prop.function.__name__)) - if not option.impl_is_optiondescription() and option.impl_is_leader() and new_prop not in ALLOWED_LEADER_PROPERTIES: + if not option.impl_is_optiondescription() and \ + option.impl_is_leader() and \ + new_prop not in ALLOWED_LEADER_PROPERTIES: raise LeadershipError(_('leader cannot have "{}" property').format(new_prop)) props.add(new_prop) props -= await self.getpermissives(option_bag) - if not uncalculated and apply_requires and not config_bag.is_unrestraint: + if not uncalculated and apply_requires and not config_bag.is_unrestraint and not help_property: cache.setcache(path, index, props, @@ -468,36 +486,20 @@ class Settings(object): True) return props - async def get_calculated_properties(self, - option_bag): - option = option_bag.option - if option.impl_is_symlinkoption(): - option = option.impl_getopt() - path = option.impl_getpath() - p_props = await self._p_.getproperties(path, - None, - option.impl_getproperties()) - if option_bag.index is not None: - p_props = chain(p_props, - await self._p_.getproperties(path, - option_bag.index, - option.impl_getproperties())) - for prop in p_props: - if not isinstance(prop, str): - yield prop - async def has_properties_index(self, option_bag): option = option_bag.option if option.impl_is_symlinkoption(): option = option.impl_getopt() path = option.impl_getpath() - p_props = await self._p_.getproperties(path, + p_props = await self._p_.getproperties(option_bag.config_bag.connection, + path, None, option.impl_getproperties()) if option_bag.index is not None: p_props = chain(p_props, - await self._p_.getproperties(path, + await self._p_.getproperties(option_bag.config_bag.connection, + path, option_bag.index, option.impl_getproperties())) for prop in p_props: @@ -505,11 +507,14 @@ class Settings(object): return True return False - async def get_context_permissives(self): - return await self.getpermissives(None) + async def get_context_permissives(self, + connection): + return await self.getpermissives(None, + connection=connection) async def getpermissives(self, - option_bag): + option_bag, + connection=None): if option_bag is None: path = None index = None @@ -521,18 +526,25 @@ class Settings(object): else: path = option_bag.path index = option_bag.index - permissives = await self._pp_.getpermissives(path, None) + connection = option_bag.config_bag.connection + permissives = await self._pp_.getpermissives(connection, + path, + None) if index is not None: - option_permissives = await self._pp_.getpermissives(path, index) + option_permissives = await self._pp_.getpermissives(connection, + path, + index) permissives = frozenset(option_permissives | permissives) return permissives #____________________________________________________________ # set methods async def set_context_properties(self, + connection, properties, context): - await self._p_.setproperties(None, + await self._p_.setproperties(connection, + None, None, properties) await context.cfgimpl_reset_cache(None) @@ -561,7 +573,8 @@ class Settings(object): raise LeadershipError(_('a leader ({0}) cannot have ' '"force_default_on_freeze" or "force_metaconfig_on_freeze" property without "frozen"' '').format(opt.impl_get_display_name())) - await self._p_.setproperties(path, + await self._p_.setproperties(option_bag.config_bag.connection, + path, option_bag.index, properties) # values too because of follower values could have a PropertiesOptionError has value @@ -569,13 +582,16 @@ class Settings(object): option_bag.properties = properties async def set_context_permissives(self, + connection, permissives): await self.setpermissives(None, - permissives) + permissives, + connection=connection) async def setpermissives(self, option_bag, - permissives): + permissives, + connection=None): """ enables us to put the permissives in the storage @@ -594,6 +610,7 @@ class Settings(object): "").format(opt.impl_get_display_name())) path = option_bag.path index = option_bag.index + connection = option_bag.config_bag.connection else: path = None index = None @@ -601,7 +618,10 @@ class Settings(object): if forbidden_permissives: raise ConfigError(_('cannot add those permissives: {0}').format( ' '.join(forbidden_permissives))) - await self._pp_.setpermissives(path, index, permissives) + await self._pp_.setpermissives(connection, + path, + index, + permissives) if option_bag is not None: await option_bag.config_bag.context.cfgimpl_reset_cache(option_bag) @@ -610,7 +630,7 @@ class Settings(object): async def reset(self, option_bag, - context): + config_bag): if option_bag is None: opt = None path = None @@ -622,12 +642,14 @@ class Settings(object): "").format(opt.impl_get_display_name()) path = option_bag.path index = option_bag.index - await self._p_.delproperties(path, index) - await context.cfgimpl_reset_cache(option_bag) + await self._p_.delproperties(config_bag.connection, + path, + index) + await config_bag.context.cfgimpl_reset_cache(option_bag) async def reset_permissives(self, option_bag, - context): + config_bag): if option_bag is None: opt = None path = None @@ -639,8 +661,10 @@ class Settings(object): "").format(opt.impl_get_display_name()) index = option_bag.index path = option_bag.path - await self._pp_.delpermissive(path, index) - await context.cfgimpl_reset_cache(option_bag) + await self._pp_.delpermissive(config_bag.connection, + path, + index) + await config_bag.context.cfgimpl_reset_cache(option_bag) #____________________________________________________________ # validate properties @@ -664,29 +688,36 @@ class Settings(object): option_properties): raises_properties = context_properties - SPECIAL_PROPERTIES # remove global permissive properties - if raises_properties and ('permissive' in raises_properties): + if raises_properties and 'permissive' in raises_properties: raises_properties -= context_permissives properties = option_properties & raises_properties - # at this point an option should not remain in properties + # at this point it should not remain any property for the option return properties async def validate_properties(self, - option_bag): - """ - validation upon the properties related to `opt` - - :param opt: an option or an option description object - :param force_permissive: behaves as if the permissive property - was present - """ - config_bag = option_bag.config_bag - if not config_bag.properties or config_bag.properties == frozenset(['cache']): # pragma: no cover + option_bag, + need_help=True): + config_properties = option_bag.config_bag.properties + if not config_properties or config_properties == frozenset(['cache']): + # if no global property return properties = await self.calc_raises_properties(option_bag) if properties != frozenset(): + if need_help: + help_properties = dict(await self.getproperties(option_bag, + help_property=True)) + calc_properties = [] + for property_ in self._calc_raises_properties(option_bag.config_bag.properties, + option_bag.config_bag.permissives, + set(help_properties.keys())): + calc_properties.append(help_properties[property_]) + calc_properties = frozenset(calc_properties) + else: + calc_properties = properties raise PropertiesOptionError(option_bag, properties, - self) + self, + help_properties=calc_properties) def validate_mandatory(self, value, @@ -731,8 +762,9 @@ class Settings(object): async def _read(self, remove, append, - context): - props = await self._p_.getproperties(None, + config_bag): + props = await self._p_.getproperties(config_bag.connection, + None, None, self.default_properties) modified = False @@ -743,19 +775,20 @@ class Settings(object): props = props | append modified = True if modified: - await self.set_context_properties(frozenset(props), - context) + await self.set_context_properties(config_bag.connection, + frozenset(props), + config_bag.context) async def read_only(self, - context): + config_bag): "convenience method to freeze, hide and disable" await self._read(self.ro_remove, self.ro_append, - context) + config_bag) async def read_write(self, - context): + config_bag): "convenience method to freeze, hide and disable" await self._read(self.rw_remove, self.rw_append, - context) + config_bag) diff --git a/tiramisu/storage/__init__.py b/tiramisu/storage/__init__.py index b82890b..91b5502 100644 --- a/tiramisu/storage/__init__.py +++ b/tiramisu/storage/__init__.py @@ -1,4 +1,4 @@ -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -18,7 +18,6 @@ settings changes will be lost. The storage is the system Tiramisu uses to communicate with various DB. -You can specified a persistent storage. Storage is basic components used to set Config informations in DB. """ @@ -44,16 +43,26 @@ class Storage: after. """ def __init__(self, - **kwargs: Dict[str, str]) -> None: - self.storage_type = None + engine=None) -> None: + self.storage_type = engine self.mod = None - if kwargs: - self.setting(**kwargs) + self.kwargs = {} - def get(self): + def engine(self, + engine) -> None: + if self.mod is not None: + raise ValueError(_('cannot change setting when storage is already in use')) + self.storage_type = engine + + def setting(self, + **kwargs: Dict[str, str]) -> None: + if self.mod is not None: + raise ValueError(_('cannot change setting when storage is already in use')) + self.kwargs = kwargs + + async def get(self): if self.storage_type is None: self.storage_type = environ.get('TIRAMISU_STORAGE', DEFAULT_STORAGE) - self.setting() if self.mod is None: modulepath = '{0}.storage.{1}'.format(MODULE_PATH, self.storage_type) @@ -65,25 +74,11 @@ class Storage: for token in modulepath.split(".")[1:]: mod = getattr(mod, token) self.mod = mod - return self.mod - - def setting(self, - **kwargs: Dict[str, str]) -> None: - if 'engine' in kwargs: - name = kwargs['engine'] - if self.storage_type is not None and self.storage_type != name: # pragma: no cover - raise ConfigError(_('storage_type is already set, ' - 'cannot rebind it')) - self.storage_type = name - del kwargs['engine'] - if kwargs: # pragma: no cover - mod = self.get() - for key, value in kwargs.items(): + for key, value in self.kwargs.items(): setattr(mod.SETTING, key, value) - - def is_persistent(self): - mod = self.get() - return mod.PERSISTENT + del self.kwargs + await self.mod.init() + return self.mod default_storage = Storage() @@ -94,60 +89,62 @@ def gen_storage_id(session_id, config): if session_id is not None: return session_id - return 'c' + str(id(config)) + str(int(time())) + str(randint(0, 500)) + return 'c' + str(id(config)) + str(int(time())) + str(randint(0, 50000)) async def get_storages(context, session_id, - persistent, - storage): + delete_old_session, + storage, + connection): session_id = gen_storage_id(session_id, context) if storage is None: storage = default_storage - imp = storage.get() - imp_storage = await imp.Storage(session_id, - persistent) + imp = await storage.get() + imp_storage = await imp.Storage(connection, + session_id, + delete_old_session) properties = imp.Properties(imp_storage) permissives = imp.Permissives(imp_storage) values = imp.Values(imp_storage) - return properties, permissives, values, session_id + return storage, properties, permissives, values, session_id -async def get_default_values_storages(): - imp = memory_storage.get() - storage = await imp.Storage('__validator_storage', - persistent=False, - test=True) +async def get_default_values_storages(connection): + imp = await memory_storage.get() + storage = await imp.Storage(connection, + '__validator_storage', + delete_old_session=True) return imp.Values(storage) -async def get_default_settings_storages(): - imp = memory_storage.get() - storage = await imp.Storage('__validator_storage', persistent=False, test=True) +async def get_default_settings_storages(connection): + imp = await memory_storage.get() + storage = await imp.Storage(connection, + '__validator_storage', + delete_old_session=True) properties = imp.Properties(storage) permissives = imp.Permissives(storage) return properties, permissives -def list_sessions(storage=default_storage): - """List all available session (persistent or not persistent) +async def list_sessions(storage=default_storage): + """List all available session """ - return storage.get().list_sessions() + stor = await storage.get() + return await stor.list_sessions() -def delete_session(session_id, storage=default_storage): +async def delete_session(session_id, + storage=default_storage): """Delete a selected session, be careful, you can deleted a session use by an other instance :params session_id: id of session to delete """ - storage_module = storage.get() - session = storage_module.storage.getsession() - storage_module.value.delete_session(session_id) - storage_module.storage.delete_session(session_id) - if session: # pragma: no cover - session.commit() - del(session) + storage_module = await storage.get() + await storage_module.value.delete_session(session_id) + await storage_module.storage.delete_session(session_id) __all__ = ('list_sessions', 'delete_session') diff --git a/tiramisu/storage/cache/dictionary.py b/tiramisu/storage/cache/dictionary.py index dfaa593..d47e7b3 100644 --- a/tiramisu/storage/cache/dictionary.py +++ b/tiramisu/storage/cache/dictionary.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2018-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2018-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/storage/cacheobj.py b/tiramisu/storage/cacheobj.py index 36bdf84..f8f0dcf 100644 --- a/tiramisu/storage/cacheobj.py +++ b/tiramisu/storage/cacheobj.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "cache used by storage" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -30,11 +30,11 @@ class Cache(DictCache): if follower, add index """ if 'cache' in props or 'cache' in self_props: - log.debug('setcache %s with index %s and value %s in %s (%s)', - path, index, val, _display_classname(self), id(self)) + # log.debug('setcache %s with index %s and value %s in %s (%s)', + # path, index, val, _display_classname(self), id(self)) super().setcache(path, index, val, time(), validated) - log.debug('not setcache %s with index %s and value %s and props %s and %s in %s (%s)', - path, index, val, props, self_props, _display_classname(self), id(self)) + # log.debug('not setcache %s with index %s and value %s and props %s and %s in %s (%s)', + # path, index, val, props, self_props, _display_classname(self), id(self)) def getcache(self, path, @@ -63,31 +63,31 @@ class Cache(DictCache): 'expire' in self_props): ntime = int(time()) if timestamp + expiration_time >= ntime: - log.debug('getcache in cache (1) %s %s %s %s %s', path, value, _display_classname(self), - id(self), index) + # log.debug('getcache in cache (1) %s %s %s %s %s', path, value, _display_classname(self), + # id(self), index) return True, value, validated - else: - log.debug('getcache expired value for path %s < %s', - timestamp + expiration_time, ntime) + # else: + # log.debug('getcache expired value for path %s < %s', + # timestamp + expiration_time, ntime) # if expired, remove from cache # self.delcache(path) else: - log.debug('getcache in cache (2) %s %s %s %s %s', path, value, _display_classname(self), - id(self), index) + # log.debug('getcache in cache (2) %s %s %s %s %s', path, value, _display_classname(self), + # id(self), index) return True, value, validated - log.debug('getcache %s with index %s not in %s cache', - path, index, _display_classname(self)) + # log.debug('getcache %s with index %s not in %s cache', + # path, index, _display_classname(self)) return no_cache def delcache(self, path): """remove cache for a specified path """ - log.debug('delcache %s %s %s', path, _display_classname(self), id(self)) + # log.debug('delcache %s %s %s', path, _display_classname(self), id(self)) super().delcache(path) def reset_all_cache(self): "empty the cache" - log.debug('reset_all_cache %s %s', _display_classname(self), id(self)) + # log.debug('reset_all_cache %s %s', _display_classname(self), id(self)) super().reset_all_cache() def get_cached(self): @@ -96,5 +96,5 @@ class Cache(DictCache): example: {'path1': {'index1': ('value1', 'time1')}, 'path2': {'index2': ('value2', 'time2', )}} """ cache = super().get_cached() - log.debug('get_chached %s for %s (%s)', cache, _display_classname(self), id(self)) + # log.debug('get_chached %s for %s (%s)', cache, _display_classname(self), id(self)) return cache diff --git a/tiramisu/storage/dictionary/__init__.py b/tiramisu/storage/dictionary/__init__.py index 3373235..3002a93 100644 --- a/tiramisu/storage/dictionary/__init__.py +++ b/tiramisu/storage/dictionary/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -17,14 +17,12 @@ """Default plugin for storage. All informations are store in a simple dictionary in memory. -You cannot have persistente informations with this kind of storage. - The advantage of this solution is that you can easily create a Config and use it. But if something goes wrong, you will lost your modifications. """ from .value import Values from .setting import Properties, Permissives -from .storage import PERSISTENT, SETTING, Storage, list_sessions +from .storage import PERSISTENT, SETTING, Storage, list_sessions, init, Connection __all__ = ('PERSISTENT', @@ -33,4 +31,6 @@ __all__ = ('PERSISTENT', 'Properties', 'Permissives', 'Storage', + 'init', + 'Connection', 'list_sessions') diff --git a/tiramisu/storage/dictionary/setting.py b/tiramisu/storage/dictionary/setting.py index 067fb47..9527301 100644 --- a/tiramisu/storage/dictionary/setting.py +++ b/tiramisu/storage/dictionary/setting.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "default plugin for setting: set it in a simple dictionary" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -20,75 +20,108 @@ from ...log import log class Properties: - __slots__ = ('_properties', - '_storage') + __slots__ = ('_storage',) def __init__(self, storage): # properties attribute: the name of a property enables this property # key is None for global properties - self._properties = {} self._storage = storage # properties - async def setproperties(self, path, index, properties): + async def setproperties(self, + connection, + path, + index, + properties): log.debug('setproperties %s %s %s', path, index, properties) - self._properties.setdefault(path, {})[index] = properties + self._storage.get_properties().setdefault(path, {})[index] = properties - async def getproperties(self, path, index, default_properties): - if path not in self._properties: + async def getproperties(self, + connection, + path, + index, + default_properties): + properties = self._storage.get_properties() + if path not in properties: ret = frozenset(default_properties) else: - ret = self._properties[path].get(index, frozenset(default_properties)) + ret = properties[path].get(index, frozenset(default_properties)) log.debug('getproperties %s %s %s', path, index, ret) return ret - async def delproperties(self, path, index): + async def delproperties(self, + connection, + path, + index): log.debug('delproperties %s', path) - if path in self._properties and index in self._properties[path]: - del(self._properties[path][index]) + properties = self._storage.get_properties() + if path in properties and index in properties[path]: + del(properties[path][index]) - async def exportation(self): + async def exportation(self, + connection): """return all modified settings in a dictionary example: {'path1': set(['prop1', 'prop2'])} """ - return deepcopy(self._properties) + return deepcopy(self._storage.get_properties()) - async def importation(self, properties): - self._properties = properties + async def importation(self, + connection, + properties): + self._storage.set_properties(properties) + + def getconnection(self): + return self._storage.getconnection() class Permissives: - __slots__ = ('_permissives', - '_storage') + __slots__ = ('_storage',) def __init__(self, storage): # permissive properties - self._permissives = {} self._storage = storage - async def setpermissives(self, path, index, permissives): + async def setpermissives(self, + connection, + path, + index, + permissives): log.debug('setpermissives %s %s', path, permissives) - self._permissives.setdefault(path, {})[index] = permissives + self._storage.get_permissives().setdefault(path, {})[index] = permissives - async def getpermissives(self, path, index): - if not path in self._permissives: + async def getpermissives(self, + connection, + path, + index): + permissives = self._storage.get_permissives() + if not path in permissives: ret = frozenset() else: - ret = self._permissives[path].get(index, frozenset()) + ret = permissives[path].get(index, frozenset()) log.debug('getpermissives %s %s', path, ret) return ret - async def delpermissive(self, path, index): + async def delpermissive(self, + connection, + path, + index): log.debug('delpermissive %s', path) - if path in self._permissives and index in self._permissives[path]: - del(self._permissives[path][index]) + permissives = self._storage.get_permissives() + if path in permissives and index in permissives[path]: + del(permissives[path][index]) - async def exportation(self): + async def exportation(self, + connection): """return all modified permissives in a dictionary example: {'path1': set(['perm1', 'perm2'])} """ - return deepcopy(self._permissives) + return deepcopy(self._storage.get_permissives()) - async def importation(self, permissives): - self._permissives = permissives + async def importation(self, + connection, + permissives): + self._storage.set_permissives(permissives) + + def getconnection(self): + return self._storage.getconnection() diff --git a/tiramisu/storage/dictionary/storage.py b/tiramisu/storage/dictionary/storage.py index 1dc5ef7..7e01d83 100644 --- a/tiramisu/storage/dictionary/storage.py +++ b/tiramisu/storage/dictionary/storage.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -26,36 +26,95 @@ class Setting: SETTING = Setting() -_list_sessions = [] -PERSISTENT = False +_list_sessions = {} +PERSISTENT = True -def list_sessions(): - return _list_sessions +async def init(): + pass + + +class Connection: + async def __aenter__(self): + return self + + async def __aexit__(self, + type, + value, + traceback): + pass + + +async def list_sessions(): + lst = list(_list_sessions.keys()) + if '__validator_storage' in lst: + lst.remove('__validator_storage') + return lst + + +async def delete_session(session_id): + try: + del _list_sessions[session_id] + except KeyError: + pass @asyncinit class Storage: - __slots__ = ('session_id', 'persistent') + __slots__ = ('session_id',) storage = 'dictionary' - # if object could be serializable - serializable = True - async def __init__(self, session_id, persistent, test=False): - if not test and session_id in _list_sessions: - raise ConflictError(_('session "{}" already exists').format(session_id)) - if persistent: - raise ValueError(_('a dictionary cannot be persistent')) + def add_session(self): + # values (('path1',), (index1,), (value1,), ('owner1')) + _list_sessions[self.session_id] = {'values': ([], [], [], []), + 'informations': {}, + 'properties': {}, + 'permissives': {}} + + async def __init__(self, + connection: Connection, + session_id: str, + delete_old_session: bool) -> None: + if not isinstance(session_id, str): + raise ValueError(_('session_id has to be a string')) self.session_id = session_id - self.persistent = persistent - _list_sessions.append(self.session_id) + if self.session_id not in _list_sessions: + self.add_session() - def __del__(self): - try: - _list_sessions.remove(self.session_id) - except AttributeError: - pass + async def delete_session(self): + await delete_session(self.session_id) + async def list_sessions(self): + return await list_sessions() -def getsession(): - pass + def get_session(self): + if self.session_id not in _list_sessions: + self.add_session() + return _list_sessions.get(self.session_id, {}) + + def get_values(self): + return self.get_session()['values'] + + def set_values(self, values): + self.get_session()['values'] = values + + def get_informations(self): + return self.get_session()['informations'] + + def set_informations(self, informations): + self.get_session()['informations'] = informations + + def get_properties(self): + return self.get_session()['properties'] + + def set_properties(self, properties): + self.get_session()['properties'] = properties + + def get_permissives(self): + return self.get_session()['permissives'] + + def set_permissives(self, permissives): + self.get_session()['permissives'] = permissives + + def getconnection(self): + return Connection() diff --git a/tiramisu/storage/dictionary/value.py b/tiramisu/storage/dictionary/value.py index 7ce8fbb..83babb3 100644 --- a/tiramisu/storage/dictionary/value.py +++ b/tiramisu/storage/dictionary/value.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "default plugin for value: set it in a simple dictionary" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -18,6 +18,7 @@ from ...setting import undefined from ...i18n import _ from ...log import log +from .storage import delete_session from copy import deepcopy @@ -30,16 +31,12 @@ class Values: def __init__(self, storage): """init plugin means create values storage """ - #(('path1',), (index1,), (value1,), ('owner1')) - self._values = ([], [], [], []) - self._informations = {} + #self._values = ([], [], [], []) + #self._informations = {} self._storage = storage - async def commit(self): - pass - def _setvalue_info(self, nb, idx, value, index, follower_idx=None): - lst = self._values[nb] + lst = self._storage.get_values()[nb] if index is None or nb == 0: # not follower or path lst[idx] = value @@ -58,26 +55,27 @@ class Values: def _add_new_value(self, index, nb, value): if index is None or nb == 0: # not follower or path - self._values[nb].append(value) + self._storage.get_values()[nb].append(value) else: # follower - self._values[nb].append([value]) + self._storage.get_values()[nb].append([value]) def _add_new_value(self, index, nb, value): if index is None or nb == 0: # not follower or path - self._values[nb].append(value) + self._storage.get_values()[nb].append(value) else: # follower - self._values[nb].append([value]) + self._storage.get_values()[nb].append([value]) # value async def setvalue(self, + connection, path, value, owner, index, - commit): + new=False): """set value for a path a specified value must be associated to an owner """ @@ -85,8 +83,9 @@ class Values: #if isinstance(value, list): # value = value - if path in self._values[0]: - idx = self._values[0].index(path) + values = self._storage.get_values() + if not new and path in values[0]: + idx = values[0].index(path) self._setvalue_info(0, idx, path, index) follower_idx = self._setvalue_info(1, idx, index, index) self._setvalue_info(2, idx, value, index, follower_idx) @@ -97,47 +96,56 @@ class Values: self._add_new_value(index, 2, value) self._add_new_value(index, 3, owner) - async def hasvalue(self, path, index=None): + async def hasvalue(self, + connection, + path, + index=None): """if path has a value return: boolean """ - has_path = path in self._values[0] + values = self._storage.get_values() + has_path = path in values[0] log.debug('hasvalue %s %s %s %s', path, index, has_path, id(self)) if index is None: return has_path elif has_path: - path_idx = self._values[0].index(path) - indexes = self._values[1][path_idx] + path_idx = values[0].index(path) + indexes = values[1][path_idx] return index in indexes return False - async def reduce_index(self, path, index): + async def reduce_index(self, + connection, + path, + index): """ _values == ((path1, path2), ((idx1_1, idx1_2), None), ((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2)) """ log.debug('reduce_index %s %s %s', path, index, id(self)) - path_idx = self._values[0].index(path) + values = self._storage.get_values() + path_idx = values[0].index(path) # get the "index" position - subidx = self._values[1][path_idx].index(index) + subidx = values[1][path_idx].index(index) # reduce to one the index - self._values[1][path_idx][subidx] -= 1 + values[1][path_idx][subidx] -= 1 async def resetvalue_index(self, + connection, path, - index, - commit): + index): log.debug('resetvalue_index %s %s %s', path, index, id(self)) + values = self._storage.get_values() def _resetvalue(nb): - del self._values[nb][path_idx] + del self._storage.get_values()[nb][path_idx] def _resetvalue_index(nb): - del self._values[nb][path_idx][subidx] + del self._storage.get_values()[nb][path_idx][subidx] - path_idx = self._values[0].index(path) - indexes = self._values[1][path_idx] + path_idx = values[0].index(path) + indexes = values[1][path_idx] if index in indexes: subidx = indexes.index(index) - if len(self._values[1][path_idx]) == 1: + if len(values[1][path_idx]) == 1: _resetvalue(0) _resetvalue(1) _resetvalue(2) @@ -148,15 +156,16 @@ class Values: _resetvalue_index(3) async def resetvalue(self, - path, - commit): + connection, + path): """remove value means delete value in storage """ log.debug('resetvalue %s %s', path, id(self)) + values = self._storage.get_values() def _resetvalue(nb): - self._values[nb].pop(idx) - if path in self._values[0]: - idx = self._values[0].index(path) + values[nb].pop(idx) + if path in values[0]: + idx = values[0].index(path) _resetvalue(0) _resetvalue(1) _resetvalue(2) @@ -164,19 +173,22 @@ class Values: # owner async def setowner(self, + connection, path, owner, - index=None): + index): """change owner for a path """ - idx = self._values[0].index(path) + values = self._storage.get_values() + idx = values[0].index(path) if index is None: follower_idx = None else: - follower_idx = self._values[1][idx].index(index) + follower_idx = values[1][idx].index(index) self._setvalue_info(3, idx, owner, index, follower_idx) async def getowner(self, + connection, path, default, index=None, @@ -202,24 +214,25 @@ class Values: """ _values == ((path1, path2), ((idx1_1, idx1_2), None), ((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2)) """ + values = self._storage.get_values() value = undefined - if path in self._values[0]: - path_idx = self._values[0].index(path) - indexes = self._values[1][path_idx] + if path in values[0]: + path_idx = values[0].index(path) + indexes = values[1][path_idx] if indexes is None: if index is not None: # pragma: no cover raise ValueError('index is forbidden for {}'.format(path)) - owner = self._values[3][path_idx] + owner = values[3][path_idx] if with_value: - value = self._values[2][path_idx] + value = values[2][path_idx] else: if index is None: # pragma: no cover raise ValueError('index is mandatory for {}'.format(path)) if index in indexes: subidx = indexes.index(index) - owner = self._values[3][path_idx][subidx] + owner = values[3][path_idx][subidx] if with_value: - value = self._values[2][path_idx][subidx] + value = values[2][path_idx][subidx] else: owner = undefined else: @@ -228,57 +241,79 @@ class Values: value = list(value) return owner, value - async def set_information(self, path, key, value): + async def set_information(self, + connection, + path, + key, + value): """updates the information's attribute (which is a dictionary) :param key: information's key (ex: "help", "doc" :param value: information's value (ex: "the help string") """ - self._informations.setdefault(path, {}) - self._informations[path][key] = value + informations = self._storage.get_informations() + informations.setdefault(path, {}) + informations[path][key] = value - async def get_information(self, path, key, default): + async def get_information(self, + connection, + path, + key, + default): """retrieves one information's item :param key: the item string (ex: "help") """ - value = self._informations.get(path, {}).get(key, default) + value = self._storage.get_informations().get(path, {}).get(key, default) if value is undefined: raise ValueError(_("information's item" " not found: {0}").format(key)) return value - async def del_information(self, path, key, raises): - if path in self._informations and key in self._informations[path]: - del self._informations[path][key] + async def del_information(self, + connection, + path, + key, + raises): + informations = self._storage.get_informations() + if path in informations and key in informations[path]: + del informations[path][key] else: if raises: raise ValueError(_("information's item not found {0}").format(key)) - async def list_information(self, path): - if path in self._informations: - return self._informations[path].keys() + async def list_information(self, + connection, + path): + informations = self._storage.get_informations() + if path in informations: + return informations[path].keys() else: return [] - async def del_informations(self): - self._informations = {} + async def del_informations(self, + connection): + self._storage.set_informations({}) - async def exportation(self): - return deepcopy(self._values) + async def exportation(self, + connection): + return deepcopy(self._storage.get_values()) - async def importation(self, export): - self._values = deepcopy(export) + async def importation(self, + connection, + export): + self._storage.set_values(deepcopy(export)) async def get_max_length(self, + connection, path): - if path in self._values[0]: - idx = self._values[0].index(path) + values = self._storage.get_values() + if path in values[0]: + idx = values[0].index(path) else: return 0 - return max(self._values[1][idx]) + 1 + return max(values[1][idx]) + 1 - -def delete_session(session_id): - raise ValueError(_('cannot delete none persistent session')) + def getconnection(self): + return self._storage.getconnection() diff --git a/tiramisu/storage/postgres/__init__.py b/tiramisu/storage/postgres/__init__.py new file mode 100644 index 0000000..bb75c17 --- /dev/null +++ b/tiramisu/storage/postgres/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2020 Team tiramisu (see AUTHORS for all contributors) +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . +# ____________________________________________________________ +"""Postgres plugin for storage. +""" +from .value import Values +from .setting import Properties, Permissives +from .storage import PERSISTENT, SETTING, Storage, list_sessions, init, Connection + + +__all__ = ('PERSISTENT', + 'SETTING', + 'Values', + 'Properties', + 'Permissives', + 'Storage', + 'init', + 'Connection', + 'list_sessions') diff --git a/tiramisu/storage/postgres/setting.py b/tiramisu/storage/postgres/setting.py new file mode 100644 index 0000000..bb339cf --- /dev/null +++ b/tiramisu/storage/postgres/setting.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +"default plugin for setting: set it in a simple dictionary" +# Copyright (C) 2020 Team tiramisu (see AUTHORS for all contributors) +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . +# ____________________________________________________________ +try: + from cPickle import loads, dumps +except ImportError: + from pickle import loads, dumps +from ...log import log + + +class Properties: + __slots__ = ('_storage',) + + def __init__(self, storage): + self._storage = storage + + # properties + async def setproperties(self, + connection, + path, + index, + properties): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + await self.delproperties(connection, path, index) + sql = "INSERT INTO property(path, idx, properties, session_id) VALUES ($1, $2, $3, $4)" + params = [path, index, dumps(properties), self._storage.database_id] + await connection.execute(sql, *params) + + async def getproperties(self, + connection, + path, + index, + default_properties): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + sql = 'SELECT properties FROM property WHERE path = $1 AND session_id = $2 AND idx = $3' + params = [path, self._storage.database_id, index] + value = await connection.fetchval(sql, *params) + if value is None: + return set(default_properties) + else: + return set(loads(value)) + + async def delproperties(self, + connection, + path, + index): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + sql = 'DELETE FROM property WHERE session_id = $1 AND path = $2 AND idx = $3' + params = [self._storage.database_id, path, index] + await connection.execute(sql, *params) + + async def exportation(self, + connection): + """return all modified settings in a dictionary + example: {'path1': set(['prop1', 'prop2'])} + """ + ret = {} + for path, idx, properties, _ in await connection.fetch("SELECT * FROM property " + "WHERE session_id = $1", + self._storage.database_id): + idx = self._storage.load_index(idx) + path = self._storage.load_path(path) + ret.setdefault(path, {})[idx] = loads(properties) + return ret + + async def importation(self, + connection, + properties): + await connection.execute("DELETE FROM property WHERE session_id = $1", self._storage.database_id) + for path, indexed_properties in properties.items(): + path = self._storage.convert_path(path) + for index, property_ in indexed_properties.items(): + index = self._storage.convert_index(index) + await connection.execute("INSERT INTO property(path, idx, properties, session_id) " + "VALUES ($1,$2,$3,$4)", path, + index, + dumps(property_), + self._storage.database_id) + + def getconnection(self): + return self._storage.getconnection() + + +class Permissives: + __slots__ = ('_storage',) + + def __init__(self, + storage): + self._storage = storage + + # permissive + async def setpermissives(self, + connection, + path, + index, + permissive): + # log.debug('setpermissive %s %s %s %s', path, index, permissive, id(self)) + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + await self.delpermissive(connection, + path, + index) + await connection.execute("INSERT INTO permissive(path, idx, permissives, session_id) " + "VALUES ($1,$2,$3,$4)", path, + index, + dumps(permissive), + self._storage.database_id) + + async def getpermissives(self, + connection, + path, + index): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + sql = 'SELECT permissives FROM permissive WHERE session_id = $1 AND path = $2 AND idx = $3' + params = [self._storage.database_id, path, index] + permissives = await connection.fetchval(sql, + *params) + if permissives is None: + return frozenset() + else: + return loads(permissives) + # log.debug('getpermissive %s %s %s', path, ret, id(self)) + + async def delpermissive(self, + connection, + path, + index): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + sql = 'DELETE FROM permissive WHERE session_id = $1 AND path = $2 AND idx = $3' + params = [self._storage.database_id, path, index] + await connection.execute(sql, *params) + + async def exportation(self, + connection): + """return all modified permissives in a dictionary + example: {'path1': set(['perm1', 'perm2'])} + """ + ret = {} + sql = "SELECT path, idx, permissives FROM permissive WHERE session_id = $1" + for path, index, permissives in await connection.fetch(sql, + self._storage.database_id): + ret.setdefault(self._storage.load_path(path), {})[self._storage.load_index(index)] = loads(permissives) + return ret + + async def importation(self, + connection, + permissives): + await connection.execute("DELETE FROM permissive WHERE session_id = $1", self._storage.database_id) + for path, indexed_permissives in permissives.items(): + for index, permissive in indexed_permissives.items(): + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + await connection.execute("INSERT INTO permissive(path, idx, permissives, session_id) " + "VALUES ($1,$2,$3,$4)", path, + index, + dumps(permissive), + self._storage.database_id) + + def getconnection(self): + return self._storage.getconnection() diff --git a/tiramisu/storage/postgres/storage.py b/tiramisu/storage/postgres/storage.py new file mode 100644 index 0000000..6650dbf --- /dev/null +++ b/tiramisu/storage/postgres/storage.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2020 Team tiramisu (see AUTHORS for all contributors) +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . +# ____________________________________________________________ +from asyncpg import create_pool +from asyncpg.exceptions import UniqueViolationError +import warnings +from os.path import join +from typing import Optional, Dict + +from ...i18n import _ +from ...error import ConflictError +from ...asyncinit import asyncinit + + +class Setting: + """:param dsn: something like postgres://tiramisu:tiramisu@localhost:5432/tiramisu + """ + __slots__ = ('dsn',) + def __init__(self): + self.dsn = 'postgres://tiramisu:tiramisu@localhost:5432/tiramisu' + # FIXME + self.dsn = 'postgres:///tiramisu?host=/var/run/postgresql/&user=tiramisu' + + def __setattr__(self, key, value): + if POOL is not None: # pragma: no cover + raise Exception(_('cannot change setting when connexion is already ' + 'opened')) + super().__setattr__(key, value) + + +POOL = None +PERSISTENT = True +SETTING = Setting() + + +class Connection: + async def __aenter__(self): + self.connection = await POOL.acquire() + self.transaction = self.connection.transaction() + await self.transaction.__aenter__() + return self + + async def __aexit__(self, + type, + value, + traceback): + await self.transaction.__aexit__(type, + value, + traceback) + await self.connection.close() + + async def fetch(self, + *args): + return await self.connection.fetch(*args) + + async def fetchrow(self, + *args): + return await self.connection.fetchrow(*args) + + async def fetchval(self, + *args): + return await self.connection.fetchval(*args) + + async def execute(self, + *args): + await self.connection.execute(*args) + + +async def list_sessions(): + async with Connection() as connection: + return await _list_sessions(connection) + + +async def _list_sessions(connection): + return [row[0] for row in await connection.fetch("SELECT session FROM session")] + + +async def delete_session(session_id): + async with Connection() as connection: + database_id = await connection.fetchval("SELECT session_id FROM session WHERE session = $1", session_id) + if database_id is not None: + await _delete_session(database_id, + connection) + + +async def _delete_session(database_id, + connection): + await connection.execute('DELETE FROM property WHERE session_id = $1', database_id) + await connection.execute('DELETE FROM permissive WHERE session_id = $1', database_id) + await connection.execute('DELETE FROM value WHERE session_id = $1', database_id) + await connection.execute('DELETE FROM information WHERE session_id = $1', database_id) + await connection.execute('DELETE FROM session WHERE session_id = $1', database_id) + + +async def init(): + # self.pool = await connect(dsn=SETTING.dsn) + global POOL + if POOL is None: + POOL = await create_pool(dsn=SETTING.dsn) + #print(' async with POOL.acquire() as connection:') + #print(' async with connection.transaction():') + sql = """ +CREATE TABLE IF NOT EXISTS session(session_id SERIAL, session TEXT UNIQUE, PRIMARY KEY(session_id)); +CREATE TABLE IF NOT EXISTS property(path TEXT, idx INTEGER, properties BYTEA, session_id INTEGER, PRIMARY KEY(path, idx, session_id), FOREIGN KEY(session_id) REFERENCES session(session_id)); +CREATE TABLE IF NOT EXISTS permissive(path TEXT, idx INTEGER, permissives BYTEA, session_id INTEGER, PRIMARY KEY(path, idx, session_id), FOREIGN KEY(session_id) REFERENCES session(session_id)); +CREATE TABLE IF NOT EXISTS value(path TEXT, value BYTEA, owner TEXT, idx INTEGER, session_id INTEGER, PRIMARY KEY (path, idx, session_id), FOREIGN KEY(session_id) REFERENCES session(session_id)); +CREATE TABLE IF NOT EXISTS information(key TEXT, value BYTEA, session_id INTEGER, path TEXT, PRIMARY KEY (key, session_id), FOREIGN KEY(session_id) REFERENCES session(session_id));""" + #print(' await connection.execute("""'+sql+'""")') + await POOL.execute(sql) + + +@asyncinit +class Storage: + __slots__ = ('pool', + 'database_id', + 'session_id', + 'created') + storage = 'postgres' + + async def __init__(self, + connection: Connection, + session_id: str, + delete_old_session: bool) -> None: + if not isinstance(session_id, str): + raise ValueError(_('session_id has to be a string')) + self.database_id = None + self.session_id = session_id + select = await connection.fetchval("SELECT session_id FROM session WHERE session = $1", + self.session_id) + if select is not None: + if delete_old_session: + await self.delete_session() + else: + self.database_id = select + if self.database_id is None: + self.database_id = await connection.fetchval('INSERT INTO session(session) VALUES ($1) RETURNING session_id', + self.session_id) + + def convert_index(self, index): + if index is None: + index = -1 + return index + + def convert_path(self, path): + if path is None: + path = '_none' + return path + + def load_index(self, index): + if index == -1: + index = None + return index + + def load_path(self, path): + if path == '_none': + path = None + return path + + async def delete_session(self): + if self.database_id is not None: + await _delete_session(self.database_id, + POOL) + self.database_id = None + + async def list_sessions(self, + connection): + return await _list_sessions(connection) + + def getconnection(self): + return Connection() diff --git a/tiramisu/storage/postgres/value.py b/tiramisu/storage/postgres/value.py new file mode 100644 index 0000000..810a84a --- /dev/null +++ b/tiramisu/storage/postgres/value.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2020 Team tiramisu (see AUTHORS for all contributors) +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . +# ____________________________________________________________ + +try: + from cPickle import loads, dumps +except ImportError: + from pickle import loads, dumps +from ...setting import undefined, owners +from ...i18n import _ +from ...log import log +from .storage import delete_session + + +class Values: + __slots__ = ('__weakref__', + '_storage') + + def __init__(self, + storage): + """init plugin means create values storage + """ + self._storage = storage + + # value + async def setvalue(self, + connection, + path, + value, + owner, + index, + new=False): + """set value for an option + a specified value must be associated to an owner + """ + # log.debug('setvalue %s %s %s %s %s', path, value, owner, index, commit) + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + sql = 'INSERT INTO value(value, owner, session_id, path, idx) VALUES ($1,$2,$3,$4,$5)' + idx = self._storage.convert_index(index) + path = self._storage.convert_path(path) + params = [dumps(value), str(owner), self._storage.database_id, path, idx] + if new is False: + if index != -1: + await self.resetvalue_index(connection, + path, + index) + else: + await self.resetvalue(connection, + path) + await connection.execute(sql, + *params) + + async def hasvalue(self, + connection, + path, + index=None): + """if opt has a value + return: boolean + """ + # log.debug('hasvalue %s %s', path, index) + if index is not None: + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + request = "SELECT value FROM value WHERE path = $1 AND session_id = $2 AND idx = $3" + params = (path, self._storage.database_id, index) + else: + path = self._storage.convert_path(path) + request = "SELECT value FROM value WHERE path = $1 AND session_id = $2" + params = (path, self._storage.database_id) + ret = await connection.fetchrow(request, *params) + return ret is not None + + + async def reduce_index(self, + connection, + path, + index): + """ + _values == ((path1, path2), ((idx1_1, idx1_2), None), + ((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2)) + """ + # log.debug('reduce_index %s %s %s', path, index, id(self)) + await connection.execute("UPDATE value SET idx = $1 WHERE path = $2 and idx = $3 " + "AND session_id = $4", + index - 1, path, index, self._storage.database_id) + + async def resetvalue_index(self, + connection, + path, + index): + """remove value means delete value in storage + """ + # log.debug('resetvalue_index %s %s', path, index) + await connection.execute("DELETE FROM value WHERE path = $1 AND session_id = $2 AND idx = $3", + path, self._storage.database_id, index) + await self.hasvalue(connection, + path, + index) + + async def resetvalue(self, + connection, + path): + """remove value means delete value in storage + """ + # log.debug('resetvalue %s', path) + await connection.execute("DELETE FROM value WHERE path = $1 AND session_id = $2", + path, self._storage.database_id) + + # owner + async def setowner(self, + connection, + path, + owner, + index): + """change owner for an option + """ + # log.debug('setowner %s %s %s', path, owner, index) + index = self._storage.convert_index(index) + path = self._storage.convert_path(path) + await connection.execute("UPDATE value SET owner = $1 WHERE path = $2 and idx = $3 AND session_id = $4", + str(owner), path, index, self._storage.database_id) + + async def getowner(self, + connection, + path, + default, + index, + with_value=False): + """get owner for an option + return: owner object + """ + # log.debug('getowner %s %s %s %s', path, default, index, with_value) + path = self._storage.convert_path(path) + index = self._storage.convert_index(index) + request = "SELECT owner, value FROM value WHERE session_id = $1 AND path = $2 AND idx = $3" + params = [self._storage.database_id, path, index] + owner = await connection.fetchrow(request, *params) + if owner is None: + if not with_value: + return default + return default, None + # autocreate owners + try: + nowner = getattr(owners, owner[0]) + except AttributeError: # pragma: no cover + owners.addowner(owner[0]) + nowner = getattr(owners, owner[0]) + if not with_value: + return nowner + value = loads(owner[1]) + return nowner, value + + async def set_information(self, + connection, + path, + key, + value): + """updates the information's attribute + (which is a dictionary) + + :param key: information's key (ex: "help", "doc" + :param value: information's value (ex: "the help string") + """ + # log.debug('set_information %s %s', key, value) + path = self._storage.convert_path(path) + await connection.execute("DELETE FROM information WHERE key = $1 AND session_id = $2 AND path = $3", + key, self._storage.database_id, path) + await connection.execute("INSERT INTO information(key, value, session_id, path) VALUES " + "($1, $2, $3, $4)", key, dumps(value), self._storage.database_id, path) + + async def get_information(self, + connection, + path, + key, + default): + """retrieves one information's item + + :param key: the item string (ex: "help") + """ + # log.debug('get_information %s %s', key, default) + path = self._storage.convert_path(path) + value = await connection.fetchval("SELECT value FROM information WHERE key = $1 AND " + "session_id = $2 AND path = $3", + key, self._storage.database_id, path) + if value is None: + if default is undefined: + raise ValueError(_("information's item" + " not found: {0}").format(key)) + return default + else: + return loads(value) + + async def del_information(self, + connection, + path, + key, + raises): + # log.debug('del_information %s %s', key, raises) + path = self._storage.convert_path(path) + information = await connection.fetchval("SELECT value FROM information WHERE key = $1 " + "AND session_id = $2 AND path = $3", + key, self._storage.database_id, path) + if raises and information is None: + raise ValueError(_("information's item not found {0}").format(key)) + await connection.execute("DELETE FROM information WHERE key = $1 AND session_id = $2 AND path = $3", + key, self._storage.database_id, path) + + async def list_information(self, + connection, + path): + path = self._storage.convert_path(path) + return [row[0] for row in await connection.fetch("SELECT key FROM information WHERE session_id = $1 AND path = $2", + self._storage.database_id, path)] + + async def del_informations(self, + connection): + await connection.execute("DELETE FROM information WHERE session_id = $1", + self._storage.database_id) + + async def exportation(self, + connection): + # log.debug('exportation') + ret = [[], [], [], []] + rows = await connection.fetch("SELECT path, value, owner, idx FROM value WHERE " + "session_id = $1", self._storage.database_id) + for row in rows: + path = self._storage.load_path(row[0]) + value = loads(row[1]) + owner = row[2] + index = self._storage.load_index(row[3]) + if index is None: + ret[0].append(path) + ret[1].append(index) + ret[2].append(value) + ret[3].append(owner) + else: + if path in ret[0]: + path_idx = ret[0].index(path) + ret[1][path_idx].append(index) + ret[2][path_idx].append(value) + ret[3][path_idx].append(owner) + else: + ret[0].append(path) + ret[1].append([index]) + ret[2].append([value]) + ret[3].append([owner]) + return ret + + async def importation(self, + connection, + export): + # log.debug('importation') + request = "DELETE FROM value WHERE session_id = $1" + await connection.execute(request, self._storage.database_id) + for idx, path in enumerate(export[0]): + path = self._storage.convert_path(path) + index = self._storage.convert_index(export[1][idx]) + value = export[2][idx] + owner = export[3][idx] + if index == -1: + await connection.execute("INSERT INTO value(path, value, owner, idx, session_id) VALUES " + "($1, $2, $3, $4, $5)", path, dumps(value), + str(owner), index, + self._storage.database_id) + else: + for val in zip(index, value, owner): + await connection.execute("INSERT INTO value(path, value, owner, idx, session_id)" + "VALUES ($1, $2, $3, $4, $5)", path, + dumps(val[1]), + str(val[2]), val[0], + self._storage.database_id) + + async def get_max_length(self, + connection, + path): + # log.debug('get_max_length %s', path) + val_max = await connection.fetchval("SELECT max(idx) FROM value WHERE path = $1 AND session_id = $2", + path, self._storage.database_id) + if val_max is None: + return 0 + return val_max + 1 + + def getconnection(self): + return self._storage.getconnection() diff --git a/tiramisu/storage/sqlite3/__init__.py b/tiramisu/storage/sqlite3/__init__.py index 10cad94..2b08283 100644 --- a/tiramisu/storage/sqlite3/__init__.py +++ b/tiramisu/storage/sqlite3/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -14,15 +14,11 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # ____________________________________________________________ -"""Sqlite3 plugin for storage. This storage is not made to be used in productive -environment. It was developing as proof of concept. - -You should not configure differents Configs with same session_id. - +"""Sqlite3 plugin for storage. """ from .value import Values from .setting import Properties, Permissives -from .storage import PERSISTENT, SETTING, Storage, list_sessions +from .storage import PERSISTENT, SETTING, Storage, list_sessions, init, Connection __all__ = ('PERSISTENT', @@ -31,4 +27,6 @@ __all__ = ('PERSISTENT', 'Properties', 'Permissives', 'Storage', + 'init', + 'Connection', 'list_sessions') diff --git a/tiramisu/storage/sqlite3/setting.py b/tiramisu/storage/sqlite3/setting.py index 5b12b0f..a4cbfc0 100644 --- a/tiramisu/storage/sqlite3/setting.py +++ b/tiramisu/storage/sqlite3/setting.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "default plugin for setting: set it in a simple dictionary" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -26,15 +26,25 @@ class Properties(Sqlite3DB): super(Properties, self).__init__(storage) # properties - async def setproperties(self, path, index, properties): - await self.delproperties(path, index, commit=False) - await self._storage.execute("INSERT INTO property(path, tiram_index, properties, session_id) VALUES " - "(?, ?, ?, ?)", (path, - index, - self._sqlite_encode(properties), - self._session_id)) + async def setproperties(self, + connection, + path, + index, + properties): + await self.delproperties(connection, + path, + index) + await connection.execute("INSERT INTO property(path, tiram_index, properties, session_id) VALUES " + "(?, ?, ?, ?)", (path, + index, + self._sqlite_encode(properties), + self._session_id)) - async def getproperties(self, path, index, default_properties): + async def getproperties(self, + connection, + path, + index, + default_properties): sql = 'SELECT properties FROM property WHERE session_id = ? ' params = [self._session_id] if path is None: @@ -47,13 +57,16 @@ class Properties(Sqlite3DB): else: sql += "AND tiram_index = ? LIMIT 1" params.append(index) - value = await self._storage.select(sql, params) + value = await connection.select(sql, params) if value is None: return set(default_properties) else: return set(self._sqlite_decode(value[0])) - async def delproperties(self, path, index, commit=True): + async def delproperties(self, + connection, + path, + index): sql = 'DELETE FROM property WHERE session_id = ? ' params = [self._session_id] if path is None: @@ -66,47 +79,61 @@ class Properties(Sqlite3DB): else: params.append(index) sql += 'AND tiram_index = ?' - await self._storage.execute(sql, params, commit) + await connection.execute(sql, params) - async def exportation(self): + async def exportation(self, + connection): """return all modified settings in a dictionary example: {'path1': set(['prop1', 'prop2'])} """ ret = {} - for path, tiram_index, properties, _ in await self._storage.select("SELECT * FROM property " - "WHERE session_id = ?", - (self._session_id,), - only_one=False): + for path, tiram_index, properties, _ in await connection.select("SELECT * FROM property " + "WHERE session_id = ?", + (self._session_id,), + only_one=False): ret.setdefault(path, {})[tiram_index] = self._sqlite_decode(properties) return ret - async def importation(self, properties): - await self._storage.execute("DELETE FROM property WHERE session_id = ?", (self._session_id,), commit=False) + async def importation(self, + connection, + properties): + await connection.execute("DELETE FROM property WHERE session_id = ?", (self._session_id,)) for path, indexed_properties in properties.items(): for index, property_ in indexed_properties.items(): - await self._storage.execute("INSERT INTO property(path, tiram_index, properties, session_id) " - "VALUES (?, ?, ?, ?)", (path, - index, - self._sqlite_encode(property_), - self._session_id, - ), False) - self._storage._conn.commit() + await connection.execute("INSERT INTO property(path, tiram_index, properties, session_id) " + "VALUES (?, ?, ?, ?)", (path, + index, + self._sqlite_encode(property_), + self._session_id, + )) + + def getconnection(self): + return self._storage.getconnection() class Permissives(Sqlite3DB): __slots__ = tuple() # permissive - async def setpermissives(self, path, index, permissive): + async def setpermissives(self, + connection, + path, + index, + permissive): log.debug('setpermissive %s %s %s %s', path, index, permissive, id(self)) - await self.delpermissive(path, index, commit=False) - await self._storage.execute("INSERT INTO permissive(path, tiram_index, permissives, session_id) " - "VALUES (?, ?, ?, ?)", (path, - index, - self._sqlite_encode(permissive), - self._session_id)) + await self.delpermissive(connection, + path, + index) + await connection.execute("INSERT INTO permissive(path, tiram_index, permissives, session_id) " + "VALUES (?, ?, ?, ?)", (path, + index, + self._sqlite_encode(permissive), + self._session_id)) - async def getpermissives(self, path, index): + async def getpermissives(self, + connection, + path, + index): sql = 'SELECT permissives FROM permissive WHERE session_id = ? ' params = [self._session_id] if path is None: @@ -119,7 +146,7 @@ class Permissives(Sqlite3DB): else: sql += "AND tiram_index = ? LIMIT 1" params.append(index) - permissives = await self._storage.select(sql, params) + permissives = await connection.select(sql, params) if permissives is None: ret = frozenset() else: @@ -127,7 +154,10 @@ class Permissives(Sqlite3DB): log.debug('getpermissive %s %s %s', path, ret, id(self)) return ret - async def delpermissive(self, path, index, commit=True): + async def delpermissive(self, + connection, + path, + index): sql = 'DELETE FROM permissive WHERE session_id = ? ' params = [self._session_id] if path is None: @@ -140,29 +170,30 @@ class Permissives(Sqlite3DB): else: params.append(index) sql += 'AND tiram_index = ?' - await self._storage.execute(sql, params, commit) + await connection.execute(sql, params) - async def exportation(self): + async def exportation(self, + connection): """return all modified permissives in a dictionary example: {'path1': set(['perm1', 'perm2'])} """ ret = {} sql = "SELECT path, tiram_index, permissives FROM permissive WHERE session_id = ?" - for path, index, permissives in await self._storage.select(sql, - (self._session_id,), - only_one=False): + for path, index, permissives in await connection.select(sql, + (self._session_id,), + only_one=False): ret.setdefault(path, {})[index] = self._sqlite_decode(permissives) return ret - async def importation(self, permissives): - await self._storage.execute("DELETE FROM permissive WHERE session_id = ?", (self._session_id,), - commit=False) + async def importation(self, + connection, + permissives): + await connection.execute("DELETE FROM permissive WHERE session_id = ?", (self._session_id,)) for path, indexed_permissives in permissives.items(): for index, permissive in indexed_permissives.items(): - await self._storage.execute("INSERT INTO permissive(path, tiram_index, permissives, session_id) " - "VALUES (?, ?, ?, ?)", (path, - index, - self._sqlite_encode(permissive), - self._session_id, - ), False) - self._storage._conn.commit() + await connection.execute("INSERT INTO permissive(path, tiram_index, permissives, session_id) " + "VALUES (?, ?, ?, ?)", (path, + index, + self._sqlite_encode(permissive), + self._session_id, + )) diff --git a/tiramisu/storage/sqlite3/sqlite3db.py b/tiramisu/storage/sqlite3/sqlite3db.py index 78ec701..e9073c4 100644 --- a/tiramisu/storage/sqlite3/sqlite3db.py +++ b/tiramisu/storage/sqlite3/sqlite3db.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "sqlite3" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the diff --git a/tiramisu/storage/sqlite3/storage.py b/tiramisu/storage/sqlite3/storage.py index 4b255bd..82fc9df 100644 --- a/tiramisu/storage/sqlite3/storage.py +++ b/tiramisu/storage/sqlite3/storage.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- " with sqlite3 engine" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -29,6 +29,67 @@ global CONN CONN = None +async def init(): + global CONN + if CONN is None: + CONN = sqlite3.connect(_gen_filename()) + CONN.text_factory = str + session_table = 'CREATE TABLE IF NOT EXISTS session(session_id INTEGER, session TEXT UNIQUE, PRIMARY KEY(session_id))' + settings_table = 'CREATE TABLE IF NOT EXISTS property(path TEXT, tiram_index INTEGER, properties TEXT, session_id INTEGER, PRIMARY KEY(path, tiram_index, session_id), ' \ + 'FOREIGN KEY(session_id) REFERENCES session(session_id))' + permissives_table = 'CREATE TABLE IF NOT EXISTS permissive(path TEXT, tiram_index INTEGER, permissives TEXT, session_id INTEGER, ' \ + 'PRIMARY KEY(path, tiram_index, session_id), ' \ + 'FOREIGN KEY(session_id) REFERENCES session(session_id))' + values_table = 'CREATE TABLE IF NOT EXISTS value(path TEXT, value TEXT, owner TEXT, idx INTEGER, session_id INTEGER, ' \ + 'PRIMARY KEY (path, idx, session_id), ' \ + 'FOREIGN KEY(session_id) REFERENCES session(session_id))' + informations_table = 'CREATE TABLE IF NOT EXISTS information(key TEXT, value TEXT, session_id INTEGER, path TEXT, ' \ + 'PRIMARY KEY (key, session_id), ' \ + 'FOREIGN KEY(session_id) REFERENCES session(session_id))' + cursor = CONN.cursor() + cursor.execute(session_table) + cursor.execute(values_table) + cursor.execute(informations_table) + cursor.execute(settings_table) + cursor.execute(permissives_table) + CONN.commit() + + +class Connection: + async def __aenter__(self): + self.connection = CONN.cursor() + return self + + async def __aexit__(self, + type, + value, + traceback): + if type is None: + CONN.commit() + else: + CONN.rollback() + self.connection.close() + + async def execute(self, + sql: str, + params: Optional[Dict]=None) -> None: + if params is None: + params = tuple() + self.connection.execute(sql, params) + + async def select(self, + sql: str, + params: Optional[Dict]=None, + only_one: bool=True) -> 'Row': + if params is None: + params = tuple() + self.connection.execute(sql, params) + if only_one: + return self.connection.fetchone() + else: + return self.connection.fetchall() + + class Setting: """:param extension: database file extension (by default: db) :param dir_database: root database directory (by default: /tmp) @@ -57,134 +118,83 @@ def _gen_filename(): return join(SETTING.dir_database, '{0}.{1}'.format(SETTING.name, SETTING.extension)) -def list_sessions(): +async def list_sessions(): if not CONN: warnings.warn_explicit(Warning(_('Cannot list sessions, please connect to database first')), category=Warning, filename=__file__, lineno=63) return [] - else: - cursor = CONN.cursor() - names = [row[0] for row in cursor.execute("SELECT session FROM session").fetchall()] - return names - - -def delete_session(session_id, - _session_id=None): cursor = CONN.cursor() - if _session_id is None: - _session_id = cursor.execute("SELECT session_id FROM session WHERE session = ?", - (session_id,)).fetchone() - if _session_id is not None: - _session_id = _session_id[0] - if _session_id is not None: - cursor.execute("DELETE FROM property WHERE session_id = ?", (_session_id,)) - cursor.execute("DELETE FROM permissive WHERE session_id = ?", (_session_id,)) - cursor.execute("DELETE FROM value WHERE session_id = ?", (_session_id,)) - cursor.execute("DELETE FROM information WHERE session_id = ?", (_session_id,)) - cursor.execute("DELETE FROM session WHERE session_id = ?", (_session_id,)) - CONN.commit() + return await _list_sessions(cursor) + + +async def _list_sessions(cursor): + names = [row[0] for row in cursor.execute("SELECT session FROM session").fetchall()] + return names + + +async def delete_session(session_id): + cursor = CONN.cursor() + ret = cursor.execute("SELECT session_id FROM session WHERE session = ?", + (session_id,)).fetchone() + if ret is not None: + database_id = ret[0] + await _delete_session(database_id, + cursor) cursor.close() +async def _delete_session(database_id, + cursor): + cursor.execute("DELETE FROM property WHERE session_id = ?", (database_id,)) + cursor.execute("DELETE FROM permissive WHERE session_id = ?", (database_id,)) + cursor.execute("DELETE FROM value WHERE session_id = ?", (database_id,)) + cursor.execute("DELETE FROM information WHERE session_id = ?", (database_id,)) + cursor.execute("DELETE FROM session WHERE session_id = ?", (database_id,)) + CONN.commit() + @asyncinit class Storage: __slots__ = ('_conn', '_cursor', - 'persistent', 'session_id', 'session_name', 'created') storage = 'sqlite3' async def __init__(self, + connection: Connection, session_id: str, - persistent: bool): + delete_old_session: bool) -> None: + if not isinstance(session_id, str): + raise ValueError(_('session_id has to be a string')) self.created = False - self.persistent = persistent - global CONN - init = False - if CONN is None: - init = True - CONN = sqlite3.connect(_gen_filename()) - CONN.text_factory = str - self._conn = CONN - self._cursor = self._conn.cursor() - self.session_name = session_id - if init: - session_table = 'CREATE TABLE IF NOT EXISTS session(session_id INTEGER, ' - session_table += 'session TEXT UNIQUE, persistent BOOL, PRIMARY KEY(session_id))' - settings_table = 'CREATE TABLE IF NOT EXISTS property(path TEXT, ' - settings_table += 'tiram_index INTEGER, properties TEXT, session_id INTEGER, PRIMARY KEY(path, tiram_index, session_id), ' - settings_table += 'FOREIGN KEY(session_id) REFERENCES session(session_id))' - permissives_table = 'CREATE TABLE IF NOT EXISTS permissive(path TEXT,' - permissives_table += 'tiram_index INTEGER, permissives TEXT, session_id INTEGER, PRIMARY KEY(path, tiram_index, session_id), ' - permissives_table += 'FOREIGN KEY(session_id) REFERENCES session(session_id))' - values_table = 'CREATE TABLE IF NOT EXISTS value(path TEXT, ' - values_table += 'value TEXT, owner TEXT, idx INTEGER, session_id INTEGER, '\ - 'PRIMARY KEY (path, idx, session_id), ' - values_table += 'FOREIGN KEY(session_id) REFERENCES session(session_id))' - informations_table = 'CREATE TABLE IF NOT EXISTS information(key TEXT,' - informations_table += 'value TEXT, session_id INTEGER, path TEXT, ' - informations_table += 'PRIMARY KEY (key, session_id), ' - informations_table += 'FOREIGN KEY(session_id) REFERENCES session(session_id))' - self._cursor.execute(session_table) - self._cursor.execute(values_table) - self._cursor.execute(informations_table) - self._cursor.execute(settings_table) - self._cursor.execute(permissives_table) - commit_needed = True - else: - commit_needed = False self.session_id = None - if self.persistent: - select = await self.select("SELECT session_id FROM session WHERE session = ?", (session_id,)) - if select is not None: + self.session_name = session_id + select = await connection.select("SELECT session_id FROM session WHERE session = ?", (session_id,)) + if select is not None: + if delete_old_session: + self.delete_session() + else: self.session_id = select[0] if self.session_id is None: - try: - self._cursor.execute('INSERT INTO session(session, persistent) VALUES (?, ?)', - (session_id, persistent)) - except sqlite3.IntegrityError: # pragma: no cover - raise ConflictError(_('session "{}" already exists').format(session_id)) - commit_needed = True - self.session_id = self._cursor.lastrowid - if commit_needed: - self._conn.commit() + await connection.execute('INSERT INTO session(session) VALUES (?)', + (session_id,)) + self.session_id = connection.connection.lastrowid self.created = True - async def commit(self) -> None: - self._conn.commit() + async def delete_session(self): + if self.session_id is not None: + await _delete_session(self.session_id, + CONN) + self.session_id = None - async def execute(self, - sql: str, - params: Optional[Dict]=None, - commit: bool=True) -> None: - #print(sql, params, commit) - if params is None: - params = tuple() - self._cursor.execute(sql, params) - if commit: - await self.commit() + async def list_sessions(self): + return await _list_sessions(self._cursor) - async def select(self, - sql: str, - params: Optional[Dict]=None, - only_one: bool=True) -> 'Row': - await self.execute(sql, params=params, commit=False) - if only_one: - return self._cursor.fetchone() - else: - return self._cursor.fetchall() - - def __del__(self) -> None: - self._cursor.close() - if self.created and not self.persistent: - if delete_session is not None: - session_id = getattr(self, 'session_id', None) - delete_session(self.session_name, - session_id) + def getconnection(self): + return Connection() def getsession(): diff --git a/tiramisu/storage/sqlite3/value.py b/tiramisu/storage/sqlite3/value.py index 55b16ec..ae98d2c 100644 --- a/tiramisu/storage/sqlite3/value.py +++ b/tiramisu/storage/sqlite3/value.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "default plugin for value: set it in a simple dictionary" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -32,50 +32,52 @@ class Values(Sqlite3DB): super(Values, self).__init__(storage) # sqlite - async def _sqlite_select(self, path, index): + async def _sqlite_select(self, + connection, + path, + index): request = "SELECT value FROM value WHERE path = ? AND session_id = ? " params = (path, self._session_id) if index is not None: request += "and idx = ? " params = (path, self._session_id, index) request += "LIMIT 1" - return await self._storage.select(request, params) - - async def commit(self): - await self._storage.commit() + return await connection.select(request, params) # value async def setvalue(self, + connection, path, value, owner, index, - commit): + new=False): """set value for an option a specified value must be associated to an owner """ - log.debug('setvalue %s %s %s %s %s', path, value, owner, index, commit) + log.debug('setvalue %s %s %s %s', path, value, owner, index) path = self._sqlite_encode_path(path) if index is not None: - await self.resetvalue_index(path, - index, - commit=False) - await self._storage.execute("INSERT INTO value(path, value, owner, idx, session_id) VALUES " - "(?, ?, ?, ?, ?)", (path, self._sqlite_encode(value), - str(owner), - index, - self._session_id), - commit=commit) - else: - await self.resetvalue(path, - commit=False) - await self._storage.execute("INSERT INTO value(path, value, owner, session_id) VALUES " - "(?, ?, ?, ?)", (path, self._sqlite_encode(value), + if not new: + await self.resetvalue_index(connection, + path, + index) + await connection.execute("INSERT INTO value(path, value, owner, idx, session_id) VALUES " + "(?, ?, ?, ?, ?)", (path, self._sqlite_encode(value), str(owner), - self._session_id), - commit=commit) + index, + self._session_id)) + else: + if not new: + await self.resetvalue(connection, + path) + await connection.execute("INSERT INTO value(path, value, owner, session_id) VALUES " + "(?, ?, ?, ?)", (path, self._sqlite_encode(value), + str(owner), + self._session_id)) async def hasvalue(self, + connection, path, index=None): """if opt has a value @@ -83,44 +85,48 @@ class Values(Sqlite3DB): """ log.debug('hasvalue %s %s', path, index) path = self._sqlite_encode_path(path) - return await self._sqlite_select(path, index) is not None + return await self._sqlite_select(connection, + path, + index) is not None - async def reduce_index(self, path, index): + async def reduce_index(self, + connection, + path, + index): """ _values == ((path1, path2), ((idx1_1, idx1_2), None), ((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2)) """ log.debug('reduce_index %s %s %s', path, index, id(self)) - await self._storage.execute("UPDATE value SET idx = ? WHERE path = ? and idx = ? " - "AND session_id = ?", - (index - 1, path, index, self._session_id)) + await connection.execute("UPDATE value SET idx = ? WHERE path = ? and idx = ? " + "AND session_id = ?", + (index - 1, path, index, self._session_id)) async def resetvalue_index(self, + connection, path, - index, - commit=True): + index): """remove value means delete value in storage """ - log.debug('resetvalue_index %s %s %s', path, index, commit) + log.debug('resetvalue_index %s %s', path, index) path = self._sqlite_encode_path(path) - await self._storage.execute("DELETE FROM value WHERE path = ? AND session_id = ? AND idx = ?", - (path, self._session_id, index), - commit=commit) + await connection.execute("DELETE FROM value WHERE path = ? AND session_id = ? AND idx = ?", + (path, self._session_id, index)) async def resetvalue(self, - path, - commit): + connection, + path): """remove value means delete value in storage """ - log.debug('resetvalue %s %s', path, commit) + log.debug('resetvalue %s', path) path = self._sqlite_encode_path(path) - await self._storage.execute("DELETE FROM value WHERE path = ? AND session_id = ?", - (path, self._session_id), - commit=commit) + await connection.execute("DELETE FROM value WHERE path = ? AND session_id = ?", + (path, self._session_id)) # owner async def setowner(self, + connection, path, owner, index=None): @@ -129,17 +135,18 @@ class Values(Sqlite3DB): log.debug('setowner %s %s %s', path, owner, index) path = self._sqlite_encode_path(path) if index is None: - await self._storage.execute("UPDATE value SET owner = ? WHERE path = ? AND session_id = ?", - (str(owner), path, self._session_id)) + await connection.execute("UPDATE value SET owner = ? WHERE path = ? AND session_id = ?", + (str(owner), path, self._session_id)) else: - await self._storage.execute("UPDATE value SET owner = ? WHERE path = ? and idx = ? AND session_id = ?", - (str(owner), path, index, self._session_id)) + await connection.execute("UPDATE value SET owner = ? WHERE path = ? and idx = ? AND session_id = ?", + (str(owner), path, index, self._session_id)) async def getowner(self, - path, - default, - index=None, - with_value=False): + connection, + path, + default, + index=None, + with_value=False): """get owner for an option return: owner object """ @@ -152,7 +159,7 @@ class Values(Sqlite3DB): else: params = (path, self._session_id) request += ' LIMIT 1' - owner = await self._storage.select(request, params) + owner = await connection.select(request, params) if owner is None: if not with_value: return default @@ -171,7 +178,11 @@ class Values(Sqlite3DB): value = self._sqlite_decode(owner[1]) return nowner, value - async def set_information(self, path, key, value): + async def set_information(self, + connection, + path, + key, + value): """updates the information's attribute (which is a dictionary) @@ -180,22 +191,25 @@ class Values(Sqlite3DB): """ log.debug('set_information %s %s', key, value) path = self._sqlite_encode_path(path) - await self._storage.execute("DELETE FROM information WHERE key = ? AND session_id = ? AND path = ?", - (key, self._session_id, path), - False) - await self._storage.execute("INSERT INTO information(key, value, session_id, path) VALUES " - "(?, ?, ?, ?)", (key, self._sqlite_encode(value), self._session_id, path)) + await connection.execute("DELETE FROM information WHERE key = ? AND session_id = ? AND path = ?", + (key, self._session_id, path)) + await connection.execute("INSERT INTO information(key, value, session_id, path) VALUES " + "(?, ?, ?, ?)", (key, self._sqlite_encode(value), self._session_id, path)) - async def get_information(self, path, key, default): + async def get_information(self, + connection, + path, + key, + default): """retrieves one information's item :param key: the item string (ex: "help") """ log.debug('get_information %s %s', key, default) path = self._sqlite_encode_path(path) - value = await self._storage.select("SELECT value FROM information WHERE key = ? AND " - "session_id = ? AND path = ?", - (key, self._session_id, path)) + value = await connection.select("SELECT value FROM information WHERE key = ? AND " + "session_id = ? AND path = ?", + (key, self._session_id, path)) if value is None: if default is undefined: raise ValueError(_("information's item" @@ -204,35 +218,43 @@ class Values(Sqlite3DB): else: return self._sqlite_decode(value[0]) - async def del_information(self, path, key, raises): + async def del_information(self, + connection, + path, + key, + raises): log.debug('del_information %s %s', key, raises) path = self._sqlite_encode_path(path) - information = await self._storage.select("SELECT value FROM information WHERE key = ? " - "AND session_id = ? AND path = ?", - (key, self._session_id, path)) + information = await connection.select("SELECT value FROM information WHERE key = ? " + "AND session_id = ? AND path = ?", + (key, self._session_id, path)) if raises and information is None: raise ValueError(_("information's item not found {0}").format(key)) - await self._storage.execute("DELETE FROM information WHERE key = ? AND session_id = ? AND path = ?", - (key, self._session_id, path)) + await connection.execute("DELETE FROM information WHERE key = ? AND session_id = ? AND path = ?", + (key, self._session_id, path)) - async def list_information(self, path): + async def list_information(self, + connection, + path): path = self._sqlite_encode_path(path) - rows = await self._storage.select("SELECT key FROM information WHERE session_id = ? AND path = ?", - (self._session_id, path), - only_one=False) + rows = await connection.select("SELECT key FROM information WHERE session_id = ? AND path = ?", + (self._session_id, path), + only_one=False) ret = [] for row in rows: ret.append(self._sqlite_decode_path(row[0])) return ret - async def del_informations(self): - await self._storage.execute("DELETE FROM information WHERE session_id = ?", - (self._session_id,)) + async def del_informations(self, + connection): + await connection.execute("DELETE FROM information WHERE session_id = ?", + (self._session_id,)) - async def exportation(self): + async def exportation(self, + connection): log.debug('exportation') - rows = await self._storage.select("SELECT path, value, owner, idx FROM value WHERE " - "session_id = ?;", (self._session_id,), only_one=False) + rows = await connection.select("SELECT path, value, owner, idx FROM value WHERE " + "session_id = ?;", (self._session_id,), only_one=False) ret = [[], [], [], []] for row in rows: path = self._sqlite_decode_path(row[0]) @@ -258,36 +280,36 @@ class Values(Sqlite3DB): return ret - async def importation(self, export): + async def importation(self, + connection, + export): log.debug('importation') request = "DELETE FROM value WHERE session_id = ?" - await self._storage.execute(request, (self._session_id,), - commit=False) + await connection.execute(request, (self._session_id,)) for idx, path in enumerate(export[0]): path = self._sqlite_encode_path(path) index = export[1][idx] value = export[2][idx] owner = export[3][idx] if index is None: - await self._storage.execute("INSERT INTO value(path, value, owner, idx, session_id) VALUES " - "(?, ?, ?, ?, ?)", (path, self._sqlite_encode(value), - str(owner), index, - self._session_id), commit=False) + await connection.execute("INSERT INTO value(path, value, owner, idx, session_id) VALUES " + "(?, ?, ?, ?, ?)", (path, self._sqlite_encode(value), + str(owner), index, + self._session_id)) else: for val in zip(index, value, owner): - await self._storage.execute("INSERT INTO value(path, value, owner, idx, session_id)" - "VALUES (?, ?, ?, ?, ?)", (path, - self._sqlite_encode(val[1]), - str(val[2]), val[0], - self._session_id), - commit=False) - self._storage._conn.commit() + await connection.execute("INSERT INTO value(path, value, owner, idx, session_id)" + "VALUES (?, ?, ?, ?, ?)", (path, + self._sqlite_encode(val[1]), + str(val[2]), val[0], + self._session_id)) async def get_max_length(self, + connection, path): log.debug('get_max_length %s', path) - val_max = await self._storage.select("SELECT max(idx) FROM value WHERE path = ? AND session_id = ?", - (path, self._session_id), False) + val_max = await connection.select("SELECT max(idx) FROM value WHERE path = ? AND session_id = ?", + (path, self._session_id), False) if val_max[0][0] is None: return 0 return val_max[0][0] + 1 diff --git a/tiramisu/todict.py b/tiramisu/todict.py index c11d80b..6b608ff 100644 --- a/tiramisu/todict.py +++ b/tiramisu/todict.py @@ -606,7 +606,7 @@ class TiramisuDict: old_properties = childapi._option_bag.config_bag.properties config = childapi._option_bag.config_bag.context settings = config.cfgimpl_get_settings() - childapi._option_bag.config_bag.properties = await settings.get_context_properties(config._impl_properties_cache) + childapi._option_bag.config_bag.properties = await self.config.property.get(default=True) # settings.get_context_properties(config._impl_properties_cache) childapi._option_bag.config_bag.properties -= {'permissive'} properties = await childapi.property.get(only_raises=True, uncalculated=True) diff --git a/tiramisu/value.py b/tiramisu/value.py index 7b8a382..9de473b 100644 --- a/tiramisu/value.py +++ b/tiramisu/value.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- "takes care of the option's values and multi values" -# Copyright (C) 2013-2019 Team tiramisu (see AUTHORS for all contributors) +# Copyright (C) 2013-2020 Team tiramisu (see AUTHORS for all contributors) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the @@ -34,7 +34,8 @@ class Values: '__weakref__') async def __init__(self, - storage): + storage, + connection): """ Initializes the values's dict. @@ -44,13 +45,17 @@ class Values: # store the storage self._p_ = storage # set default owner - owner = await self._p_.getowner(None, None) + owner = await self._p_.getowner(connection, + None, + None, + None) if owner is None: - await self._p_.setvalue(None, + await self._p_.setvalue(connection, + None, None, owners.user, None, - True) + new=True) #______________________________________________________________________ # get value @@ -105,7 +110,10 @@ class Values: if 'force_metaconfig_on_freeze' in option_bag.properties: settings = option_bag.config_bag.context.cfgimpl_get_settings() if 'force_metaconfig_on_freeze' in option_bag.option.impl_getproperties() and \ - not await settings._p_.getproperties(option_bag.path, None, frozenset()): + not await settings._p_.getproperties(option_bag.config_bag.connection, + option_bag.path, + None, + frozenset()): # if force_metaconfig_on_freeze is only in option (not in config) return option_bag.config_bag.context.impl_type == 'config' else: @@ -143,7 +151,8 @@ class Values: _index = None else: _index = index - owner, value = await self._p_.getowner(option_bag.path, + owner, value = await self._p_.getowner(option_bag.config_bag.connection, + option_bag.path, owners.default, index=_index, with_value=True) @@ -286,10 +295,9 @@ class Values: # set value async def setvalue(self, value, - option_bag, - _commit): + option_bag): context = option_bag.config_bag.context - owner = await self.get_context_owner() + owner = await self.get_context_owner(option_bag.config_bag.connection) if 'validator' in option_bag.config_bag.properties: await self.setvalue_validation(value, option_bag) @@ -299,8 +307,7 @@ class Values: value = value.copy() await self._setvalue(option_bag, value, - owner, - commit=False) + owner) setting_properties = option_bag.config_bag.properties validator = 'validator' in setting_properties and 'demoting_error_warning' not in setting_properties if validator: @@ -315,10 +322,7 @@ class Values: await option_bag.option.impl_get_leadership().follower_force_store_value(self, value, option_bag, - owners.forced, - _commit=_commit) - if _commit: - await self._p_.commit() + owners.forced) async def setvalue_validation(self, value, @@ -343,14 +347,13 @@ class Values: async def _setvalue(self, option_bag, value, - owner, - commit=True): + owner): await option_bag.config_bag.context.cfgimpl_reset_cache(option_bag) - await self._p_.setvalue(option_bag.path, + await self._p_.setvalue(option_bag.config_bag.connection, + option_bag.path, value, owner, - option_bag.index, - commit) + option_bag.index) async def _get_modified_parent(self, option_bag: OptionBag) -> Optional[OptionBag]: @@ -420,13 +423,15 @@ class Values: 'force_default_on_freeze' in option_bag.properties: return owners.default if only_default: - if await self._p_.hasvalue(option_bag.path, + if await self._p_.hasvalue(option_bag.config_bag.connection, + option_bag.path, option_bag.index): owner = 'not_default' else: owner = owners.default else: - owner = await self._p_.getowner(option_bag.path, + owner = await self._p_.getowner(option_bag.config_bag.connection, + option_bag.path, owners.default, index=option_bag.index) if validate_meta is not False and (owner is owners.default or \ @@ -455,26 +460,27 @@ class Values: if owner in forbidden_owners: raise ValueError(_('set owner "{0}" is forbidden').format(str(owner))) - if not await self._p_.hasvalue(option_bag.path): + if not await self._p_.hasvalue(option_bag.config_bag.connection, + option_bag.path): raise ConfigError(_('no value for {0} cannot change owner to {1}' '').format(option_bag.path, owner)) option_bag.config_bag.context.cfgimpl_get_settings().validate_frozen(option_bag) - await self._p_.setowner(option_bag.path, - owner, - index=option_bag.index) + await self._p_.setowner(option_bag.config_bag.connection, + option_bag.path, + owner, + index=option_bag.index) #______________________________________________________________________ # reset async def reset(self, - option_bag, - _commit=True): - + option_bag): context = option_bag.config_bag.context - hasvalue = await self._p_.hasvalue(option_bag.path) + hasvalue = await self._p_.hasvalue(option_bag.config_bag.connection, + option_bag.path) setting_properties = option_bag.config_bag.properties if hasvalue and 'validator' in option_bag.config_bag.properties: - fake_context = await context._gen_fake_values() + fake_context = await context._gen_fake_values(option_bag.config_bag.connection) config_bag = option_bag.config_bag.copy() config_bag.remove_validation() config_bag.context = fake_context @@ -489,21 +495,19 @@ class Values: opt = option_bag.option if opt.impl_is_leader(): await opt.impl_get_leadership().reset(self, - option_bag, - _commit=_commit) + option_bag) if hasvalue: if 'force_store_value' in option_bag.config_bag.properties and 'force_store_value' in option_bag.properties: value = await self.getdefaultvalue(option_bag) await self._setvalue(option_bag, value, - owners.forced, - commit=_commit) + owners.forced) else: # for leader only value = None - await self._p_.resetvalue(option_bag.path, - _commit) + await self._p_.resetvalue(option_bag.config_bag.connection, + option_bag.path) await context.cfgimpl_reset_cache(option_bag) if 'force_store_value' in setting_properties and option_bag.option.impl_is_leader(): if value is None: @@ -511,17 +515,17 @@ class Values: await option_bag.option.impl_get_leadership().follower_force_store_value(self, value, option_bag, - owners.forced, - _commit=_commit) + owners.forced) async def reset_follower(self, - option_bag, - _commit=True): - if await self._p_.hasvalue(option_bag.path, index=option_bag.index): + option_bag): + if await self._p_.hasvalue(option_bag.config_bag.connection, + option_bag.path, + index=option_bag.index): context = option_bag.config_bag.context setting_properties = option_bag.config_bag.properties if 'validator' in setting_properties: - fake_context = await context._gen_fake_values() + fake_context = await context._gen_fake_values(option_bag.config_bag.connection) fake_value = fake_context.cfgimpl_get_values() config_bag = option_bag.config_bag.copy() config_bag.remove_validation() @@ -537,12 +541,11 @@ class Values: await self._setvalue(option_bag, value, - owners.forced, - commit=_commit) + owners.forced) else: - await self._p_.resetvalue_index(option_bag.path, - option_bag.index, - _commit) + await self._p_.resetvalue_index(option_bag.config_bag.connection, + option_bag.path, + option_bag.index) await context.cfgimpl_reset_cache(option_bag) async def reset_leadership(self, @@ -561,13 +564,13 @@ class Values: index, option_bag) await self.setvalue(current_value, - option_bag, - _commit=True) + option_bag) #______________________________________________________________________ # information async def set_information(self, + connection, key, value, path=None): @@ -576,11 +579,13 @@ class Values: :param key: information's key (ex: "help", "doc" :param value: information's value (ex: "the help string") """ - await self._p_.set_information(path, + await self._p_.set_information(connection, + path, key, value) async def get_information(self, + connection, key, default=undefined, path=None): @@ -588,21 +593,26 @@ class Values: :param key: the item string (ex: "help") """ - return await self._p_.get_information(path, + return await self._p_.get_information(connection, + path, key, default) async def del_information(self, + connection, key, raises=True, path=None): - await self._p_.del_information(path, + await self._p_.del_information(connection, + path, key, raises) async def list_information(self, + connection, path=None): - return await self._p_.list_information(path) + return await self._p_.list_information(connection, + path) #______________________________________________________________________ # mandatory warnings @@ -675,18 +685,20 @@ class Values: od_setting_properties = config_bag.properties - {'mandatory', 'empty'} setting_properties = set(config_bag.properties) - {'warnings'} setting_properties.update(['mandatory', 'empty']) - config_bag = ConfigBag(context=config_bag.context, - properties=frozenset(setting_properties), - permissives=config_bag.permissives) - config_bag.set_permissive() - od_config_bag = ConfigBag(context=config_bag.context, + nconfig_bag = ConfigBag(context=config_bag.context, + properties=frozenset(setting_properties), + permissives=config_bag.permissives) + nconfig_bag.connection = config_bag.connection + nconfig_bag.set_permissive() + od_config_bag = ConfigBag(context=nconfig_bag.context, properties=frozenset(od_setting_properties), - permissives=config_bag.permissives) + permissives=nconfig_bag.permissives) + od_config_bag.connection = config_bag.connection od_config_bag.set_permissive() descr = context.cfgimpl_get_description() async for option in self._mandatory_warnings(context, - config_bag, + nconfig_bag, descr, [], context, @@ -696,15 +708,20 @@ class Values: #____________________________________________________________ # default owner methods async def set_context_owner(self, + connection, owner): ":param owner: sets the default value for owner at the Config level" if owner in forbidden_owners: raise ValueError(_('set owner "{0}" is forbidden').format(str(owner))) - await self._p_.setowner(None, + await self._p_.setowner(connection, + None, owner, index=None) - async def get_context_owner(self): - return await self._p_.getowner(None, + async def get_context_owner(self, + connection): + return await self._p_.getowner(connection, + None, + None, None)