Compare commits

...

165 Commits

Author SHA1 Message Date
ce0a46232d Merge remote-tracking branch 'official/master' into develop 2021-05-18 18:54:36 +02:00
64017d5cd4 import/export informations 2021-05-18 18:53:14 +02:00
b0462a1e80 . is no more unvalable 2021-05-18 18:52:42 +02:00
8b4af12217 Merge remote-tracking branch 'official/master' into develop 2021-05-16 06:52:38 +02:00
a5b6352188 calc_value: join with multi 2021-05-16 06:51:33 +02:00
75a073455e Merge remote-tracking branch 'official/master' into develop 2021-04-12 15:05:32 +02:00
87093da974 add test about deepcopy with multi parents 2021-04-03 20:38:08 +02:00
f7721a9775 manage force_store_value with dynoption 2021-04-03 20:24:27 +02:00
33f9cbdc64 allow caching with the demoting_error_warning property 2021-03-29 10:35:56 +02:00
6084487d08 add test to dyn optiondescription 2021-03-29 10:35:56 +02:00
9576809543 dict with leader_to_list parameter 2021-03-29 10:35:56 +02:00
af2d3eb3ce calculation with submulti 2021-03-29 10:35:56 +02:00
b76db42204 better error when value not in a choice 2021-03-29 10:35:56 +02:00
5858bcc00b Calculation to non-leader option with leader parameter is now possible 2021-03-29 10:35:56 +02:00
200562d23c manage callback with unrestraint 2021-03-29 10:35:56 +02:00
2f173af70f Add ParamSelfInformation 2021-03-29 10:35:56 +02:00
9a4faf391e 2020/2021 2021-03-29 10:35:56 +02:00
e2d5a1c8aa filename must be a full path 2021-03-29 10:35:56 +02:00
0bb066a8b8 exected could be a list 2021-03-29 10:35:56 +02:00
d3d4de7ae3 wrong leadership name in dict() 2021-03-29 10:35:56 +02:00
f0be02b80f better error message 2021-03-29 10:35:55 +02:00
b9107867c9 do not remove notempty and notunique properties 2021-03-29 10:35:55 +02:00
3b1dccd844 allow caching with the demoting_error_warning property 2021-03-21 14:51:12 +01:00
12174045a2 add test to dyn optiondescription 2021-03-18 09:00:28 +01:00
8972e796db dict with leader_to_list parameter 2021-03-18 09:00:04 +01:00
29282d8ea3 calculation with submulti 2021-03-18 08:57:22 +01:00
668ed3ad37 better error when value not in a choice 2021-03-18 08:54:59 +01:00
da946baba6 Calculation to non-leader option with leader parameter is now possible 2021-03-18 08:52:22 +01:00
0167f4e2d0 manage callback with unrestraint 2021-03-08 06:39:40 +01:00
acc86bc49f Add ParamSelfInformation 2021-03-06 19:23:35 +01:00
7ebad5724e 2020/2021 2021-02-24 20:30:04 +01:00
385160cabd filename must be a full path 2021-02-17 09:50:36 +01:00
99a422dad7 exected could be a list 2021-02-06 15:18:28 +01:00
bfed49a11f wrong leadership name in dict() 2021-01-11 22:40:25 +01:00
c9e166f1d4 better error message 2020-11-21 19:26:50 +01:00
da87f40f12 do not remove notempty and notunique properties 2020-11-03 22:34:57 +01:00
3e0e7244ef Merge remote-tracking branch 'official/master' into develop 2020-10-14 22:31:54 +02:00
e1fef11465 refactor 2020-10-05 21:16:41 +02:00
a269cbcc93 copy/deepcopy should duplicate informations 2020-10-05 20:27:17 +02:00
cd50225bad Merge remote-tracking branch 'official/master' into develop 2020-10-03 16:18:21 +02:00
6910371779 Add ParamInformation and callback can be a coroutine 2020-10-03 14:29:15 +02:00
afeedc1db6 config_bag and name not already exists 2020-08-15 00:23:48 +02:00
ba23a144ce Merge remote-tracking branch 'official/master' into develop 2020-08-12 11:59:50 +02:00
50d42624cc better support of PACKAGE_DST environment variable 2020-08-12 11:55:55 +02:00
659243ba8f better support for warnings_only 2020-08-04 16:49:21 +02:00
dc8010f0af calc_value with join parameter now work if an option is empty 2020-08-04 16:43:40 +02:00
96c76286db get dependencies in API 2020-08-04 16:35:40 +02:00
5c1d4afd56 remove unconsistent test 2020-08-04 16:35:10 +02:00
c4572ec409 remove codeset to i18n 2020-08-04 16:34:43 +02:00
2f125cfc8c better error for IP like 192.168.001.1 => 192.168.1.1 2020-08-04 16:33:52 +02:00
4b3ac5f350 New release candidate 3.0 rc16 2020-07-29 16:25:01 +02:00
2d7729612b can load old session 2020-04-21 19:19:04 +02:00
86a48ce9f1 support callback with submulti 2020-04-21 17:13:25 +02:00
f437bb78f3 add a test with default_multi for a submulti follower 2020-04-21 09:16:29 +02:00
f7bd6e3a47 add support in calculation when option is in a dynoptiondescription 2020-04-11 13:13:35 +02:00
d71018a88e release 3.0rc16 2020-04-01 11:49:18 +02:00
2d2e8a63fb add new argument in config.new() 2020-03-16 15:38:41 +01:00
6929d2740d do not raise error if setting is not changed 2020-03-14 22:31:42 +01:00
f1651848d2 can create a config with a mix_config 2020-03-04 15:39:47 +01:00
ad6ed0a648 storage in groupconfig 2020-02-18 22:10:33 +01:00
6b33bddbac validate value before validate unique value 2020-02-18 22:09:53 +01:00
91c44b38bc ip_in_network without all information 2020-02-18 22:08:52 +01:00
3bef45c9db New Postgres storage 2020-01-30 16:10:54 +01:00
746fa0134f add tiramisu/asyncinit.py file 2020-01-17 14:15:57 +01:00
1861dc59d4 add leader_to_list to dict message 2019-12-28 12:30:32 +01:00
52ddd76b1a corrections in dict and todict 2019-12-25 20:44:56 +01:00
503d4b2cca async version of tiramisu 2019-12-24 15:25:12 +01:00
76e7fd93b2 can convert suffix to build path for dynoptiondescription 2019-12-21 18:29:21 +01:00
0cb69f7a85 empty follower without empty property is valid 2019-12-19 17:18:09 +01:00
fb93c0cf6f updates tests 2019-12-08 09:09:48 +01:00
4e04082cec error should be returned in todict 2019-12-08 08:15:47 +01:00
d958b9dfad do not init storage before first used 2019-12-08 08:15:14 +01:00
d9c0b18404 'new' config allow storage 2019-12-08 08:14:36 +01:00
9cc4518087 copy value before store it 2019-12-02 10:42:17 +01:00
cdcb155acc support of todict 2019-12-02 10:41:43 +01:00
27838e67a3 support of sqlite3 2019-12-02 10:41:16 +01:00
8345a4651d can get uncalculated property 2019-12-02 10:40:17 +01:00
b6c11c08db add MacOption, remove UnicodeOption 2019-12-02 10:39:10 +01:00
358a49c0e2 can get uncalculated property + can add storage when init mixconfig 2019-12-02 10:37:21 +01:00
212fd5f16d easy way to add a group 2019-11-29 12:07:43 +01:00
323d1b83d6 hack to make a dict without all none implemented feature 2019-11-29 12:07:18 +01:00
709c0bf228 force_store_value for follower 2019-11-20 08:29:45 +01:00
1bcad4d7ed corrections in has_index 2019-11-20 08:28:26 +01:00
13c0c0e256 better error message 2019-11-20 08:27:33 +01:00
ce297ed804 better unique support 2019-11-20 08:26:41 +01:00
973b81d339 add GroupnameOption 2019-11-20 08:25:16 +01:00
9d5bae9305 better follower properties 2019-11-20 08:24:13 +01:00
8fa91abefb calc_value: inverse_condition => reverse_condition 2019-11-20 08:22:12 +01:00
d3e99cc9a5 notunique and notempty support 2019-11-19 18:52:20 +01:00
6b77b0c5ad DomainnameOption add network support 2019-11-19 18:48:13 +01:00
c5d8e0055b force_store_value for follower 2019-11-19 18:46:05 +01:00
7325f6e12f add index to properties/permissives 2019-11-19 18:39:44 +01:00
15669372db add GroupnameOption 2019-11-19 18:31:48 +01:00
74e604478e _validation, _second_level_validation => validation, second_level_validation 2019-11-19 08:26:42 +01:00
5c3a133928 consistency is now simple validation 2019-10-27 16:53:25 +01:00
e62268c46a Merge branch 'master' into develop 2019-10-20 08:26:06 +02:00
c75425c03a Merge branch 'master' into develop 2019-10-20 08:24:48 +02:00
a7e4399ae5 get information with default attribute when information is set to an option 2019-10-16 07:42:18 +02:00
ba5cc57166 get_type not exists for optiondescription, change it to impl_get_group_type 2019-10-16 07:34:03 +02:00
280d2ebd0a better error message if option that does not exists is in root optiondescription 2019-10-16 07:31:52 +02:00
42291aec51 DynOptionDescription accept only suffixes attributes with Calculation, no more callback/callback_params 2019-10-15 17:45:21 +02:00
fd50913466 add Calculation to values 2019-09-28 16:32:48 +02:00
f976c31233 Changelog 2019-09-16 07:56:34 +02:00
06ad839468 add parents method to MetaConfig 2019-09-02 14:11:36 +02:00
bb2ecc94d9 add Calculation to properties 2019-09-01 09:41:53 +02:00
7c641961d3 better validation with parent + deepconfig 2019-08-28 15:55:10 +02:00
4321bde399 prefix metaconfig_prefix with current name 2019-08-26 17:04:46 +02:00
c15dac8093 unrestraint in subconfig 2019-08-24 08:14:54 +02:00
82a91db16e prefix metaconfig_prefix with current name 2019-08-21 16:24:50 +02:00
5ff47ac5c9 rc 11 2019-08-19 14:13:56 +02:00
a9ca9fdb6a add multi parents tests 2019-08-07 08:40:23 +02:00
b6ec77aa23 better way to manage follower in MetaConfig 2019-08-07 08:38:32 +02:00
2d7d237e19 Config could have multiple parents 2019-08-05 22:31:56 +02:00
113b7a3410 todict works with Metaconfig 2019-08-03 21:03:23 +02:00
1691e38db5 separate Cache from values and settings 2019-08-01 18:22:18 +02:00
c5ce9be699 doc + description + can updates with dict 2019-07-29 22:13:04 +02:00
613ae47573 update tests ans version number 2019-07-26 10:13:45 +02:00
fd18af62ca update Changelog and translation 2019-07-26 09:45:19 +02:00
34d71901d0 to_dict improvment and add display_name parameter to change impl_get_display_name function 2019-07-26 08:55:20 +02:00
35ef218c9c better message error 2019-07-26 08:52:01 +02:00
a33c7ed41e follower option with consistency 2019-07-16 08:03:33 +02:00
73d45f54cf follower option with consistency 2019-07-14 10:35:46 +02:00
69384a5e69 update translations 2019-07-06 11:39:06 +02:00
e73f3d1e47 we have to access to option without restriction 2019-07-06 08:36:13 +02:00
d3eef77c03 works with test/auto tests 2019-07-06 07:18:32 +02:00
fb1286e50e better hidden/display support 2019-07-04 20:43:47 +02:00
83f05197fb update todict support and tests 2019-06-21 23:04:04 +02:00
55da00f131 3.0 rc 8 2019-06-21 09:14:09 +02:00
516a5a7219 copy default properties when copy config or create a config in a metaconfig 2019-06-20 15:24:21 +02:00
620e8bbf2e optimize 2019-06-12 08:45:56 +02:00
4df36a5548 3.0 rc7 2019-06-05 15:03:17 +02:00
aa11e3b79c can retrieve metaconfig/mixconfig/config in a metaconfig/mixconfig 2019-06-05 14:37:58 +02:00
07e6ea5eb2 can add new config with mixconfig type 2019-06-05 12:33:00 +02:00
e7cbd7849a add test for config's deepcopy 2019-05-28 07:19:26 +02:00
b9e9e98270 reindent 2019-05-27 16:21:43 +02:00
a774378732 local must not be None 2019-05-27 16:18:57 +02:00
5498a12b2b copy/deepcopy groupconfig 2019-05-27 16:11:41 +02:00
552cd3740d todict: better support for callback 2019-05-09 20:32:43 +02:00
5ea35bf84e simplify tiramisu dict format 2019-04-22 10:51:44 +02:00
6d0d233d9b demoting_error_warning is not more mandatory in option.dict()
RequirementError returns proptype
better submulti support for valid_mandatory
2019-04-17 19:13:40 +02:00
829247e79f better symlink support for option.dict() 2019-04-17 19:13:17 +02:00
63094f7e54 better error messages with list 2019-04-13 22:04:49 +02:00
1aec891408 import tiramisu-json in tiramisu repository 2019-04-08 20:34:05 +02:00
48b3b7e8a4 flit 2019-04-07 20:51:53 +02:00
4dbb82ed3f Python Packaging Autority recommandations 2019-04-05 22:39:24 +02:00
97b75660c5 do not change Config contexts properties when reload in MetaConfig (fixes #7) 2019-04-05 22:11:54 +02:00
06f501ad05 test for property in persistent storage 2019-04-05 21:17:36 +02:00
2b45955886 add/remove config in mixconfig or metaconfig (fixes #6) 2019-04-05 21:00:25 +02:00
0e02ae3182 changelog 2019-03-24 20:27:26 +01:00
ac42fd509c remove documentation (now in a separate project) 2019-03-24 20:26:51 +01:00
4709ac5f01 corrections in debug logger 2019-03-23 08:26:39 +01:00
cab8dae15a requirement can have callback 2019-03-13 08:49:18 +01:00
05abe76932 add generic calc_value function 2019-03-09 13:28:15 +01:00
33c1666cc9 add cidr notation to domainnameoption if allow_ip is True (fixes #5) 2019-03-08 07:11:56 +01:00
2a6df8c8d8 safer option.type() (ref #4) 2019-03-06 21:50:28 +01:00
cc44cabf56 update translation 2019-03-05 20:46:04 +01:00
35ee424810 add test_leadership_requires_transitive 2019-03-03 08:02:57 +01:00
5c0ac75c52 multiple option call (fixes #1) 2019-03-02 21:31:21 +01:00
7873910322 doesn't check follower requirement with an other follower or a leader if idx is None (fixes #3) 2019-03-02 19:43:58 +01:00
d25edd7dd7 update test_auto (fixes #2) 2019-03-02 19:32:55 +01:00
e786b4068d update french translation 2019-02-25 20:32:14 +01:00
da015d3af0 coverage 2019-02-25 20:30:20 +01:00
a248e114de simplify netmaskoption 2019-02-25 19:29:00 +01:00
74d367c731 simplify netmaskoption 2019-02-25 19:18:52 +01:00
0e20318a9b simplify netmaskoption 2019-02-25 19:10:20 +01:00
334 changed files with 33022 additions and 23538 deletions

1
.gitignore vendored
View File

@ -3,5 +3,4 @@
*.pyc
*.mo
*.swp
version.in
build/

View File

@ -1,4 +1,68 @@
Sat Sep 8 22:54:12 2018 +0200 Emmanuel Garette <egarette@cadoles.com>
Mon Apr 1 11:47:30 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc16
* tiramisu is now async
* add postgresql storage
Mon Sep 2 14:10:40 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc15
* add parents method to MetaConfig
Wed Aug 28 15:50:30 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc14
* correction in metaconfig_prefix
* correction in validation with parent
Mon Aug 21 14:24:42 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc12
* prefix metaconfig_prefix with current name
Mon Aug 19 08:02:27 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc11
* Config could have multiple parents
* todict works with Metaconfig
* separate Cache from values and settings
Fri Jul 26 09:43:03 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc9 and rc10
* better todict support (especially for leadership
* can add display_name method to Config init to change the name a
option in errors
Mon Jun 5 14:49:27 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc7
* retrieve metaconfig/mixconfig/config by name in a metaconfig/mixconfig
* add new config with mixconfig type
Mon Apr 8 08:40:10 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc6
* import tiramisu-json in tiramisu repository
Fri Apr 5 20:57:05 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc4 and rc5
* change filename/directory name with Python Packaging Autority
recommendations
* do not change Config contexts properties when reload in MetaConfig
(fixes #7)
* add/remove config in mixconfig or metaconfig (fixes #6)
Sun Mar 24 20:24:34 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc3
* corrections in debug logger
* requirement can have callback
* version 3.0 rc2
* add cidr notation to domainnameoption if allow_ip is True (fixes #5)
* safer option.type() (ref #4)
Tue Mar 5 08:22:12 2018 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc2
* simplifying netmaskoption
* multiple option call (fixes #1)
* doesn't check follower requirement with an other follower or a leader if idx is None (fixes #3)
Mon Feb 25 10:12:35 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc1
Sat Sep 8 22:54:12 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* propose a new API to access to Tiramisu Option
This new API is totally incompatible with older's one

8
MANIFEST.in Normal file
View File

@ -0,0 +1,8 @@
# Include the README
include *.rst
# Include the license file
include LICENSE.txt
# Include the data files
recursive-include tiramisu *.py *.mo

View File

@ -10,7 +10,7 @@ INSTALL_DATA := install -m 644
INSTALL_PROGRAM := install -m 755
INSTALL_DIR := install -m 755 -d
TRADUC_DIR = translations
TRADUC_DIR = tiramisu/locale
TRADUC_DEST = $(DESTDIR)/usr/share/locale
PYTHON_OPTS =
@ -26,7 +26,7 @@ define gettext
else \
P="pygettext.py" ; \
fi ; \
$$P -p translations/ -o $(PACKAGE).pot `find $(PACKAGE)/ -name "*.py"`
$$P -p $(TRADUC_DIR)/ -o $(PACKAGE).pot `find $(PACKAGE)/ -name "*.py"`
endef
# Build translation files
@ -69,12 +69,12 @@ build-pot:
build-lang:
$(call build_translation, $(TRADUC_DIR))
install-lang:
$(INSTALL_DIR) $(TRADUC_DEST)
$(call install_translation, $(TRADUC_DIR))
# install-lang:
# $(INSTALL_DIR) $(TRADUC_DEST)
# $(call install_translation, $(TRADUC_DIR))
install: install-lang
python setup.py install --no-compile $(PYTHON_OPTS)
install: # install-lang
python3 setup.py install --no-compile $(PYTHON_OPTS)
dist:
git archive --format=tar --prefix $(PACKAGE)-$(VERSION)/ HEAD | gzip -9 > $(PACKAGE)-$(VERSION).tar.gz

View File

View File

@ -1 +0,0 @@
master

View File

@ -1,153 +0,0 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/tiramisu.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/tiramisu.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/tiramisu"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/tiramisu"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@ -1,6 +0,0 @@
{{ fullname }}
{{ underline }}
.. automodule:: {{ fullname }}
:members:
:noindex:

View File

@ -1,15 +0,0 @@
Auto generated library's API
================================
.. autosummary::
:toctree: api
:template: module.rst
tiramisu.option
tiramisu.setting
tiramisu.config
tiramisu.value
tiramisu.autolib
tiramisu.error
tiramisu.storage

View File

@ -1,6 +0,0 @@
tiramisu.autolib
================
.. automodule:: tiramisu.autolib
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.config
===============
.. automodule:: tiramisu.config
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.error
==============
.. automodule:: tiramisu.error
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.option
===============
.. automodule:: tiramisu.option
:members:
:noindex:

View File

@ -1,5 +0,0 @@
tiramisu.setting
================
.. automodule:: tiramisu.setting
:members:

View File

@ -1,6 +0,0 @@
tiramisu.storage
================
.. automodule:: tiramisu.storage
:members:
:noindex:

View File

@ -1,5 +0,0 @@
tiramisu.value
==============
.. automodule:: tiramisu.value
:members:

View File

@ -1,295 +0,0 @@
# -*- coding: utf-8 -*-
#
# tiramisu documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 20 14:29:31 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.extlinks']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'tiramisu'
copyright = u'2013, tiramisu team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'traditional'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'tiramisudoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'tiramisu.tex', u'tiramisu Documentation',
u'gwen', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'tiramisu', u'tiramisu Documentation',
[u'gwen'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'tiramisu', u'tiramisu Documentation',
u'gwen', 'tiramisu', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'tiramisu'
epub_author = u'gwen'
epub_publisher = u'gwen'
epub_copyright = u'2012, gwen'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
todo_include_todos = True
extlinks = {'api': ('./api/tiramisu.%s', ""),
'test': ('./api/test.%s', "")}
autosummary_generate = True

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,257 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="400"
height="200"
id="svg2"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="test.svg"
inkscape:export-filename="/home/gnunux/git/tiramisu/doc/storage.png"
inkscape:export-xdpi="135"
inkscape:export-ydpi="135">
<defs
id="defs4">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
id="perspective3827" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="1"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="73.881208"
inkscape:cy="154.11692"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="1600"
inkscape:window-height="841"
inkscape:window-x="0"
inkscape:window-y="27"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-852.36218)">
<g
id="g4206"
transform="translate(32.34835,646.56497)">
<text
sodipodi:linespacing="686.00001%"
id="text2985"
y="368.36218"
x="98"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="368.36218"
x="98"
id="tspan2987"
sodipodi:role="line">Config</tspan></text>
<rect
y="351.36218"
x="81"
height="30"
width="63"
id="rect3757"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
</g>
<g
id="g4211"
transform="translate(-21.922096,643.64303)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text3777"
y="325.76599"
x="220.51762"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="325.76599"
x="220.51762"
id="tspan3779"
sodipodi:role="line">Option</tspan><tspan
y="335.76599"
x="220.51762"
sodipodi:role="line"
id="tspan3022">Description</tspan></text>
</g>
<g
id="g4201"
transform="translate(11,622)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<g
id="g4201-9"
transform="translate(85.749784,621.95117)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5-1"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190-0"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194-2"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<g
id="g4211-4"
transform="translate(52.525433,602.85429)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2-3"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text3777-0"
y="325.76599"
x="220.51762"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="325.76599"
x="220.51762"
id="tspan3779-1"
sodipodi:role="line">Option</tspan><tspan
y="335.76599"
x="220.51762"
sodipodi:role="line"
id="tspan3022-7">Description</tspan></text>
</g>
<g
id="g4201-1"
transform="translate(123.6527,582.89051)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5-7"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190-2"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194-8"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 151.43627,945.42468 19.70537,10.58053"
id="path3110"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4201"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 198.77217,956.00521 -0.21665,-10.62936"
id="path3112"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4201-9"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 226.45587,956.00521 19.69159,-10.78874"
id="path3114"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211-4"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 259.11483,915.21647 -8.55152,-8.90128"
id="path3116"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211-4"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4201-1"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 164.25211,997.92715 15.42203,-11.92194"
id="path3118"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4206"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211"
inkscape:connection-end-point="d4" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.0 KiB

View File

@ -1,570 +0,0 @@
.. default-role:: literal
===============================
Options handling basics
===============================
Tiramisu is made of almost three main objects :
- :class:`tiramisu.option.Option` stands for the option types
- :class:`tiramisu.option.OptionDescription` is the shema, the option's structure
- :class:`tiramisu.config.Config` which is the whole configuration entry point
Accessing the `Option`'s
-------------------------
The :class:`~tiramisu.config.Config` object attribute access notation stands for
the value of the configuration's :class:`~tiramisu.option.Option`.
:class:`~tiramisu.config.Config`'s object attribute is the name of the option,
and the value is the value accessed by the `__getattr__` attribute access
mechanism.
If the attribute of the `Config` called by `__getattr__` has not been set before
(by the classic `__setattr__` mechanism), the default value of the `Option`
object is returned, and if no `Option` has been declared in the
`OptionDescription` (that is the schema of the configuration), an
`AttributeError` is raised.
::
>>> from tiramisu.config import Config
>>> from tiramisu.option import BoolOption, OptionDescription
>>>
>>> gcdummy = BoolOption('dummy', 'dummy', default=False)
>>> gcdummy.impl_getdefault()
False
>>> cfg.dummy
False
>>> descr = OptionDescription('tiramisu', '', [gcdummy])
>>> cfg = Config(descr)
>>> cfg.dummy = True
>>> cfg.dummy
True
>>> cfg.idontexist
AttributeError: 'OptionDescription' object has no attribute 'idontexist'
The `Option` objects (in this case the :class:`~tiramisu.option.BoolOption`),
are organized into a tree into nested
:class:`~tiramisu.option.OptionDescription` objects.
.. image:: config.png
Every option has a name, as does every option group. The parts
of the full name of the option are separated by dots: e.g.
``cfg.optgroup.optname``.
Let's make the protocol of accessing a `Config`'s attribute explicit
(because explicit is better than implicit):
1. If the option has not been declared, an `AttributeError` is raised,
2. If an option is declared, but neither a value nor a default value has
been set, the returned value is `None`,
3. If an option is declared and a default value has been set, but no value
has been set, the returned value is the default value of the option,
4. If an option is declared, and a value has been set, the returned value is
the value of the option.
But there are special exceptions. We will see later on that an option can be a
:term:`mandatory option`. A mandatory option is an option that must have a value
defined.
Setting the value of an option
------------------------------
An important part of the setting's configuration consists of setting the
value's option. There are different ways of setting values,
the first one is of course the `__setattr__` method
::
cfg.name = value
And if you wanna come back to a default value, use the builtin `del()` function::
del(cfg.name)
.. module:: tiramisu.config
.. _`tree`:
The handling of options
~~~~~~~~~~~~~~~~~~~~~~~~~~
The handling of options is split into two parts: the description of
which options are available, what their possible values and defaults are
and how they are organized into a tree. A specific choice of options is
bundled into a configuration object which has a reference to its option
description (and therefore makes sure that the configuration values
adhere to the option description).
Common manipulations
------------------------
Let's perform some common manipulation on some options
>>> from tiramisu.config import Config
>>> from tiramisu.option import UnicodeOption, OptionDescription
>>> #
>>> var1 = UnicodeOption('var1', 'first variable')
>>> var2 = UnicodeOption('var2', '', u'value')
>>> #
>>> od1 = OptionDescription('od1', 'first OD', [var1, var2])
>>> rootod = OptionDescription('rootod', '', [od1])
let's set somme access rules on the main namespace
>>> c = Config(rootod)
>>> c.read_write()
let's travel the namespaces
>>> print c
[od1]
>>> print c.od1
var1 = None
var2 = value
>>> print c.od1.var1
None
>>> print c.od1.var2
value
let's modify a value (be careful to the value's type...)
>>> c.od1.var1 = 'value'
Traceback (most recent call last):
ValueError: invalid value value for option var1
>>> c.od1.var1 = u'value'
>>> print c.od1.var1
value
>>> c.od1.var2 = u'value2'
>>> print c.od1.var2
value2
let's come back to the default value
>>> del(c.od1.var2)
>>> print c.od1.var2
value
The value is saved in a :class:`~tiramisu.value.Value` object. It is on this
object that we have to trigger the `reset`, which take the option itself
(`var2`) as a parameter.
On the other side, in the `read_only` mode, it is not possible to modify the value
>>> c.read_only()
>>> c.od1.var2 = u'value2'
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: cannot change the value for option var2 this option is frozen
let's retrieve the option `var1` description
>>> var1.impl_get_information('doc')
'first variable'
And if the option has been lost, it is possible to retrieve it again:
>>> c.unwrap_from_path('od1.var1').impl_get_information('doc')
'first variable'
Searching for an option
~~~~~~~~~~~~~~~~~~~~~~~~~~
In an application, knowing the path of an option is not always feasible.
That's why a tree of options can easily be searched. First, let's build such a tree::
>>> var1 = UnicodeOption('var1', '')
>>> var2 = UnicodeOption('var2', '')
>>> var3 = UnicodeOption('var3', '')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> var4 = UnicodeOption('var4', '')
>>> var5 = UnicodeOption('var5', '')
>>> var6 = UnicodeOption('var6', '')
>>> var7 = UnicodeOption('var1', '', u'value')
>>> od2 = OptionDescription('od2', '', [var4, var5, var6, var7])
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
Second, let's find an option by it's name::
>>> print c.find(byname='var1')
[<tiramisu.option.UnicodeOption object at 0x7ff1bf7d6ef0>,
<tiramisu.option.UnicodeOption object at 0x7ff1b90c7290>]
If the option name is unique, the search can be stopped once one matched option
has been found:
>>> print c.find_first(byname='var1')
<tiramisu.option.UnicodeOption object at 0x7ff1bf7d6ef0>
Instead of the option's object, the value or path can be retrieved:
>>> print c.find(byname='var1', type_='value')
[None, u'value']
>>> print c.find(byname='var1', type_='path')
['od1.var1', 'od2.var1']
Finaly, a search can be performed on the values, the type or even a combination
of all these criteria:
>>> print c.find(byvalue=u'value', type_='path')
['od2.var1']
>>> print c.find(bytype=UnicodeOption, type_='path')
['od1.var1', 'od1.var2', 'od1.var3', 'od2.var4', 'od2.var5', 'od2.var6', 'od2.var1']
>>> print c.find(byvalue=u'value', byname='var1', bytype=UnicodeOption, type_='path')
['od2.var1']
The search can be performed in a subtree:
>>> print c.od1.find(byname='var1', type_='path')
['od1.var1']
In a root tree or in a subtree, all option can be retrieved in a dict container:
>>> print c.make_dict()
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value',
'od1.var1': None, 'od1.var3': None, 'od1.var2': None}
If the organisation in a tree is not important,
:meth:`~config.SubConfig.make_dict()` results can be flattened
>>> print c.make_dict(flatten=True)
{'var5': None, 'var4': None, 'var6': None, 'var1': u'value', 'var3': None,
'var2': None}
.. note:: be carefull with this `flatten` parameter, here we have just lost
two options named `var1`
One can export only interesting parts of a tree of options into a dict, for
example the options that are in the same group that a given `var1` option::
>>> print c.make_dict(withoption='var1')
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value',
'od1.var1': None, 'od1.var3': None, 'od1.var2': None}
>>> print c.make_dict(withoption='var1', withvalue=u'value')
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value'}
and of course, :meth:`~config.SubConfig.make_dict()` can be called in a subtree:
>>> print c.od1.make_dict(withoption='var1')
{'var1': None, 'var3': None, 'var2': None}
The owners
~~~~~~~~~~~
.. glossary::
owner
When a value is set on an option, an owner is set too, that's why one can know
at any time if a value is a default value or not. Let's create a tree::
>>> var1 = UnicodeOption('var1', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
Then let's retrieve the owner associated to an option::
>>> print c.getowner(var1)
default
>>> c.od1.var1 = u'no'
>>> print c.getowner(var1)
user
>>> del(c.var1)
>>> print c.getowner(var1)
default
You can create your own owner, for example to distinguish modification made by
one user to an other one's.
>>> from tiramisu.setting import owners
>>> owners.addowner('toto')
>>> c.cfgimpl_get_settings().setowner(owners.toto)
>>> print c.getowner(var1)
default
>>> c.od1.var1 = u'no'
>>> print c.getowner(var1)
toto
The properties
~~~~~~~~~~~~~~
A property is an information on an option's state.
Let's create options with properties::
>>> var1 = UnicodeOption('var1', '', u'value', properties=('hidden',))
>>> var2 = UnicodeOption('var2', '', properties=('mandatory',))
>>> var3 = UnicodeOption('var3', '', u'value', properties=('frozen', 'unknown'))
>>> var4 = UnicodeOption('var4', '', u'value')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> od2 = OptionDescription('od2', '', [var4], properties=('hidden',))
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
A hidden value is a value that cannot be accessed in read/write mode. This
option cannot be modified any more. Let's try to access to an option's value
with a hidden option::
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: var1
with properties ['hidden']
>>> c.read_only()
>>> print c.od1.var1
value
A mandatory option is an option with a value that shall not be `None`. The
value has to be defined. Accessing to such an option is easy in read/write
mode. But in read only mode, an error is raised if no value has been defined::
>>> c.read_write()
>>> print c.od1.var2
None
>>> c.read_only()
>>> print c.od1.var2
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: var2
with properties ['mandatory']
>>> c.read_write()
>>> c.od1.var2 = u'value'
>>> c.read_only()
>>> print c.od1.var2
value
A frozen option, is an option that cannot be modified by a user.
Let's try to modify a frozen option::
>>> c.read_write()
>>> print c.od1.var3
value
>>> c.od1.var3 = u'value2'
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: cannot change the value for option var3 this option is frozen
>>> c.read_only()
>>> print c.od1.var3
value
Tiramisu allows us to use user defined properties. Let's define and use one in
read/write or read only mode::
>>> c.cfgimpl_get_settings().append('unknown')
>>> print c.od1.var3
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var3 with properties ['unknown']
>>> c.cfgimpl_get_settings().remove('unknown')
>>> print c.od1.var3
value
Many properties can be defined at the same time on an option::
>>> c.cfgimpl_get_settings().extend(['unknown1', 'unknown2'])
Properties can also be defined on an option group (that is, on an
:term:`option description`) let's hide a group and try to access to it::
>>> c.read_write()
>>> print c.od2.var4
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: od2
with properties ['hidden']
>>> c.read_only()
>>> print c.od2.var4
value
Furthermore, let's retrieve the properties, delete and add the `hidden` property::
>>> c.read_write()
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('hidden')
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('hidden')
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
.. _multi-option:
The multi-options
~~~~~~~~~~~~~~~~~~~~~
.. glossary::
multi-option
Multi-options are normal options that have list of values (multiple values)
instead of values::
>>> var1 = UnicodeOption('var1', '', [u'val1', u'val2'], multi=True)
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
A multi-option's value can be manipulated like a list::
>>> print c.od1.var1
[u'val1', u'val2']
>>> c.od1.var1 = [u'var1']
>>> print c.od1.var1
[u'var1']
>>> c.od1.var1.append(u'val3')
>>> print c.od1.var1
[u'var1', u'val3']
>>> c.od1.var1.pop(1)
u'val3'
>>> print c.od1.var1
[u'var1']
But it is not possible to set a value to a multi-option which is not a list::
>>> c.od1.var1 = u'error'
Traceback (most recent call last):
ValueError: invalid value error for option var1 which must be a list
The master/slave groups
~~~~~~~~~~~~~~~~~~~~~~~~~
.. glossary::
master/slave
A master/slave group is an :class:`~tiramisu.option.OptionDescription` and the
options that lives inside.
Inside this group, a special option, named master option, has the same name as
the group. The group (the option description) is set to type `master`.
All options in a master group is a multi-option (see :ref:`multi-option`).
The slave options have a `default_multi` attribute set to `True`::
>>> from tiramisu.setting import groups
>>> from tiramisu.config import Config
>>> from tiramisu.option import UnicodeOption, OptionDescription
>>>
>>> var1 = UnicodeOption('master', '', multi=True)
>>> var2 = UnicodeOption('slave1', '', multi=True)
>>> var3 = UnicodeOption('slave2', '', multi=True, default_multi=u"default")
>>>
>>> od1 = OptionDescription('master', '', [var1, var2, var3])
>>> od1.impl_set_group_type(groups.master)
>>>
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The length of the lists can be modified::
>>> print c.master
master = []
slave1 = []
slave2 = []
>>> c.master.master.append(u'oui')
>>> print c.master
master = [u'oui']
slave1 = [None]
slave2 = [u'default']
>>> c.master.master = [u'non']
>>> print c.master
master = [u'non']
slave1 = [None]
slave2 = [u'default']
>>>
>>> c.master.master = [u'oui', u'non']
>>> print c.master
master = [u'oui', u'non']
slave1 = [None, None]
slave2 = [u'default', u'default']
But it is forbidden to change the lenght of a slave::
>>> c.master.slave1[0] = u'super'
>>> print c.master
master = [u'oui', u'non']
slave1 = [u'super', None]
slave2 = [u'default', u'default']
>>> c.master.slave1 = [u'new1', u'new2']
>>> print c.master
master = [u'oui', u'non']
slave1 = [u'new1', u'new2']
slave2 = [u'default', u'default']
>>> c.master.slave1 = [u'new1']
Traceback (most recent call last):
tiramisu.error.SlaveError: invalid len for the slave: slave1 which has master.master as master
>>> c.master.slave1 = [u'new1', u'new2', u'new3']
tiramisu.error.SlaveError: invalid len for the slave: slave1 which has master.master as master
you have to call the `pop` function on the master::
>>> c.master.master = [u'oui']
Traceback (most recent call last):
tiramisu.error.SlaveError: invalid len for the master: master which has slave1 as slave with greater len
>>> c.master.master.pop(0)
u'oui'
>>> print c.master
master = [u'non']
slave1 = [u'new2']
slave2 = [u'default']
Configuration's interesting methods
------------------------------------------
A `Config` object is informed by an `option.OptionDescription`
instance. The attributes of the ``Config`` objects are the names of the
children of the ``OptionDescription``.
Here are the (useful) methods on ``Config`` (or `SubConfig`).
.. currentmodule:: tiramisu.config
.. class:: Config
.. autoclass:: SubConfig
:members: find, find_first, __iter__, iter_groups, iter_all, make_dict
.. automethod:: __init__
.. rubric:: Summary
.. autosummary::
find
find_first
__iter__
iter_groups
iter_all
make_dict
.. rubric:: Methods
A :class:`~config.CommonConfig` is a abstract base class. A
:class:`~config.SubConfig` is an just in time created objects that wraps an
::class:`~option.OptionDescription`. A SubConfig differs from a Config in the
fact that a config is a root object and has an environnement, a context which
defines the different properties, access rules, vs... There is generally only
one Config, and many SubConfigs.

View File

@ -1,306 +0,0 @@
.. default-role:: literal
.. currentmodule:: tiramisu
The global consistency
===========================
Identical option names
----------------------
If an :class:`~option.Option()` happens to be defined twice in the
:term:`schema` (e.g. the :class:`~option.OptionDescription()`),
that is the two options actually have the same name, an exception is raised.
The calculation is currently carried out in the samespace, for example
if `config.gc.name` is defined, another option in `gc` with the name
`name` is **not** allowed, whereas `config.whateverelse.name` is still
allowed.
Option's values type validation
--------------------------------
When a value is set to the option, the value is validated by the
option's :class:`option.Option()` validator's type.
Notice that if the option is `multi`, that is the `multi` attribute is set to
`True`, then the validation of the option value accepts a list of values
of the same type.
For example, an :class:`option.IntOption` validator waits for an `int` object of
course, an :class:`option.StrOption` validator waits for an `str`, vs...
Where are located the values
-------------------------------
The entry point of the acces to the values is the :class:`setting.Setting()` of
the root configuration object, but the values are actually located in the
:class:`value.Values()` object, in order to be delegated in some kind of a
`tiramisu.storage`, which can be a in-memory storage, or a persistent (for the
time being, a sqlite3) storage.
:class:`value.Values()` is also responsible of the owners and the calculation
of the options that have callbacks.
Requirements
------------
Configuration options can specify requirements as parameters at the init
time, the specification of some links between options or groups allows
to carry out a dependencies calculation. For example, an option can ben
hidden if another option has been set with some expected value. This is
just an example, the possibilities are hudge.
A requirement is a list of dictionaries that have fairly this form::
[{'option': a, 'expected': False, 'action': 'disabled', 'inverse': True,
'transitive':True, 'same_action': True}]
Actually a transformation is made to this dictionary during the validation of
this requires at the :class:`~option.Option()`'s init. The dictionary becomes
a tuple, wich is passed to the :meth:`~setting.Settings.apply_requires()`
method. Take a look at the code to fully understand the exact meaning of the
requirements:
.. automethod:: tiramisu.setting.Settings.apply_requires
The path of the option is required, the second element is the value wich is
expected to trigger the callback, it is required too, and the third one is the
callback's action name (`hide`, `show`...), wich is a
:class:`~setting.Property()`. Requirements are validated in
:class:`setting.Setting`.
Let's create an option wich has requirements::
>>> from tiramisu.option import *
>>> from tiramisu.config import *
>>> var2 = UnicodeOption('var2', '', u'oui')
>>> var1 = UnicodeOption('var1', '', u'value', requires=[{'option':var2, 'expected':u'non', 'action':'hidden'}])
>>> var3 = UnicodeOption('var3', '', u'value', requires=[{'option':var2, 'expected':u'non', 'action':'hidden'}, {'option':var2, 'expected':u'non', 'action':'disabled'}])
>>> var4 = UnicodeOption('var4', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> od2 = OptionDescription('od2', '', [var4], requires=[{'option':od1.var2, 'expected':u'oui', 'action':'hidden', 'inverse':True}])
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
The requirement here is the dict `{'option':var2, 'expected':u'non',
'action':'hidden'}` wich means that is the option `'od1.var2'` is set to
`'non'`, the option `'od1.var1'` is gonna be hidden. On the other hand, if the
option `'od1.var2'` is different from `'non'`, the option `'od1.var1'` is not
hidden any more::
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
>>> print c.od1.var2
oui
>>> c.od1.var2 = u'non'
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
>>> c.od1.var2 = u'oui'
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
The requirement on `od2` is `{'option':od1.var2, 'expected':u'oui',
'action':'hidden', 'inverse':True}`, which means that if the option `od1.var2`
is set to `oui`, the option is not hidden (because of the `True` at the end of
the tuple wich means 'inverted', take a look at the :doc:`consistency`
document.)::
>>> print c.od2.var4
oui
>>> c.od1.var2 = u'non'
>>> print c.od2.var4
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: od2 with properties ['hidden']
>>> c.od1.var2 = u'oui'
>>> print c.od2.var4
oui
Requirements can be accumulated
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
[]
>>> c.od1.var2 = u'non'
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
['disabled', 'hidden']
>>> c.od1.var2 = u'oui'
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
[]
Requirements can be accumulated for different or identical properties (inverted
or not)::
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'expected':'oui',
... 'action':'hidden'}])
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'excepted':'oui',
... 'action':'disabled', 'inverse':True}])
But it is not possible to have inverted requirements on the same property.
Here is an impossible situation::
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'expected':'oui',
... 'hidden', True}])
Traceback (most recent call last):
ValueError: inconsistency in action types for option: var3 action: hidden
Validation upon a whole configuration object
----------------------------------------------
An option's integrity can be validated towards a whole configuration.
This type of validation is very open. Let's take a use case : an option
has a certain value, and the value of this option can change the owner
of another option or option group... Everything is possible.
.. currentmodule:: tiramisu.option
Other hooks are availables to validate upon a whole configuration at any time,
for example the consistency between two options (typically, an
:class:`IPOption` and a :class:`NetworkOption`).
Let's define validator (wich is a normal python function)::
>>> def valid_a(value, letter=''):
... return value.startswith(letter)
Here is an option wich uses this validator::
>>> var1 = UnicodeOption('var1', '', u'oui', validator=valid_a, validator_args={'letter': 'o'})
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The validation is applied at the modification time::
>>> c.od1.var1 = u'non'
Traceback (most recent call last):
ValueError: invalid value non for option var1
>>> c.od1.var1 = u'oh non'
You can disabled this validation::
>>> c.cfgimpl_get_settings().remove('validator')
>>> c.od1.var1 = u'non'
Values that are calculated
--------------------------------
An option that have a callback is considered to have a value that is to be
calculated.
An option's property with a `force_store_value` attribute is considered to be
modified at the first calculation.
.. automodule:: tiramisu.autolib
:members:
This is the typically protocol for accessing a option's for a calculated value,
but some twisted ways are also possible, take a look at the `force_store_value`
attribute.
.. glossary::
force store value
A calculated value (that is, an option that has a callback) with the
attribute `force_store_value` enabled is considered to be modified at
the first calculation
Let's create four calculation functions::
def return_calc():
#return an unicode value
return u'calc'
def return_value(value):
return value
def return_value_param(param=u''):
return param
def return_no_value_if_non(value):
#if value is not u'non' return value
if value == u'non':
return None
else:
return value
Then we create four options using theses functions::
>>> var1 = UnicodeOption('var1', '', callback=return_calc)
>>> var2 = UnicodeOption('var2', '', callback=return_value, callback_params={'': (u'value',)})
>>> var3 = UnicodeOption('var3', '', callback=return_value_param, callback_params={'param': (u'value_param',)})
>>> var4 = UnicodeOption('var4', '', callback=return_no_value_if_non, callback_params={'': (('od1.var5', False),)})
>>> var5 = UnicodeOption('var5', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3, var4, var5])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The first option `var1` returns the result of the `return_calc` function, wich
is `u'calc'`::
>>> print c.od1.var1
calc
The second option `var2` returns the result of the `return_value` fucntion,
wich is `value`. The parameter `u'value'` is passed to this function::
>>> print c.od1.var2
value
The third option `var3` returns the result of the function `return_value_param`
with the named parameter `param` and the value `u'value_param'`::
>>> print c.od1.var3
value_param
The fourth option `var4` returns the reslut of the function `return_no_value_if_non`
that is the value of `od1.var5` exceptif the value is u`non`::
>>> print c.od1.var4
oui
>>> c.od1.var5 = u'new'
>>> print c.od1.var4
new
>>> c.od1.var5 = u'non'
>>> print c.od1.var4
None
The calculation replaces the default value.
If we modify the value, the calculation is not carried out any more::
>>> print c.od1.var1
calc
>>> c.od1.var1 = u'new_value'
>>> print c.od1.var1
new_value
To force the calculation to be carried out in some cases, one must add the
`frozen` and the `force_default_on_freeze` properties::
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('frozen')
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('force_default_on_freeze')
>>> print c.od1.var1
calc
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('frozen')
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('force_default_on_freeze')
>>> print c.od1.var1
new_value

View File

@ -1,92 +0,0 @@
Test framework
==================
Have a look at the :file:`test` subdirectory of the project.
We are using py.test_
.. _py.test: http://pytest.org/latest/
config APIs
-----------------
.. automodule:: test.test_config
:members:
option APIs
---------------
.. automodule:: test.test_option
:members:
others
----------
.. automodule:: test.test_mandatory
:members:
.. automodule:: test.test_config_big_example
:members:
.. automodule:: test.test_option_default
:members:
.. automodule:: test.test_option_consistency
:members:
.. automodule:: test.test_cache
:members:
.. automodule:: test.test_option_setting
:members:
.. automodule:: test.test_freeze
:members:
.. automodule:: test.test_config_ip
:members:
.. automodule:: test.test_slots
:members:
.. automodule:: test.test_reverse_from_path
:members:
.. automodule:: test.test_requires
:members:
.. automodule:: test.test_option_owner
:members:
.. automodule:: test.test_permissive
:members:
.. automodule:: test.test_option_type
:members:
.. automodule:: test.test_dereference
:members:
.. automodule:: test.test_storage
:members:
.. automodule:: test.test_option_calculation
:members:
.. automodule:: test.test_option_with_special_name
:members:
.. automodule:: test.test_config_domain
:members:
.. automodule:: test.test_symlink
:members:
.. automodule:: test.test_metaconfig
:members:
.. automodule:: test.test_parsing_group
:members:

View File

@ -1,12 +0,0 @@
SRC=$(wildcard *.tex)
OBJ=$(subst .tex,.pdf,$(SRC))
pdf: $(OBJ)
%.pdf: %.tex
pdflatex $<
clean:
rm -f $(OBJ)
rm -f *.aux *.log *.toc *.snm *.out *.nav

View File

@ -1,69 +0,0 @@
\begin{frame}
\frametitle{Comparaison entre le noyau de Créole et Tiramisu}
\begin{itemize}
\item \emph{Tiramisu} a pour objectif de
\begin{itemize}
\item remplacer le noyau \emph{Creole} (\texttt{EoleDict}) de manière transparente ;
\item résoudre les problèmes inhérents à \texttt{CreoleServ} ;
\end{itemize}
\item au niveau du code, il y a enfin une vraie séparation du c\oe ur et du fonctionnel ;
\item valide le type \emph{et la structure}, l'ajout de types est aisé.
\item \emph{Creole} : \texttt{EoleDict, EoleVars} $ \Leftrightarrow $ \texttt{Config, Option}\\
cf \texttt{tiramisu/doc/build/pydoc/index.html}
\item intégré à \texttt{gen\_config}, \texttt{cheetah}, \texttt{DTD Creole}, syntaxe \texttt{Creole} \dots
\item \texttt{eole-report/D02CoherenceVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Gestionnaire de configuration existants}
\begin{itemize}
\item Le gestionnaire de conf de Victor Stinner $\Rightarrow$ \emph{NuFw};
\item puppet, cfgengine... $\Rightarrow$ intéressant, de nombreux comportements peuvent être repris, mais tel quel difficilement compatible avec \emph{Creole};
\item \emph{Creole} $\Leftrightarrow$ \texttt{tiramisu/doc/build/glossary.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Un "vrai" serveur de config}
\begin{itemize}
\item un serveur de données de configuration ;
\item $1^{ere}$ méthode : exportation (snapshot) d'un état de la config $ \Rightarrow $ Créole ;
\item $2^{eme}$ méthode : JIT (just in time) calculation, une modification
de l'état de la configuration est possible \emph{pendant} la manipulation et l'utilisation de la conf $ \Rightarrow $ Tiramisu.
\item \texttt{doc/getting-started.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Qu'est-ce qu'un gestionnaire de conf moderne ?}
\begin{itemize}
\item c'est une organisation arborescente des données (les données sont imbriquées) ;
\item c'est un accès facile aux données (typiquement une interface de type \emph{dictionnaire}) ;
\item clefs-valeurs, mais quelles valeurs exactement ? $ \Rightarrow $ calcul JIT (just in time) ;
\item \texttt{eole-report/D01AccesVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Définition d'un gestionnaire de configuration}
\begin{itemize}
\item les families, groups, master \dots~ ce sont des \emph{schémas} de données (\texttt{OptionDescription}) ;
\item c'est la configuration (\texttt{Config}) qui est responsable de l'accès aux valeurs ;
\item la configuration est aisément manipulable, et a un point d'entrée unique ;
\item l'accès aux valeurs des \texttt{Options} de configuration ne peut se faire \emph{que} depuis la conf racine.
\item \texttt{eole-report/D01AccesVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Organisation en espace de nommage}
\begin{itemize}
\item dans \emph{tiramisu} l'accent est mis sur l'organisation arborescente des données ;
\item la validation des options de configuration se fait par l'appartenance aux groupes (families, master/slaves \dots) ;
\item l'organisation en groupes est unifiée par l'espace de nommage ;
\item \texttt{eole-report/D03ReglesEtats.pdf}
\item lisibilité d'une config : \texttt{tiramisu/report/build/index.html} rapport html d'une config
\end{itemize}
\end{frame}

View File

@ -1,61 +0,0 @@
\begin{frame}
\frametitle{Etats ("status") de la configuration}
\begin{itemize}
\item système d'états de la configuration par \emph{droits d'accès} ;
\item \texttt{read write}, \texttt{read only} ;
\item correspond à \texttt{freeze}, \texttt{hidden}, \texttt{disabled} \dots ;
\item \texttt{doc/status.html} ;
\item \texttt{eole-report/D03ReglesEtats.pdf} ;
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{hidden if in, hidden if not in}
\begin{itemize}
\item les hidden if in, disabled if, \dots sont généralisés
\item dans tiramisu, ce sont des pré-requis sur une (des) variables
\item \texttt{eole-report/D03ReglesEtats.pdf}
\item \texttt{doc/consistency.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{un peu de mathématiques : prévenir les deadlocks}
\begin{itemize}
\item sûreté : prévention des deadlocks ;
\item dans tiramisu, le modèle est suffisamment abstrait pour que son exploitation mathématique soit
réalisable par les techniques de \emph{Model Checking} ;
\item soit on a besoin de ne connaître que l'ensemble des états, pas leurs liens $\Rightarrow$ espace d'états ;
\item soit on a besoin de connaître toutes les relations $\Rightarrow$ graphe d'accessibilité ;
\item la configuration est modélisable en une structure de \emph{Kripe} ;
\item déjà le parsing de la conf est facile, la preuve : \texttt{tiramisu/report/build/index.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{un peu de mathématiques (suite) CreoleLint}
\begin{itemize}
\item exemple : $ P = 3 \wedge Q = 1 \triangleleft \langle P = 1 \hookleftarrow Q = 0 \rangle$
\item la propriété \og dans aucun état on a $P = 3$ et $Q = 1$ \fg~ est-elle vraie ?
Pour vérifier cette propriété, on a besoin de connaître l'espace d'états ;
\item la propriété \og chaque chemin débutant dans un état accessible $P=1$ passe par un état où $Q=3$ et $P=2$ \fg~
est-elle vraie ? Cela demande de connaître le graphe d'accessibilité ;
\item les structures de \emph{Kripe} sont des machines à états étiquetées par les valuations de toutes les variables propositionnelles ;
\item une compliation statique devient possible dans \emph{CreoleLint} \dots
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{compatibilité Créole : ce qui reste à faire}
\begin{itemize}
\item les options spéciales sont implémentées (auto, fill, obligatoire, \dots) reste la librairie des fonctions pour les variables automatiques \texttt{eosfunc} ;
\item tous les états sont implémentés (hidden, disabled, mode (normal/expert), \dots), il faut fixer les comportement \texttt{read write} ;
\item les "valprec" (valeur précédentes) et une mémoire de \emph{tous} les états antérieurs ;
\item fixer les comportement des hides (sous-groupes récursifs, \dots) ;
\item validations master/slaves, validations globales au regard de la configuration entière puisque c'est possible maintenant.
\end{itemize}
\end{frame}

View File

@ -1,36 +0,0 @@
%%presentation
\documentclass{beamer}
\usepackage{beamerthemetree}
%%impression
%\documentclass[a4paper,9pt]{extarticle}
%\usepackage{beamerarticle}
%%
% class FR
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[frenchb]{babel}
% image
%% \usepackage{graphicx}
\usepackage{alltt}
\usecolortheme{crane}
\beamertemplatetransparentcovered
%\logo{\includegraphics[height=1cm]{ban.png}}
\title{Tiramisu}
\subtitle{gestionnaire de configuration}
\author{Gwen}
\institute{\texttt{git clone git://git.labs.libre-entreprise.org/tiramisu.git} \\
\texttt{firefox tiramisu/doc/build/index.html}}
\date{\today}
\begin{document}
\frame{\titlepage}
\include{definition}
\include{statut}
\end{document}

View File

@ -1,19 +0,0 @@
Errors that may be encountered
==================================
Three builtins exceptions are used :
-----------------------------------------
- **ValueError** : Validation error, parameters error, a list instead
of a Multi, or if the value does not make sense
- **TypeError** : type error in a parameter
- **AttributeError** : wrong path or unknownd option or optiondescription
And five other exceptions :
------------------------------
.. automodule:: tiramisu.error
:members:

View File

@ -1,86 +0,0 @@
==================================
Getting started
==================================
What is options handling ?
=================================
Due to more and more available options required to set up an operating system,
compiler options or whatever, it became quite annoying to hand the necessary
options to where they are actually used and even more annoying to add new
options. To circumvent these problems the configuration control was
introduced...
What is Tiramisu ?
===================
Tiramisu is an options handler and an options controller, which aims at
producing flexible and fast options access. The main advantages are its access
rules and the fact that the whole consistency is preserved at any time, see
:doc:`consistency`. There is of course type and structure validations, but also
validations towards the whole options. Furthermore, options can be reached and
changed according to the access rules from nearly everywhere in your appliance.
Just the facts
==============
.. _gettingtiramisu:
`tiramisu`\ 's home page is here_
.. _here: https://forge.cadoles.com/Cadoles/tiramisu
Download
---------
To obtain a copy of the sources, check it out from the repository using `git`.
We suggest using `git` if one wants to access to the current developments.
::
git clone https://forge.cadoles.com/Cadoles/tiramisu.git
This will get you a fresh checkout of the code repository in a local directory
named ``tiramisu``.
Getting started
-------------------
Option objects can be created in different ways. Let's perform very basic
:class:`~tiramisu.option.Option` and :class:`~tiramisu.config.Config` object
manipulations:
::
>>> from tiramisu.config import Config
>>> from tiramisu.option import OptionDescription, BoolOption
>>> # let's create a group of options... with only one option inside
>>> descr = OptionDescription("optgroup", "", [
... BoolOption("bool", "", default=False)])
>>> # c is a namespace as well as a container for the options
>>> c = Config(descr)
>>> c.bool
False
>>> c.bool = True
>>> c.bool
True
So by now, we have:
- a namespace (which is `c` here)
- the access of an option's value by the
attribute access way (here `bool`, which is a boolean option
:class:`~tiramisu.option.BoolOption()`.
So, option objects are produced at the entry point `c` and then handed down to
where they are actually used when `c.bool` is triggered. This keeps options
local but available at any timer and consistent.
Once the namespace is created, we can set a
:meth:`~config.CommonConfig.read_write()` access to the options::
>>> c.read_write()
which enables us to set a bunch of access rules that we wil explain later in
:doc:`status`.

View File

@ -1,86 +0,0 @@
.. default-role:: literal
Glossary
==========
.. glossary::
configuration
Global configuration object, wich contains the whole configuration
options *and* their descriptions (option types and group)
schema
option description
see :class:`tiramisu.option.OptionDescription`
The schema of a configuration :
- the option types
- how they are organised in groups or even subgroups, that's why we
call them **groups** too.
configuration option
An option object wich has a name and a value and can be accessed
from the configuration object
access rules
Global access rules are : :meth:`~config.CommonConfig.read_write()` or
:meth:`~config.Config.read_only()`, see :doc:`status`
default value
Default value of a configuration option. The default value can be
set at instanciation time, or even at any moment. Remember that if
you reset the default value, the owner reset to `default`
freeze
A whole configuration can be frozen (used in read only access). See
:ref:`frozen` for details.
A single option can be frozen too.
value owner
When an option is modified, including at the instanciation, we
always know who has modified it. It's the owner of the option, see
:doc:`status` for more details.
option with properties
an option wich has property like 'hidden' or 'disabled' is an option
wich has restricted acces rules
hidden option
a hidden option has a different behaviour on regards to the access
of the value in the configuration, see :doc:`status` for more details.
disabled option
a disabled option has a different behaviour on regards to the access
of the value in the configuration, see :doc:`status` for more details.
mandatory option
A mandatory option is a configuration option wich value has to be
set, that is the default value cannot be `None`.
consistency
Preserving the consistency in a whole configuration is a tricky thing,
tiramisu takes care of it for you, see :doc:`consistency` for details.
context
The context is a :class:`tiramisu.setting.Setting()` object in the
configuration that enables us to access to the global properties
for example the `read_write` or `read_only` :term:`access rules`

View File

@ -1,62 +0,0 @@
.. default-role:: literal
.. meta::
:description: configuration management
:keywords: config, configuration
.. title:: tiramisu
The tasting of `Tiramisu`
=========================
.. image:: logo.png
:height: 150px
`Tiramisu`
is a cool, refreshing Italian dessert,
it is also an `options controller tool`_.
.. _`options controller tool`: http://en.wikipedia.org/wiki/Configuration_management#Overview
It's a pretty small, local (that is, straight on the operating system) options
handler and controller.
controlling options explanations
--------------------------------------
.. toctree::
:maxdepth: 1
getting-started
config
option
storage
status
consistency
error
glossary
api
doctest
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. note:: The tiramisu code is licensed under the `LGPL licence`_
and this documentation is licensed under the `Creative Commons
Attribution-ShareAlike 3.0 Unported License`_\ .
.. _`Creative Commons Attribution-ShareAlike 3.0 Unported License`: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
.. _`LGPL licence`: http://www.gnu.org/licenses/lgpl.html
.. todolist::

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,125 +0,0 @@
.. default-role:: literal
.. module:: tiramisu.option
The options types
===================
Description of Options
----------------------
All the constructors take a ``name`` and a ``doc`` argument as first
arguments to give to the option or option description a name and a description document.
Most constructors take a ``default`` argument that specifies the default
value of the option. If this argument is not supplied the default value
is assumed to be ``None``.
The `Option` base class
-------------------------
It's the abstract base class for almost all options (except the symlink).
.. _optioninit:
.. autoclass:: Option
:special-members:
:members:
All option types
------------------
BoolOption
~~~~~~~~~~
.. autoclass:: BoolOption
:private-members:
IntOption
~~~~~~~~~
.. autoclass:: IntOption
:private-members:
FloatOption
~~~~~~~~~~~
.. autoclass:: FloatOption
:private-members:
StrOption
~~~~~~~~~
.. autoclass:: StrOption
:private-members:
UnicodeOption
~~~~~~~~~~~~~
.. autoclass:: UnicodeOption
:private-members:
SymLinkOption
~~~~~~~~~~~~~
.. autoclass:: SymLinkOption
:private-members:
``SymLinkOption`` redirects to another configuration option in the
configuration, that is :
- retrieves the value of the target,
- can set the value of the target too
IPOption
~~~~~~~~
.. autoclass:: IPOption
:private-members:
PortOption
~~~~~~~~~~
.. autoclass:: PortOption
:private-members:
NetmaskOption
~~~~~~~~~~~~~
.. autoclass:: NetmaskOption
:private-members:
NetworkOption
~~~~~~~~~~~~~
.. autoclass:: NetworkOption
:private-members:
DomainnameOption
~~~~~~~~~~~~~~~~
.. autoclass:: DomainnameOption
:private-members:
ChoiceOption
~~~~~~~~~~~~
.. autoclass:: ChoiceOption
:private-members:
.. _optdescr:
The `OptionDescription` class
-------------------------------
.. autoclass:: OptionDescription
:special-members:
:members:
If you need to access to an option object, you can do it with the
OptionDescription object. Not only the value of the option by attribute access,
but the option object itself that lives behind the scene. It can always be
accessed internally. The option objects are in the `_children`
`OptionDescription`'s attribute.

View File

@ -1,155 +0,0 @@
.. default-role:: literal
Local statuses and global settings
=====================================
Available configuration statuses
----------------------------------
.. currentmodule:: tiramisu
The configuration's status lives in an :class:`setting.Setting()` object.
This configuration status corresponds to specific attributes or bunch of
attributes that can be accessed together with some `setting.Setting`
method:
**read write status**
The configuration can be accessed by `__get__` and `__set__`
properties, except for the `hidden` configuration options but, yes, it is
possible to modify a disabled option.
To enable read-write status, call
:class:`~config.CommonConfig.read_write()` on the config.
**read only status**
The whole configuration is `frozen`, that is modifiying a value is
forbidden. We can access to a configuration option only with the
`__getattr__` property.
The configuration has not an access to the hidden options
but can read the disabled options.
To enable read only status, call :class:`~config.SubConfig.read_only()` on
the config.
.. csv-table:: **Configuration's statuses summary**
:header: " ", "Hidden", "Disabled", "Mandatory"
"read only status", `False`, `True`, `True`
"read-write status", `True`, `False`, `False`
.. _`frozen`:
Freezing a configuration
---------------------------
At the configuration level, :class:`~setting.Setting()` enables us to freeze the
whole configuration, wich means that the frozen :class:`~option.Option()`'s
values cannot be modified.
It is possible to *freeze* a single :class:`~option.Option()` object with
:meth:`~config.SubConfig.cfgimpl_get_settings()`. If you try to modify a frozen
option, it raises a `TypeError: trying to change a frozen option object`.
To find out if an option `myoption` is frozen, just make an assertion on the
settings like that::
'frozen' in cfg.cfgimpl_get_settings()[myoption]
Moreover, frozen option can return their default values if
:meth:`~option.Option.force_default()` is called on this option.
.. glossary::
force default on freeze
A single option is frozen and we want the option to return something
else than his value, typically it is his default value.
In the option's values, an attribute can be set
:attr:`force_default_on_freeze`, that forces this behavior.
Restricted access to an `Option()`
-----------------------------------
.. autoclass:: tiramisu.setting.Property
The `properties` attribute is in charge of the access rules' option's value.
Configuration options access statuses are defined at configuration level
that corresponds to the `option.Option()`'s `properties` attribute,
for example: hidden, disabled.
Use the pythonic way to know if a property is there::
'hidden' in c.cfgimpl_get_settings()
'frozen' in c.cfgimpl_get_settings()[opt]
To access to the global settings::
cfg.cfgimpl_get_settings()
cfg.cfgimpl_get_settings()[option1]
to add, or suppress a global property::
cfg.cfgimpl_get_settings()[option1].append('hidden')
cfg.cfgimpl_get_settings()[option1].remove('hidden')
to activate, deactivate properties::
cfg.cfgimpl_get_settings().append('hidden')
cfg.cfgimpl_get_settings().remove('hidden')
The global properties are living in e :class:`~setting.Setting` object. A
`Setting` object also takes care of the way to access option values and the
storage in the cache.
Value owners
-------------
Every configuration option has a **owner**. When the option is instanciated,
the owner is :obj:`setting.owners.default` because a default value has been set
(including `None`, wich means that no value has been set yet).
.. method:: config.CommonConfig.getowner()
This method can retrieve an Option's owner.
- At the instance of the `Config` object, the value owner is
:obj:`setting.owners.default` because
the default values are set at the instance of the configuration option
object,
- at the modification of an option, the owner is `owners.default`, (which is
:obj:`owners.user`)
Special behaviors for an option
---------------------------------
**mandatory**
A mandatory option shall return a value. If a value, or a default value
has not been set, a error is raised.
**has a callback**
This means that it is a calculated value and therefore automatically
protected it cannot be modified by attribute access.
**force_store_value**
if the configuration option has a default value, the default is
returned, otherwise the value is calculated.
Its inner state is represented by `option.Option.force_default()`
Configuration options have default values that are stored in the
`Option()` object itself. Default values, the `default`, can be set in
various ways.
If a default value is modified by overriding it, not only the value of
the option resets to the default that is proposed, but the owner is
modified too, it is reseted to `owners.default`.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,265 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="400"
height="200"
id="svg2"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="test.svg"
inkscape:export-filename="/home/gnunux/git/tiramisu/doc/storage.png"
inkscape:export-xdpi="135"
inkscape:export-ydpi="135">
<defs
id="defs4">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
id="perspective3827" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="1"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="106.95445"
inkscape:cy="208.15932"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="1600"
inkscape:window-height="841"
inkscape:window-x="0"
inkscape:window-y="27"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-852.36218)">
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 235.5,78.588237 306,109"
id="path4403"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
transform="translate(0,852.36218)" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 235.5,131.08416 305,107"
id="path4405"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4216"
inkscape:connection-start-point="d4"
transform="translate(0,852.36218)" />
<g
id="g4206"
transform="translate(-17,590)">
<text
sodipodi:linespacing="686.00001%"
id="text2985"
y="368.36218"
x="98"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="368.36218"
x="98"
id="tspan2987"
sodipodi:role="line">Config</tspan></text>
<rect
y="351.36218"
x="81"
height="30"
width="63"
id="rect3757"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
</g>
<g
id="g4211"
transform="translate(-17,590)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="686.00001%"
id="text3777"
y="330.36218"
x="206"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="330.36218"
x="206"
id="tspan3779"
sodipodi:role="line">Values</tspan></text>
</g>
<g
id="g4216"
transform="translate(-17,590)">
<rect
y="389.36218"
x="189.5"
height="30"
width="63"
id="rect3757-4"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="686.00001%"
id="text3799"
y="407.36218"
x="200"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="407.36218"
x="200"
id="tspan3801"
sodipodi:role="line">Settings</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 127,967.39444 45.5,15.93548"
id="path4028"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 127,945.0396 45.5,-16.35484"
id="path4030"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect4161"
width="55.5"
height="26"
x="277.5"
y="946.36218" />
<path
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z"
transform="matrix(0.71325325,0,0,0.57998971,18.66254,749.17042)" />
<path
transform="matrix(0.71325325,0,0,0.57998971,18.57337,775.05247)"
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843-3"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z" />
<path
transform="matrix(0.71325325,0,0,0.57998971,18.52879,762.07519)"
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843-3-0"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect3883"
width="62.989182"
height="6.7061315"
x="274.72043"
y="949.91193" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect3883-3"
width="58.087975"
height="6.4161367"
x="277.34818"
y="962.78046" />
<path
style="fill:none;stroke:#000000;stroke-width:1.26286423;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
d="m 277.52869,943.35095 -0.0442,26.02673"
id="path3917"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#000000;stroke-width:1.26286423;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
d="m 331.64698,969.26909 0.13377,-26.17203"
id="path3921"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<text
xml:space="preserve"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
x="286.33643"
y="958.32324"
id="text3821"
sodipodi:linespacing="686.00001%"><tspan
sodipodi:role="line"
id="tspan3823"
x="286.33643"
y="958.32324">Storage</tspan></text>
<g
id="g4201"
transform="translate(-17,590)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 95.5,913.42468 0,27.9375"
id="path4199"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,52 +0,0 @@
Storage
=======
.. automodule:: tiramisu.storage
.. automethod:: tiramisu.storage.set_storage
.. image:: storage.png
Dictionary
~~~~~~~~~~
.. automodule:: tiramisu.storage.dictionary
Dictionary settings:
.. automethod:: tiramisu.storage.dictionary.storage.Setting
Sqlite3
~~~~~~~
.. automodule:: tiramisu.storage.sqlite3
Sqlite3 settings:
.. automethod:: tiramisu.storage.sqlite3.storage.Setting
Example
~~~~~~~
>>> from tiramisu.option import StrOption, OptionDescription
>>> from tiramisu.config import Config
>>> from tiramisu.storage import set_storage
>>> set_storage('sqlite3', dir_database='/tmp/tiramisu')
>>> s = StrOption('str', '')
>>> o = OptionDescription('od', '', [s])
>>> c1 = Config(o, persistent=True, session_id='xxxx')
>>> c1.str
>>> c1.str = 'yes'
>>> c1.str
'yes'
>>> del(c1)
>>> c2 = Config(o, persistent=True, session_id='xxxx')
>>> c2.str
'yes'
>>> del(c2)
>>> list_sessions()
['xxxx']
>>> delete_session('xxxx')
>>> c3 = Config(o, persistent=True, session_id='xxxx')
>>> c3.str

View File

@ -1,57 +1,33 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from os.path import dirname, abspath, join, normpath, isdir
from os import listdir
from setuptools import setup
import os
from tiramisu import __version__
package_name = os.environ.get('PACKAGE_DST', 'tiramisu')
ORI_PACKAGE_NAME = 'tiramisu'
PACKAGE_NAME = os.environ.get('PACKAGE_DST', ORI_PACKAGE_NAME)
def fetch_version():
"""Get version from version.in"""
return open('VERSION', 'r').readline().strip()
def return_files(component):
here = dirname(abspath(__file__))
path = normpath(join(here, 'tiramisu', component))
dir_content = [content for content in listdir(path)
if not content == '__pycache__']
paths = filter(isdir, [join(path, content)
for content in dir_content])
lst = ['.'.join(path.split('/')[-3:]) for path in paths]
#lst = [package_name + '.' + '.'.join(path.split('/')[-2:]) for path in paths]
return lst
packages = [package_name, package_name + '.storage', package_name + '.option']
packages.extend(return_files('storage'))
packages.extend(return_files('option'))
if package_name != 'tiramisu':
package_dir = {package_name: 'tiramisu'}
if PACKAGE_NAME != ORI_PACKAGE_NAME:
package_dir = {PACKAGE_NAME: ORI_PACKAGE_NAME}
else:
package_dir = {}
package_dir = None
setup(
version=__version__,
author="Tiramisu's team",
author_email='contact@cadoles.com',
name=package_name,
version=fetch_version(),
author_email='gnunux@gnunux.info',
name=PACKAGE_NAME,
description='an options controller tool',
url='http://tiramisu.labs.libre-entreprise.org/',
url='https://framagit.org/tiramisu/tiramisu',
license='GNU Library or Lesser General Public License (LGPL)',
provides=['tiramisu_api'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Linguistic"
"Natural Language :: English",
"Natural Language :: French",
],
long_description="""\
An options controller tool
@ -67,8 +43,9 @@ Tiramisu is an options handler and an options controller, wich aims at
producing flexible and fast options access.
This version requires Python 2.6 or later.
This version requires Python 3.5 or later.
""",
packages=packages,
package_dir=package_dir
include_package_data=True,
package_dir=package_dir,
packages=[PACKAGE_NAME],
)

View File

@ -1,582 +0,0 @@
# coding: utf-8
from time import sleep, time
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu.option import BoolOption, IPOption, IntOption, StrOption, OptionDescription, Leadership
from tiramisu import Config
from tiramisu.error import ConfigError, PropertiesOptionError
from tiramisu.setting import groups
from tiramisu import undefined, Params, ParamValue, ParamOption, \
list_sessions, default_storage, delete_session
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__)
global incr
incr = -1
def return_incr():
global incr
incr += 1
return int(incr/2) + 1
def return_value(val):
return val
def make_description():
u1 = IntOption('u1', '', multi=True)
u2 = IntOption('u2', '')
u3 = IntOption('u3', '', multi=True)
return OptionDescription('od1', '', [u1, u2, u3])
def test_cache_config():
od1 = make_description()
assert od1.impl_already_build_caches() is False
c = Config(od1)
assert od1.impl_already_build_caches() is True
c
def test_cache():
od1 = make_description()
cfg = Config(od1)
values = cfg._config_bag.context.cfgimpl_get_values()
settings = cfg._config_bag.context.cfgimpl_get_settings()
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.option('u2').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' in values._p_.get_cached()
assert 'u2' in settings._p_.get_cached()
def test_cache_importation():
od1 = make_description()
cfg = Config(od1)
cfg.option('u2').value.set(1)
export = cfg.value.exportation()
assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
cfg.option('u2').value.set(2)
assert cfg.value.dict() == {'u1': [], 'u2': 2, 'u3': []}
cfg.value.importation(export)
assert cfg.value.dict() == {'u1': [], 'u2': 1, 'u3': []}
def test_cache_importation_property():
od1 = make_description()
cfg = Config(od1)
cfg.option('u2').property.add('prop')
export = cfg.property.exportation()
assert cfg.option('u2').property.get() == {'prop'}
cfg.option('u2').property.add('prop2')
assert cfg.option('u2').property.get() == {'prop', 'prop2'}
cfg.property.importation(export)
assert cfg.option('u2').property.get() == {'prop'}
def test_cache_importation_permissive():
od1 = make_description()
cfg = Config(od1)
cfg.option('u2').permissive.set(frozenset(['prop']))
export = cfg.permissive.exportation()
assert cfg.option('u2').permissive.get() == {'prop'}
cfg.option('u2').permissive.set(frozenset(['prop', 'prop2']))
assert cfg.option('u2').permissive.get() == {'prop', 'prop2'}
cfg.permissive.importation(export)
assert cfg.option('u2').permissive.get() == {'prop'}
def test_cache_reset():
od1 = make_description()
cfg = Config(od1)
values = cfg._config_bag.context.cfgimpl_get_values()
settings = cfg._config_bag.context.cfgimpl_get_settings()
#when change a value
cfg.option('u1').value.get()
cfg.option('u2').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' in values._p_.get_cached()
assert 'u2' in settings._p_.get_cached()
assert 'u1' in values._p_.get_cached()
cfg.option('u2').value.set(1)
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' not in values._p_.get_cached()
assert 'u2' not in settings._p_.get_cached()
#when remove a value
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.option('u2').value.reset()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' not in values._p_.get_cached()
assert 'u2' not in settings._p_.get_cached()
#when add/del property
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.option('u2').property.add('test')
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' not in values._p_.get_cached()
assert 'u2' not in settings._p_.get_cached()
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.option('u2').property.pop('test')
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' not in values._p_.get_cached()
assert 'u2' not in settings._p_.get_cached()
#when enable/disabled property
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.property.add('test')
assert 'u1' not in values._p_.get_cached()
assert 'u1' not in settings._p_.get_cached()
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.property.pop('test')
assert 'u1' not in values._p_.get_cached()
assert 'u1' not in settings._p_.get_cached()
def test_cache_reset_multi():
od1 = make_description()
cfg = Config(od1)
values = cfg._config_bag.context.cfgimpl_get_values()
settings = cfg._config_bag.context.cfgimpl_get_settings()
cfg.option('u1').value.get()
cfg.option('u3').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' in values._p_.get_cached()
assert 'u3' in settings._p_.get_cached()
#when change a value
cfg.option('u3').value.set([1])
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' not in values._p_.get_cached()
assert 'u3' not in settings._p_.get_cached()
#when append value
cfg.option('u1').value.get()
cfg.option('u3').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' in values._p_.get_cached()
assert 'u3' in settings._p_.get_cached()
cfg.option('u3').value.set([1, 1])
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' not in values._p_.get_cached()
assert 'u3' not in settings._p_.get_cached()
#when pop value
cfg.option('u1').value.get()
cfg.option('u3').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' in values._p_.get_cached()
assert 'u3' in settings._p_.get_cached()
cfg.option('u3').value.set([1])
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' not in values._p_.get_cached()
assert 'u3' not in settings._p_.get_cached()
#when remove a value
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.option('u3').value.reset()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u3' not in values._p_.get_cached()
assert 'u3' not in settings._p_.get_cached()
def test_reset_cache():
od1 = make_description()
cfg = Config(od1)
values = cfg._config_bag.context.cfgimpl_get_values()
settings = cfg._config_bag.context.cfgimpl_get_settings()
cfg.option('u1').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
cfg.cache.reset()
assert 'u1' not in values._p_.get_cached()
assert 'u1' not in settings._p_.get_cached()
cfg.option('u1').value.get()
cfg.option('u2').value.get()
assert 'u1' in values._p_.get_cached()
assert 'u1' in settings._p_.get_cached()
assert 'u2' in values._p_.get_cached()
assert 'u2' in settings._p_.get_cached()
cfg.cache.reset()
assert 'u1' not in values._p_.get_cached()
assert 'u1' not in settings._p_.get_cached()
assert 'u2' not in values._p_.get_cached()
assert 'u2' not in settings._p_.get_cached()
def test_cache_not_cache():
od1 = make_description()
cfg = Config(od1)
values = cfg._config_bag.context.cfgimpl_get_values()
settings = cfg._config_bag.context.cfgimpl_get_settings()
cfg.property.pop('cache')
cfg.option('u1').value.get()
assert 'u1' not in values._p_.get_cached()
assert 'u1' not in settings._p_.get_cached()
def test_cache_leadership():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
cfg = Config(maconfig)
cfg.property.read_write()
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {}
#
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
cache = cfg._config_bag.context.cfgimpl_get_values()._p_.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 = cfg._config_bag.context.cfgimpl_get_settings()._p_.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])
#
cfg.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
cfg.option('ip_admin_eth0.ip_admin_eth0').value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()
cfg.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()
cache = cfg._config_bag.context.cfgimpl_get_values()._p_.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 = cfg._config_bag.context.cfgimpl_get_settings()._p_.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, 1])
#DEL, insert, ...
def return_value(value=None):
return value
def compare(calculated, expected):
assert set(calculated.keys()) == set(expected.keys())
for calculated_key in calculated:
assert set(calculated[calculated_key].keys()) == set(expected[calculated_key].keys())
for calculated_subkey in calculated[calculated_key]:
# do not check timestamp
assert calculated[calculated_key][calculated_subkey][0] == expected[calculated_key][calculated_subkey][0]
def test_cache_callback():
val1 = StrOption('val1', "", 'val')
val2 = StrOption('val2', "", callback=return_value, callback_params=Params((ParamOption(val1),)), properties=('mandatory',))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params((ParamValue('yes'),)))
val4 = StrOption('val4', "", callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
val5 = StrOption('val5', "", callback=return_value, callback_params=Params(kwargs={'value': ParamValue('yes')}), multi=True)
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5])
cfg = Config(maconfig)
cfg.property.read_write()
cfg.value.dict()
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('val', None)},
'val2': {None: ('val', None)},
'val3': {None: ('yes', None)},
'val4': {None: ('val', None)},
'val5': {None: (['yes'], None)}})
cfg.option('val1').value.set('new')
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val3': {None: ('yes', None)},
'val5': {None: (['yes'], None)}})
cfg.value.dict()
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('yes', None)},
'val4': {None: ('new', None)},
'val5': {None: (['yes'], None)}})
cfg.option('val3').value.set('new2')
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val4': {None: ('new', None)},
'val5': {None: (['yes'], None)}})
cfg.value.dict()
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new', None)},
'val5': {None: (['yes'], None)}})
cfg.option('val4').value.set('new3')
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)},
# 'val4': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val5': {None: (['yes'], None)}})
cfg.value.dict()
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)},
# 'val4': {None: (set([]), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)},
'val5': {None: (['yes'], None)}})
cfg.option('val5').value.set([undefined, 'new4'])
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)},
# 'val4': {None: (set([]), None)},
# 'val5': {None: (set(['empty']), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)}})
cfg.value.dict()
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)},
# 'val3': {None: (set([]), None)},
# 'val4': {None: (set([]), None)},
# 'val5': {None: (set(['empty']), None)}}
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1': {None: ('new', None)},
'val2': {None: ('new', None)},
'val3': {None: ('new2', None)},
'val4': {None: ('new3', None)},
'val5': {None: (['yes', 'new4'], None)}})
def test_cache_leader_and_followers():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
cfg = Config(maconfig)
cfg.property.read_write()
cfg.value.dict()
global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']
val1_props = []
val1_val1_props = ['empty']
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
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1.val1': {None: ([], None)}})
#
cfg.option('val1.val1').value.set([undefined])
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached(), {None: {None: (set(global_props), None)}})
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
cfg.value.dict()
#has value
idx_val2 = 0
val_val2 = None
val_val2_props = {idx_val2: (val1_val2_props, None), None: (set(), None)}
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1.val1': {None: ([None], None)},
'val1.val2': {idx_val2: (val_val2, None)}})
cfg.option('val1.val1').value.set([undefined, undefined])
cfg.value.dict()
cfg.option('val1.val2', 1).value.set('oui')
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}})
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
val1_val2_props = {0: (frozenset([]), None), 1: (frozenset([]), None)}
#assert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (global_props, None)},
# 'val1': {None: (val1_props, None)},
# 'val1.val1': {None: (val1_val1_props, None)},
# 'val1.val2': val1_val2_props}
#if TIRAMISU_VERSION == 2:
# assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {'val1.val1': {None: ([None, None], None)},
# 'val1.val2': {None: ([None, 'oui'], None)}}
#else:
# assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {'val1.val1': {None: ([None, None], None)},
# 'val1.val2': {0: (None, None), 1: ('oui', None)}}
def test_cache_leader_callback():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
cfg = Config(maconfig)
cfg.property.read_write()
cfg.value.dict()
global_props = ['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']
val1_props = []
val1_val1_props = ['empty']
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)
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'val1.val1': {None: ([], None)}})
cfg.option('val1.val1').value.set([undefined])
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached(), {None: {None: (set(global_props), None)}})
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
cfg.value.dict()
#FIXMEassert cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached() == {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings']), None)},
# 'val1': {None: (set([]), None)}}
#FIXMEassert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {'val1.val1': {None: ([None], None)},
# 'val1.val2': {None: ([None], None)}
# }
def test_cache_requires():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
cfg = Config(od)
cfg.property.read_write()
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
assert cfg.option('ip_address_service').value.get() == None
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}})
cfg.value.dict()
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}})
cfg.option('ip_address_service').value.set('1.1.1.1')
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)},
'activate_service': {None: (set([]), None)}})
compare(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'activate_service': {None: (True, None)}})
cfg.value.dict()
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'ip_address_service': {None: ('1.1.1.1', None)},
'activate_service': {None: (True, None)}})
cfg.option('activate_service').value.set(False)
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.get_cached(), {None: {None: (set(['cache', 'disabled', 'frozen', 'hidden', 'validator', 'warnings', 'force_store_value']), None)}})
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
cfg.value.dict()
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'activate_service': {None: (False, None)}})
def test_cache_global_properties():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
cfg = Config(od)
cfg.property.read_write()
assert cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached() == {}
assert cfg.option('ip_address_service').value.get() == None
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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(cfg._config_bag.context.cfgimpl_get_values()._p_.get_cached(), {'ip_address_service': {None: (None, None)},
'activate_service': {None: (True, None)}})
cfg.property.pop('disabled')
assert cfg.option('ip_address_service').value.get() == None
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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)}})
cfg.property.add('test')
assert cfg.option('ip_address_service').value.get() == None
compare(cfg._config_bag.context.cfgimpl_get_settings()._p_.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)}})
def test_callback_value_incr():
val1 = IntOption('val1', "", callback=return_incr, properties=('expire',))
val2 = IntOption('val2', "", callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
maconfig = OptionDescription('rootconfig', '', [val1, val2])
cfg = Config(maconfig)
assert cfg.cache.get_expiration_time() == 5
cfg.cache.set_expiration_time(1)
assert cfg.cache.get_expiration_time() == 1
cfg.property.read_write()
assert cfg.option('val1').value.get() == 1
sleep(1)
assert cfg.option('val2').value.get() == 1
sleep(1)
assert cfg.option('val1').value.get() == 1
assert cfg.option('val2').value.get() == 1
sleep(2)
assert cfg.option('val1').value.get() == 2
assert cfg.option('val2').value.get() == 2
assert cfg.option('val1').value.get() == 2
assert cfg.option('val2').value.get() == 2

View File

@ -1,253 +0,0 @@
# coding: utf-8
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu.setting import owners
from tiramisu import ChoiceOption, StrOption, OptionDescription, Config
from tiramisu.error import ConfigError
from tiramisu import undefined, Params, ParamValue, ParamOption
from tiramisu.api import TIRAMISU_VERSION
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def return_val(val):
return val
def return_list():
return ['val1', 'val2']
def return_calc_list(val):
return [val]
def return_error(*args, **kwargs):
raise Exception('test')
def test_choiceoption():
choice = ChoiceOption('choice', '', values=('val1', 'val2'))
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.get() == owners.default
assert cfg.option('choice').owner.isdefault()
#
cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner
assert not cfg.option('choice').owner.isdefault()
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.get() == owners.default
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.get() == owners.default
assert cfg.option('choice').owner.isdefault()
#
assert cfg.option('choice').value.list() == ('val1', 'val2')
def test_choiceoption_function():
choice = ChoiceOption('choice', '', values=return_list)
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.isdefault()
#
cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.isdefault()
#
assert cfg.option('choice').value.list() == ['val1', 'val2']
def test_choiceoption_function_error():
choice = ChoiceOption('choice', '', values=return_error)
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')")
def test_choiceoption_function_error_args():
choice = ChoiceOption('choice', '', values=return_error, values_params=Params((ParamValue('val1'),)))
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')")
def test_choiceoption_function_error_kwargs():
choice = ChoiceOption('choice', '', values=return_error, values_params=Params(kwargs={'kwargs': ParamValue('val1')}))
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set('val1')")
def test_choiceoption_calc_function():
choice = ChoiceOption('choice', "", values=return_calc_list, values_params=Params((ParamValue('val1'),)))
odesc = OptionDescription('od', '', [choice])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.isdefault()
#
cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.isdefault()
def test_choiceoption_calc_opt_function():
str_ = StrOption('str', '', 'val1')
choice = ChoiceOption('choice',
"",
values=return_calc_list,
values_params=Params((ParamOption(str_),)))
odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.isdefault()
#
cfg.option('choice').value.set('val1')
assert cfg.option('choice').owner.get() == owner
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.isdefault()
def test_choiceoption_calc_opt_function_propertyerror():
str_ = StrOption('str', '', 'val1', properties=('disabled',))
choice = ChoiceOption('choice',
"",
values=return_calc_list,
values_params=Params((ParamOption(str_),)))
odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc)
cfg.property.read_write()
if TIRAMISU_VERSION == 2:
raises(ValueError, "cfg.option('choice').value.set('no')")
else:
raises(ConfigError, "cfg.option('choice').value.set('no')")
def test_choiceoption_calc_opt_multi_function():
str_ = StrOption('str', '', ['val1'], multi=True)
choice = ChoiceOption('choice',
"",
default_multi='val2',
values=return_val,
values_params=Params((ParamOption(str_),)),
multi=True)
ch2 = ChoiceOption('ch2',
"",
default=['val2'],
values=return_val,
values_params=Params((ParamOption(str_),)),
multi=True)
odesc = OptionDescription('od', '', [str_, choice, ch2])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.isdefault()
assert cfg.option('choice').value.get() == []
#
cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner
#
raises(ValueError, "cfg.option('choice').value.set([undefined])")
#
cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('ch2').value.get()")
def test_choiceoption_calc_opt_multi_function_kwargs():
str_ = StrOption('str', '', ['val1'], multi=True)
choice = ChoiceOption('choice',
"",
default_multi='val2',
values=return_val,
values_params=Params(kwargs={'val': ParamOption(str_)}),
multi=True)
ch2 = ChoiceOption('ch2',
"",
default=['val2'],
values=return_val,
values_params=Params(kwargs={'val': ParamOption(str_)}),
multi=True)
odesc = OptionDescription('od', '', [str_, choice, ch2])
cfg = Config(odesc)
cfg.property.read_write()
owner = cfg.owner.get()
assert cfg.option('choice').owner.isdefault()
assert cfg.option('choice').value.get() == []
#
cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner
#
raises(ValueError, "cfg.option('choice').value.set([undefined])")
#
cfg.option('choice').value.set(['val1'])
assert cfg.option('choice').owner.get() == owner
#
cfg.option('choice').value.reset()
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('choice').value.set('no')")
assert cfg.option('choice').owner.isdefault()
#
raises(ValueError, "cfg.option('ch2').value.get()")
def test_choiceoption_calc_invalid():
str_ = StrOption('str', '', ['val1'], multi=True)
str_
raises(ValueError,
"choice = ChoiceOption('choice', '', default_multi='val2', values=[1, 2, 3], \
values_params=Params((ParamOption(str_),)), multi=True)")
def test_choiceoption_calc_not_list():
str_ = StrOption('str', '', 'val1')
choice = ChoiceOption('choice',
"",
default_multi='val2',
values=return_val,
values_params=Params((ParamOption(str_),)),
multi=True)
odesc = OptionDescription('od', '', [str_, choice])
cfg = Config(odesc)
cfg.property.read_write()
raises(ConfigError, "cfg.option('choice').value.set(['val1'])")

View File

@ -1,338 +0,0 @@
# -*- coding: utf-8 -*-
"""theses tests are much more to test that config, option description, vs...
**it's there** and answers via attribute access"""
from py.test import raises
import weakref
from .autopath import do_autopath
do_autopath()
from tiramisu import Config
from tiramisu.config import SubConfig
from tiramisu.i18n import _
from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, UnicodeOption, SymLinkOption, OptionDescription, undefined
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)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc", properties=('mandatory', ))
boolop = BoolOption('boolop', 'Test boolean option op', default=True, properties=('hidden',))
wantref_option = BoolOption('wantref', 'Test requires', default=False)
wantref_option.impl_set_information('info', 'default value')
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False)
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiram', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop])
return descr
def test_base_config():
"""making a :class:`tiramisu.config.Config()` object
and a :class:`tiramisu.option.OptionDescription()` object
"""
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr)
assert cfg.option('dummy').value.get() is False
#dmo = cfg.unwrap_from_path('dummy')
#assert dmo.impl_getname() == 'dummy'
def test_base_config_name():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
cfg = Config(descr, session_id='cfg')
cfg.config.name() == 'cfg'
#raises(ValueError, "Config(descr, session_id='unvalid name')")
#
#
#def test_not_config():
# assert raises(TypeError, "Config('str')")
def test_base_path():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
Config(descr)
base = OptionDescription('config', '', [descr])
base
raises(ConfigError, "Config(base)")
def test_base_config_force_permissive():
descr = make_description()
config = Config(descr)
config.property.read_write()
config.permissive.set(frozenset(['hidden']))
raises(PropertiesOptionError, "config.option('boolop').value.get()")
assert config.forcepermissive.option('boolop').value.get() is True
def test_base_config_in_a_tree():
"how options are organized into a tree, see :ref:`tree`"
descr = make_description()
config = Config(descr)
#
config.option('bool').value.set(False)
#
assert config.option('gc.name').value.get() == 'ref'
config.option('gc.name').value.set('framework')
assert config.option('gc.name').value.get() == 'framework'
#
assert config.option('objspace').value.get() == 'std'
config.option('objspace').value.set('thunk')
assert config.option('objspace').value.get() == 'thunk'
#
assert config.option('gc.float').value.get() == 2.3
config.option('gc.float').value.set(3.4)
assert config.option('gc.float').value.get() == 3.4
#
assert config.option('int').value.get() == 0
config.option('int').value.set(123)
assert config.option('int').value.get() == 123
#
assert config.option('wantref').value.get() is False
config.option('wantref').value.set(True)
assert config.option('wantref').value.get() is True
#
assert config.option('str').value.get() == 'abc'
config.option('str').value.set('def')
assert config.option('str').value.get() == 'def'
#
raises(AttributeError, "config.option('gc.foo').value.get()")
##
config = Config(descr)
assert config.option('bool').value.get() is True
assert config.option('gc.name').value.get() == 'ref'
assert config.option('wantframework').value.get() is False
def test_not_valid_properties():
raises(TypeError, "stroption = StrOption('str', 'Test string option', default='abc', properties=['mandatory',])")
def test_information_config():
descr = make_description()
config = Config(descr)
string = 'some informations'
#
assert list(config.information.list()) == []
config.information.set('info', string)
assert config.information.get('info') == string
assert list(config.information.list()) == ['info']
#
raises(ValueError, "config.information.get('noinfo')")
assert config.information.get('noinfo', 'default') == 'default'
config.information.reset('info')
raises(ValueError, "config.information.get('info')")
raises(ValueError, "config.information.reset('noinfo')")
assert list(config.information.list()) == []
def test_information_option():
descr = make_description()
config = Config(descr)
string = 'some informations'
#
list(config.option('gc.name').information.list()) == []
config.option('gc.name').information.set('info', string)
assert config.option('gc.name').information.get('info') == string
list(config.option('gc.name').information.list()) == ['info']
#
raises(ValueError, "config.option('gc.name').information.get('noinfo')")
assert config.option('gc.name').information.get('noinfo', 'default') == 'default'
config.option('gc.name').information.reset('info')
raises(ValueError, "config.option('gc.name').information.get('info')")
raises(ValueError, "config.option('gc.name').information.reset('noinfo')")
list(config.option('gc.name').information.list()) == []
#
assert config.option('wantref').information.get('info') == 'default value'
config.option('wantref').information.set('info', 'default value')
assert config.option('wantref').information.get('info') == 'default value'
config.option('wantref').information.reset('info')
assert config.option('wantref').information.get('info') == 'default value'
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 test_get_modified_values():
g1 = IntOption('g1', '', 1)
g2 = StrOption('g2', '', 'héhé')
g3 = UnicodeOption('g3', '', u'héhé')
g4 = BoolOption('g4', '', True)
g5 = StrOption('g5', '')
g6 = StrOption('g6', '', multi=True)
d1 = OptionDescription('od', '', [g1, g2, g3, g4, g5, g6])
root = OptionDescription('root', '', [d1])
config = Config(root)
assert to_tuple(config.value.exportation()) == ((), (), (), ())
assert not config.option('od.g5').option.ismulti()
assert not config.option('od.g5').option.issubmulti()
config.option('od.g5').value.set('yes')
assert to_tuple(config.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',))
config.option('od.g4').value.set(False)
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', False), ('user', 'user'))
config.option('od.g4').value.set(undefined)
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g4'), (None, None), ('yes', True), ('user', 'user'))
config.option('od.g4').value.reset()
assert to_tuple(config.value.exportation()) == (('od.g5',), (None,), ('yes',), ('user',))
assert config.option('od.g6').option.ismulti()
config.option('od.g6').value.set([undefined])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', (None,)), ('user', 'user'))
config.option('od.g6').value.set([])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))
config.option('od.g6').value.set(['3'])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', ('3',)), ('user', 'user'))
config.option('od.g6').value.set([])
assert to_tuple(config.value.exportation()) == (('od.g5', 'od.g6'), (None, None), ('yes', tuple()), ('user', 'user'))
def test_get_modified_values_not_modif():
g1 = StrOption('g1', '', multi=True)
d1 = OptionDescription('od', '', [g1])
root = OptionDescription('root', '', [d1])
config = Config(root)
assert config.option('od.g1').value.get() == []
value = config.option('od.g1').value.get()
value.append('val')
assert config.option('od.g1').value.get() == []
def test_duplicated_option():
g1 = IntOption('g1', '', 1)
g1
#in same OptionDescription
raises(ConflictError, "d1 = OptionDescription('od', '', [g1, g1])")
def test_duplicated_option_diff_od():
g1 = IntOption('g1', '', 1)
d1 = OptionDescription('od1', '', [g1])
#in different OptionDescription
d2 = OptionDescription('od2', '', [g1, d1])
d2
raises(ConflictError, 'Config(d2)')
def test_cannot_assign_value_to_option_description():
descr = make_description()
cfg = Config(descr)
raises(APIError, "cfg.option('gc').value.set(3)")
def test_config_multi():
i1 = IntOption('test1', '', multi=True)
i2 = IntOption('test2', '', multi=True, default_multi=1)
i3 = IntOption('test3', '', default=[2], multi=True, default_multi=1)
od = OptionDescription('test', '', [i1, i2, i3])
config = Config(od)
assert config.option('test1').value.get() == []
assert config.option('test2').value.get() == []
config.option('test2').value.set([undefined])
assert config.option('test2').value.get() == [1]
assert config.option('test3').value.get() == [2]
config.option('test3').value.set([undefined, undefined])
assert config.option('test3').value.get() == [2, 1]
def test_no_validation():
i1 = IntOption('test1', '')
od = OptionDescription('test', '', [i1])
config = Config(od)
config.property.read_write()
config.option('test1').value.set(1)
raises(ValueError, "config.option('test1').value.set('yes')")
assert config.option('test1').value.get() == 1
config.property.pop('validator')
config.option('test1').value.set('yes')
assert config.option('test1').value.get() == 'yes'
config.property.add('validator')
raises(ValueError, "config.option('test1').value.get()")
config.option('test1').value.reset()
assert config.option('test1').value.get() is None
def test_subconfig():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
c
raises(TypeError, "SubConfig(i, weakref.ref(c))")
def test_config_subconfig():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
od1 = OptionDescription('od1', '', [i1, i2, i3, i4])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf1')
raises(ConfigError, "conf2 = Config(od1, session_id='conf2')")
def test_config_invalidsession():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
raises(ValueError, 'Config(o2, session_id=2)')
def test_config_od_name():
i = IntOption('i', '')
s = SymLinkOption('s', i)
o = OptionDescription('val', '', [i, s])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').option.name() == 'i'
assert c.option('val.s').option.name() == 's'
assert c.option('val.s').option.name(follow_symlink=True) == 'i'
def test_config_od_type():
i = IntOption('i', '')
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').option.type() == 'integer'
def test_config_default():
i = IntOption('i', '', 8)
o = OptionDescription('val', '', [i])
o2 = OptionDescription('val', '', [o])
c = Config(o2)
assert c.option('val.i').value.default() == 8
c.option('val.i').value.set(9)
assert c.option('val.i').value.get() == 9
assert c.option('val.i').value.default() == 8

View File

@ -1,382 +0,0 @@
"configuration objects global API"
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu import Config, IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, FilenameOption, UnicodeOption, SymLinkOption, IPOption, \
PortOption, NetworkOption, NetmaskOption, BroadcastOption, \
DomainnameOption, OptionDescription
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__)
def make_description():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False)
prop = BoolOption('prop', 'prop 1', properties=('disabled',))
prop2 = StrOption('prop', 'prop 2', properties=('hidden',))
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
booloption2 = BoolOption('bool', 'Test boolean option', default=False)
intoption = IntOption('int', 'Test int option', default=0)
floatoption2 = FloatOption('float', 'Test float option', default=2.3)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Tests', default=False)
wantframework_option = BoolOption('wantframework', 'Test', default=False)
gcgroup2 = OptionDescription('gc2', '', [booloption2, prop])
gcgroup = OptionDescription('gc', '', [gcgroup2, gcoption, gcdummy, floatoption, prop2])
descr = OptionDescription('tiramisu', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop, floatoption2])
return descr
def _is_same_opt(opt1, opt2):
if "id" in dir(opt1):
assert opt1.id == opt2.id
else:
assert opt1 == opt2
def test_od_not_list():
b = BoolOption('bool', '', multi=True)
raises(AssertionError, "OptionDescription('od', '', b)")
def test_str():
descr = make_description()
c = Config(descr)
c # does not crash
def test_make_dict():
"serialization of the whole config to a dict"
descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('hidden',))]),
IntOption("int", "", default=42)])
config = Config(descr)
config.property.read_write()
config.permissive.set(frozenset(['hidden']))
d = config.value.dict()
assert d == {"s1.a": False, "int": 42}
config.option('int').value.set(43)
config.option('s1.a').value.set(True)
d = config.value.dict()
assert d == {"s1.a": True, "int": 43}
d2 = config.value.dict(flatten=True)
assert d2 == {'a': True, 'int': 43}
raises(ValueError, 'd2 = config.value.dict(withvalue="3")')
d = config.forcepermissive.value.dict()
assert d == {"s1.a": True, "s1.b": False, "int": 43}
def test_make_dict_with_disabled():
descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]),
OptionDescription("s2", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)])
config = Config(descr)
config.property.read_only()
assert config.value.dict() == {"s1.a": False, "int": 42}
assert config.forcepermissive.value.dict() == {"s1.a": False, "int": 42}
assert config.unrestraint.value.dict() == {"int": 42, "s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False}
def test_make_dict_with_disabled_withoption():
descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]),
OptionDescription("s2", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)])
config = Config(descr)
config.property.read_only()
assert config.value.dict(withoption="a") == {"s1.a": False}
assert config.forcepermissive.value.dict(withoption="a") == {"s1.a": False}
assert config.unrestraint.value.dict(withoption="a") == {"s1.a": False, "s1.b": False, "s2.a": False, "s2.b": False}
def test_make_dict_with_disabled_in_callback():
descr = OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]),
OptionDescription("s2", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)])
config = Config(descr)
config.property.read_only()
d = config.value.dict()
assert d == {"s1.a": False, "int": 42}
def test_make_dict_fullpath():
descr = OptionDescription("root", "", [
OptionDescription("opt", "", [
OptionDescription("s1", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False, properties=('disabled',))]),
OptionDescription("s2", "", [
BoolOption("a", "", default=False),
BoolOption("b", "", default=False)], properties=('disabled',)),
IntOption("int", "", default=42)]),
IntOption("introot", "", default=42)])
config = Config(descr)
config.property.read_only()
assert config.value.dict() == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
assert config.option('opt').value.dict() == {"s1.a": False, "int": 42}
assert config.value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42, "introot": 42}
assert config.option('opt').value.dict(fullpath=True) == {"opt.s1.a": False, "opt.int": 42}
def test_find_in_config():
"finds option in config"
descr = make_description()
conf = Config(descr)
conf.property.read_only()
conf.permissive.set(frozenset(['hidden']))
ret = list(conf.option.find('dummy'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get())
#
ret = conf.option.find('dummy', first=True).option.get()
_is_same_opt(ret, conf.option('gc.dummy').option.get())
#
ret = list(conf.option.find('float'))
assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.option('gc.float').option.get())
_is_same_opt(ret[1].option.get(), conf.option('float').option.get())
#
_is_same_opt(conf.option.find('bool', first=True).option.get(), conf.option('gc.gc2.bool').option.get())
_is_same_opt(conf.option.find('bool', value=True, first=True).option.get(), conf.option('bool').option.get())
_is_same_opt(conf.option.find('dummy', first=True).option.get(), conf.option('gc.dummy').option.get())
_is_same_opt(conf.option.find('float', first=True).option.get(), conf.option('gc.float').option.get())
#FIXME cannot find an option without name
#ret = conf.find(bytype=ChoiceOption)
#assert len(ret) == 2
#_is_same_opt(ret[0], conf.unwrap_from_path('gc.name'))
#_is_same_opt(ret[1], conf.unwrap_from_path('objspace'))
#
#_is_same_opt(conf.find_first(bytype=ChoiceOption), conf.unwrap_from_path('gc.name'))
#ret = conf.find(byvalue='ref')
#assert len(ret) == 1
#_is_same_opt(ret[0], conf.unwrap_from_path('gc.name'))
#_is_same_opt(conf.find_first(byvalue='ref'), conf.unwrap_from_path('gc.name'))
#
ret = list(conf.option.find('prop'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get())
#
ret = list(conf.option.find('prop', value=None))
assert len(ret) == 1
ret = list(conf.option.find('prop'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get())
#
conf.property.read_write()
raises(AttributeError, "assert conf.option.find('prop').option.get()")
ret = list(conf.unrestraint.option.find(name='prop'))
assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(ret[1].option.get(), conf.forcepermissive.option('gc.prop').option.get())
#
ret = list(conf.forcepermissive.option.find('prop'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.forcepermissive.option('gc.prop').option.get())
#
_is_same_opt(conf.forcepermissive.option.find('prop', first=True).option.get(), conf.forcepermissive.option('gc.prop').option.get())
# combinaison of filters
ret = list(conf.unrestraint.option.find('prop', type=BoolOption))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(conf.unrestraint.option.find('prop', type=BoolOption, first=True).option.get(), conf.unrestraint.option('gc.gc2.prop').option.get())
#
ret = list(conf.option.find('dummy', value=False))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get())
#
_is_same_opt(conf.option.find('dummy', value=False, first=True).option.get(), conf.option('gc.dummy').option.get())
#subconfig
ret = list(conf.option('gc').find('dummy'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.dummy').option.get())
#
ret = list(conf.option('gc').find('float'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.float').option.get())
#
ret = list(conf.option('gc').find('bool'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.gc2.bool').option.get())
_is_same_opt(conf.option('gc').find('bool', value=False, first=True).option.get(), conf.option('gc.gc2.bool').option.get())
#
raises(AttributeError, "assert conf.option('gc').find('bool', value=True, first=True).option.get()")
#
raises(AttributeError, "conf.option('gc').find('wantref').option.get()")
#
ret = list(conf.unrestraint.option('gc').find('prop'))
assert len(ret) == 2
_is_same_opt(ret[0].option.get(), conf.unrestraint.option('gc.gc2.prop').option.get())
_is_same_opt(ret[1].option.get(), conf.forcepermissive.option('gc.prop').option.get())
#
conf.property.read_only()
ret = list(conf.option('gc').find('prop'))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), conf.option('gc.prop').option.get())
# not OptionDescription
raises(AttributeError, "conf.option.find('gc', first=True)")
raises(AttributeError, "conf.option.find('gc2', first=True)")
def test_find_multi():
b = BoolOption('bool', '', multi=True)
o = OptionDescription('od', '', [b])
conf = Config(o)
#
raises(AttributeError, "list(conf.option.find('bool', value=True))")
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))")
conf.option('bool').value.set([False])
raises(AttributeError, "list(conf.option.find('bool', value=True))")
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))")
conf.option('bool').value.set([False, False])
raises(AttributeError, "list(conf.option.find('bool', value=True))")
raises(AttributeError, "list(conf.option.find('bool', value=True, first=True))")
conf.option('bool').value.set([False, False, True])
ret = list(conf.option.find('bool', value=True))
assert len(ret) == 1
_is_same_opt(ret[0].option.get(), b)
_is_same_opt(conf.option.find('bool', value=True, first=True).option.get(), b)
def test_does_not_find_in_config():
descr = make_description()
conf = Config(descr)
raises(AttributeError, "list(conf.option.find('IDontExist'))")
def test_filename():
a = FilenameOption('a', '')
o = OptionDescription('o', '', [a])
cfg = Config(o)
cfg.option('a').value.set('/')
cfg.option('a').value.set('/tmp')
cfg.option('a').value.set('/tmp/')
cfg.option('a').value.set('/tmp/text.txt')
cfg.option('a').value.set('tmp')
cfg.option('a').value.set('tmp/')
cfg.option('a').value.set('tmp/text.txt')
raises(ValueError, "cfg.option('a').value.set('/tmp/with space.txt')")
raises(ValueError, "cfg.option('a').value.set('/tmp/with$.txt')")
def test_invalid_option():
ChoiceOption('a', '', ('1', '2'))
raises(TypeError, "ChoiceOption('a', '', [1, 2])")
raises(TypeError, "ChoiceOption('a', '', 1)")
raises(ValueError, "ChoiceOption('a', '', (1,), 3)")
FloatOption('a', '')
raises(ValueError, "FloatOption('a', '', 'string')")
UnicodeOption('a', '')
raises(ValueError, "UnicodeOption('a', '', 1)")
u = UnicodeOption('a', '')
SymLinkOption('a', u)
raises(ValueError, "SymLinkOption('a', 'string')")
IPOption('a', '')
raises(ValueError, "IPOption('a', '', 1)")
raises(ValueError, "IPOption('a', '', 'string')")
PortOption('a', '')
raises(ValueError, "PortOption('a', '', 'string')")
raises(ValueError, "PortOption('a', '', '11:12:13', allow_range=True)")
raises(ValueError, "PortOption('a', '', 11111111111111111111)")
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=False)")
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=True, allow_registred=False, allow_private=True)")
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=False, allow_private=True)")
raises(ValueError, "PortOption('a', '', allow_zero=True, allow_wellknown=False, allow_registred=True, allow_private=True)")
raises(ValueError, "PortOption('a', '', allow_zero=False, allow_wellknown=False, allow_registred=False, allow_private=False)")
NetworkOption('a', '')
raises(ValueError, "NetworkOption('a', '', 'string')")
NetmaskOption('a', '')
raises(ValueError, "NetmaskOption('a', '', 'string')")
BroadcastOption('a', '')
raises(ValueError, "BroadcastOption('a', '', 'string')")
DomainnameOption('a', '')
raises(ValueError, "DomainnameOption('a', '', 'string')")
raises(ValueError, "DomainnameOption('a', '', type_='string')")
raises(ValueError, "DomainnameOption('a', '', allow_ip='string')")
raises(ValueError, "DomainnameOption('a', '', allow_without_dot='string')")
raises(ValueError, "DomainnameOption('a', '', 1)")
#
ChoiceOption('a', '', (1,), multi=True, default_multi=1)
raises(ValueError, "ChoiceOption('a', '', (1,), default_multi=1)")
raises(ValueError, "ChoiceOption('a', '', (1,), multi=True, default=[1,], default_multi=2)")
raises(ValueError, "FloatOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "UnicodeOption('a', '', multi=True, default_multi=1)")
raises(ValueError, "IPOption('a', '', multi=True, default_multi=1)")
raises(ValueError, "IPOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "PortOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "PortOption('a', '', multi=True, default_multi='11:12:13', allow_range=True)")
raises(ValueError, "PortOption('a', '', multi=True, default_multi=11111111111111111111)")
raises(ValueError, "NetworkOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "NetmaskOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "BroadcastOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "DomainnameOption('a', '', multi=True, default_multi='string')")
raises(ValueError, "DomainnameOption('a', '', multi=True, default_multi=1)")
def test_help():
stro = StrOption('s', '', multi=True)
od1 = OptionDescription('o', '', [stro])
od2 = OptionDescription('o', '', [od1])
cfg = Config(od2)
cfg.help(_display=False)
cfg.config.help(_display=False)
cfg.option.help(_display=False)
#FIXMEcfg.option('o').help(_display=False)
cfg.option('o.s').help(_display=False)
def test_config_reset():
descr = make_description()
c = Config(descr)
c.owner.set('test')
assert c.owner.get() == 'test'
assert not c.option('gc.gc2.bool').value.get()
assert not c.option('boolop').property.get()
assert not c.option('boolop').permissive.get()
assert not c.option('wantref').information.get('info', None)
#
c.option('gc.gc2.bool').value.set(True)
c.option('boolop').property.add('test')
c.option('float').permissive.set(frozenset(['test']))
c.option('wantref').information.set('info', 'info')
assert c.option('gc.gc2.bool').value.get()
assert c.option('boolop').property.get()
assert c.option('float').permissive.get()
assert c.option('wantref').information.get('info', None)
#
assert c.owner.get() == 'test'
c.config.reset()
assert c.owner.get() == 'test'
assert not c.option('gc.gc2.bool').value.get()
assert not c.option('boolop').property.get()
assert not c.option('float').permissive.get()
assert not c.option('wantref').information.get('info', None)

View File

@ -1,176 +0,0 @@
from .autopath import do_autopath
do_autopath()
import warnings, sys
from py.test import raises
from tiramisu import Config
from tiramisu.option import DomainnameOption, EmailOption, URLOption, OptionDescription
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__)
def test_domainname():
d = DomainnameOption('d', '')
f = DomainnameOption('f', '', allow_without_dot=True)
g = DomainnameOption('g', '', allow_ip=True)
od = OptionDescription('a', '', [d, f, g])
cfg = Config(od)
cfg.property.read_write()
cfg.option('d').value.set('toto.com')
raises(ValueError, "cfg.option('d').value.set('toto')")
cfg.option('d').value.set('toto3.com')
raises(ValueError, "cfg.option('d').value.set('toto_super.com')")
cfg.option('d').value.set('toto-.com')
raises(ValueError, "cfg.option('d').value.set('toto..com')")
#
cfg.option('f').value.set('toto.com')
cfg.option('f').value.set('toto')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')")
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
raises(ValueError, "cfg.option('d').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowien')")
cfg.option('f').value.set('d')
cfg.option('f').value.set('d.t')
#
raises(ValueError, "cfg.option('f').value.set('192.168.1.1')")
cfg.option('g').value.set('toto.com')
cfg.option('g').value.set('192.168.1.0')
cfg.option('g').value.set('192.168.1.29')
def test_domainname_upper():
d = DomainnameOption('d', '')
od = OptionDescription('a', '', [d])
cfg = Config(od)
cfg.property.read_write()
cfg.option('d').value.set('toto.com')
msg = _('some characters are uppercase')
has_error = False
try:
cfg.option('d').value.set('TOTO.COM')
except ValueError as err:
assert msg in str(err)
has_error = True
assert has_error is True
has_error = False
try:
cfg.option('d').value.set('toTo.com')
except ValueError as err:
assert msg in str(err)
has_error = True
assert has_error is True
def test_domainname_warning():
d = DomainnameOption('d', '', warnings_only=True)
f = DomainnameOption('f', '', allow_without_dot=True, warnings_only=True)
g = DomainnameOption('g', '', allow_ip=True, warnings_only=True)
od = OptionDescription('a', '', [d, f, g])
warnings.simplefilter("always", ValueWarning)
cfg = Config(od)
cfg.property.read_write()
cfg.option('d').value.set('toto.com')
raises(ValueError, "cfg.option('d').value.set('toto')")
cfg.option('d').value.set('toto3.com')
with warnings.catch_warnings(record=True) as w:
cfg.option('d').value.set('toto_super.com')
assert len(w) == 1
with warnings.catch_warnings(record=True) as w:
cfg.option('d').value.set('toto-.com')
assert len(w) == 0
raises(ValueError, "cfg.option('d').value.set('toto..com')")
#
cfg.option('f').value.set('toto.com')
cfg.option('f').value.set('toto')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea')
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamean')")
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nd')
cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainnamea.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnameto.olongthathavemorethanmaximumsizeforatruedomainnameanditsnoteas.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie')
raises(ValueError, "cfg.option('f').value.set('domainnametoolongthathavemorethanmaximumsizeforatruedomainname.nditsnoteasytogeneratesolongdomainnamewithoutrepeatdomainnamet.olongthathavemorethanmaximumsizeforatruedomainnameanditsnotea.ytogeneratesolongdomainnamewithoutrepeatbutimnotabletodoitnowie.xxxx')")
cfg.option('f').value.set('d')
cfg.option('f').value.set('d.t')
#
raises(ValueError, "cfg.option('f').value.set('192.168.1.1')")
cfg.option('g').value.set('toto.com')
cfg.option('g').value.set('192.168.1.0')
cfg.option('g').value.set('192.168.1.29')
def test_special_domain_name():
"""domain name option that starts with a number or not
"""
d = DomainnameOption('d', '')
e = DomainnameOption('e', '', type_='netbios')
od = OptionDescription('a', '', [d, e])
cfg = Config(od)
cfg.property.read_write()
cfg.option('d').value.set('1toto.com')
cfg.option('d').value.set('123toto.com')
cfg.option('e').value.set('toto')
cfg.option('e').value.set('1toto')
def test_domainname_netbios():
d = DomainnameOption('d', '', type_='netbios')
e = DomainnameOption('e', '', "toto", type_='netbios')
od = OptionDescription('a', '', [d, e])
cfg = Config(od)
cfg.property.read_write()
raises(ValueError, "cfg.option('d').value.set('toto.com')")
cfg.option('d').value.set('toto')
raises(ValueError, "cfg.option('d').value.set('domainnametoolong')")
def test_domainname_hostname():
d = DomainnameOption('d', '', type_='hostname')
e = DomainnameOption('e', '', "toto", type_='hostname')
od = OptionDescription('a', '', [d, e])
cfg = Config(od)
cfg.property.read_write()
raises(ValueError, "cfg.option('d').value.set('toto.com')")
cfg.option('d').value.set('toto')
cfg.option('d').value.set('domainnametoolong')
def test_email():
e = EmailOption('e', '')
od = OptionDescription('a', '', [e])
cfg = Config(od)
cfg.property.read_write()
cfg.option('e').value.set('foo-bar.baz@example.com')
cfg.option('e').value.set('root@foo.com')
cfg.option('e').value.set('root@domain')
raises(ValueError, "cfg.option('e').value.set(1)")
raises(ValueError, "cfg.option('e').value.set('root')")
raises(ValueError, "cfg.option('e').value.set('root[]@domain')")
def test_url():
u = URLOption('u', '')
od = OptionDescription('a', '', [u])
cfg = Config(od)
cfg.property.read_write()
cfg.option('u').value.set('http://foo.com')
cfg.option('u').value.set('https://foo.com')
cfg.option('u').value.set('https://foo.com/')
raises(ValueError, "cfg.option('u').value.set(1)")
raises(ValueError, "cfg.option('u').value.set('ftp://foo.com')")
raises(ValueError, "cfg.option('u').value.set('foo.com')")
raises(ValueError, "cfg.option('u').value.set(':/foo.com')")
raises(ValueError, "cfg.option('u').value.set('foo.com/http://')")
cfg.option('u').value.set('https://foo.com/index.html')
cfg.option('u').value.set('https://foo.com/index.html?var=value&var2=val2')
raises(ValueError, "cfg.option('u').value.set('https://foo.com/index\\n.html')")
cfg.option('u').value.set('https://foo.com:8443')
cfg.option('u').value.set('https://foo.com:8443/')
cfg.option('u').value.set('https://foo.com:8443/index.html')
raises(ValueError, "cfg.option('u').value.set('https://foo.com:84438989')")
cfg.option('u').value.set('https://foo.com:8443/INDEX')
raises(ValueError, "cfg.option('u').value.set('https://FOO.COM:8443')")

View File

@ -1,280 +0,0 @@
from .autopath import do_autopath
do_autopath()
import warnings
from py.test import raises
from tiramisu import Config, IPOption, NetworkOption, NetmaskOption, \
PortOption, BroadcastOption, OptionDescription
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__)
def test_ip():
a = IPOption('a', '')
b = IPOption('b', '', private_only=True)
d = IPOption('d', '', warnings_only=True, private_only=True)
warnings.simplefilter("always", ValueWarning)
od = OptionDescription('od', '', [a, b, d])
config = Config(od)
config.option('a').value.set('192.168.1.1')
config.option('a').value.set('192.168.1.0')
config.option('a').value.set('88.88.88.88')
config.option('a').value.set('0.0.0.0')
raises(ValueError, "config.option('a').value.set('255.255.255.0')")
config.option('b').value.set('192.168.1.1')
config.option('b').value.set('192.168.1.0')
raises(ValueError, "config.option('b').value.set('88.88.88.88')")
config.option('b').value.set('0.0.0.0')
raises(ValueError, "config.option('b').value.set('255.255.255.0')")
raises(ValueError, "config.option('a').value.set('333.0.1.20')")
raises(ValueError, "IPOption('a', 'ip', default='192.000.023.01')")
with warnings.catch_warnings(record=True) as w:
config.option('d').value.set('88.88.88.88')
assert len(w) == 1
def test_ip_cidr():
b = IPOption('b', '', private_only=True, cidr=True)
c = IPOption('c', '', private_only=True)
warnings.simplefilter("always", ValueWarning)
od = OptionDescription('od', '', [b, c])
config = Config(od)
raises(ValueError, "config.option('b').value.set('192.168.1.1')")
config.option('b').value.set('192.168.1.1/24')
raises(ValueError, "config.option('b').value.set('192.168.1.1/32')")
#
config.option('c').value.set('192.168.1.1')
raises(ValueError, "config.option('c').value.set('192.168.1.1/24')")
raises(ValueError, "config.option('c').value.set('192.168.1.1/32')")
def test_ip_default():
a = IPOption('a', '', '88.88.88.88')
od = OptionDescription('od', '', [a])
c = Config(od)
c.option('a').value.get() == '88.88.88.88'
def test_ip_reserved():
a = IPOption('a', '')
b = IPOption('b', '', allow_reserved=True)
c = IPOption('c', '', warnings_only=True)
od = OptionDescription('od', '', [a, b, c])
warnings.simplefilter("always", ValueWarning)
cfg = Config(od)
raises(ValueError, "cfg.option('a').value.set('240.94.1.1')")
cfg.option('b').value.set('240.94.1.1')
with warnings.catch_warnings(record=True) as w:
cfg.option('c').value.set('240.94.1.1')
assert len(w) == 1
def test_network():
a = NetworkOption('a', '')
b = NetworkOption('b', '', warnings_only=True)
od = OptionDescription('od', '', [a, b])
warnings.simplefilter("always", ValueWarning)
cfg = Config(od)
cfg.option('a').value.set('192.168.1.1')
cfg.option('a').value.set('192.168.1.0')
cfg.option('a').value.set('88.88.88.88')
cfg.option('a').value.set('0.0.0.0')
raises(ValueError, "cfg.option('a').value.set(1)")
raises(ValueError, "cfg.option('a').value.set('1.1.1.1.1')")
raises(ValueError, "cfg.option('a').value.set('255.255.255.0')")
raises(ValueError, "cfg.option('a').value.set('192.168.001.0')")
raises(ValueError, "cfg.option('a').value.set('333.168.1.1')")
with warnings.catch_warnings(record=True) as w:
cfg.option('b').value.set('255.255.255.0')
assert len(w) == 1
def test_network_cidr():
a = NetworkOption('a', '', cidr=True)
od = OptionDescription('od', '', [a])
cfg = Config(od)
cfg.option('a').value.set('192.168.1.1/32')
cfg.option('a').value.set('192.168.1.0/24')
cfg.option('a').value.set('88.88.88.88/32')
cfg.option('a').value.set('0.0.0.0/0')
raises(ValueError, "cfg.option('a').value.set('192.168.1.1')")
raises(ValueError, "cfg.option('a').value.set('192.168.1.1/24')")
raises(ValueError, "cfg.option('a').value.set('2001:db00::0/24')")
def test_network_invalid():
raises(ValueError, "NetworkOption('a', '', default='toto')")
def test_netmask():
a = NetmaskOption('a', '')
od = OptionDescription('od', '', [a])
cfg = Config(od)
raises(ValueError, "cfg.option('a').value.set('192.168.1.1.1')")
raises(ValueError, "cfg.option('a').value.set('192.168.1.1')")
raises(ValueError, "cfg.option('a').value.set('192.168.1.0')")
raises(ValueError, "cfg.option('a').value.set('88.88.88.88')")
raises(ValueError, "cfg.option('a').value.set('255.255.255.000')")
raises(ValueError, "cfg.option('a').value.set(2)")
cfg.option('a').value.set('0.0.0.0')
cfg.option('a').value.set('255.255.255.0')
def test_broadcast():
a = BroadcastOption('a', '')
od = OptionDescription('od', '', [a])
cfg = Config(od)
raises(ValueError, "cfg.option('a').value.set('192.168.1.255.1')")
raises(ValueError, "cfg.option('a').value.set('192.168.001.255')")
raises(ValueError, "cfg.option('a').value.set('192.168.0.300')")
raises(ValueError, "cfg.option('a').value.set(1)")
raises(ValueError, "cfg.option('a').value.set(2)")
raises(ValueError, "cfg.option('a').value.set('2001:db8::1')")
cfg.option('a').value.set('0.0.0.0')
cfg.option('a').value.set('255.255.255.0')
def test_port():
a = PortOption('a', '')
b = PortOption('b', '', allow_zero=True)
c = PortOption('c', '', allow_zero=True, allow_registred=False)
d = PortOption('d', '', allow_zero=True, allow_wellknown=False, allow_registred=False)
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 = Config(od)
raises(ValueError, "cfg.option('a').value.set('0')")
cfg.option('a').value.set('1')
cfg.option('a').value.set('1023')
cfg.option('a').value.set('1024')
cfg.option('a').value.set('49151')
raises(ValueError, "cfg.option('a').value.set('49152')")
raises(ValueError, "cfg.option('a').value.set('65535')")
raises(ValueError, "cfg.option('a').value.set('65536')")
cfg.option('b').value.set('0')
cfg.option('b').value.set('1')
cfg.option('b').value.set('1023')
cfg.option('b').value.set('1024')
cfg.option('b').value.set('49151')
raises(ValueError, "cfg.option('b').value.set('49152')")
raises(ValueError, "cfg.option('b').value.set('65535')")
raises(ValueError, "cfg.option('b').value.set('65536')")
cfg.option('c').value.set('0')
cfg.option('c').value.set('1')
cfg.option('c').value.set('1023')
raises(ValueError, "cfg.option('c').value.set('1024')")
raises(ValueError, "cfg.option('c').value.set('49151')")
raises(ValueError, "cfg.option('c').value.set('49152')")
raises(ValueError, "cfg.option('c').value.set('65535')")
raises(ValueError, "cfg.option('c').value.set('65536')")
cfg.option('d').value.set('0')
raises(ValueError, "cfg.option('d').value.set('1')")
raises(ValueError, "cfg.option('d').value.set('1023')")
raises(ValueError, "cfg.option('d').value.set('1024')")
raises(ValueError, "cfg.option('d').value.set('49151')")
raises(ValueError, "cfg.option('d').value.set('49152')")
raises(ValueError, "cfg.option('d').value.set('65535')")
raises(ValueError, "cfg.option('d').value.set('65536')")
cfg.option('e').value.set('0')
cfg.option('e').value.set('1')
cfg.option('e').value.set('1023')
cfg.option('e').value.set('1024')
cfg.option('e').value.set('49151')
cfg.option('e').value.set('49152')
cfg.option('e').value.set('65535')
raises(ValueError, "cfg.option('f').value.set('0')")
cfg.option('f').value.set('1')
cfg.option('f').value.set('1023')
cfg.option('f').value.set('1024')
cfg.option('f').value.set('49151')
cfg.option('f').value.set('49152')
cfg.option('f').value.set('65535')
raises(ValueError, "cfg.option('f').value.set('65536')")
def test_port_range():
a = PortOption('a', '', allow_range=True)
b = PortOption('b', '', allow_range=True, allow_zero=True)
c = PortOption('c', '', allow_range=True, allow_zero=True, allow_registred=False)
d = PortOption('d', '', allow_range=True, allow_zero=True, allow_wellknown=False, allow_registred=False)
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 = Config(od)
raises(ValueError, "cfg.option('a').value.set('0')")
cfg.option('a').value.set('1')
cfg.option('a').value.set('1023')
cfg.option('a').value.set('1024')
cfg.option('a').value.set('49151')
raises(ValueError, "cfg.option('a').value.set('49152')")
raises(ValueError, "cfg.option('a').value.set('65535')")
raises(ValueError, "cfg.option('a').value.set('65536')")
cfg.option('a').value.set('1:49151')
raises(ValueError, "cfg.option('a').value.set('0:49151')")
raises(ValueError, "cfg.option('a').value.set('1:49152')")
cfg.option('b').value.set('0')
cfg.option('b').value.set('1')
cfg.option('b').value.set('1023')
cfg.option('b').value.set('1024')
cfg.option('b').value.set('49151')
raises(ValueError, "cfg.option('b').value.set('49152')")
raises(ValueError, "cfg.option('b').value.set('65535')")
raises(ValueError, "cfg.option('b').value.set('65536')")
cfg.option('b').value.set('0:49151')
raises(ValueError, "cfg.option('b').value.set('0:49152')")
cfg.option('c').value.set('0')
cfg.option('c').value.set('1')
cfg.option('c').value.set('1023')
raises(ValueError, "cfg.option('c').value.set('1024')")
raises(ValueError, "cfg.option('c').value.set('49151')")
raises(ValueError, "cfg.option('c').value.set('49152')")
raises(ValueError, "cfg.option('c').value.set('65535')")
raises(ValueError, "cfg.option('c').value.set('65536')")
cfg.option('c').value.set('0:1023')
raises(ValueError, "cfg.option('c').value.set('0:1024')")
cfg.option('d').value.set('0')
raises(ValueError, "cfg.option('d').value.set('1')")
raises(ValueError, "cfg.option('d').value.set('1023')")
raises(ValueError, "cfg.option('d').value.set('1024')")
raises(ValueError, "cfg.option('d').value.set('49151')")
raises(ValueError, "cfg.option('d').value.set('49152')")
raises(ValueError, "cfg.option('d').value.set('65535')")
raises(ValueError, "cfg.option('d').value.set('65536')")
raises(ValueError, "cfg.option('d').value.set('0:0')")
raises(ValueError, "cfg.option('d').value.set('0:1')")
cfg.option('e').value.set('0')
cfg.option('e').value.set('1')
cfg.option('e').value.set('1023')
cfg.option('e').value.set('1024')
cfg.option('e').value.set('49151')
cfg.option('e').value.set('49152')
cfg.option('e').value.set('65535')
cfg.option('e').value.set('0:65535')
raises(ValueError, "cfg.option('e').value.set('0:65536')")
raises(ValueError, "cfg.option('f').value.set('0')")
cfg.option('f').value.set('1')
cfg.option('f').value.set('1023')
cfg.option('f').value.set('1024')
cfg.option('f').value.set('49151')
cfg.option('f').value.set('49152')
cfg.option('f').value.set('65535')
raises(ValueError, "cfg.option('f').value.set('65536')")
cfg.option('f').value.set('1:65535')
cfg.option('f').value.set('3:4')
raises(ValueError, "cfg.option('f').value.set('0:65535')")
raises(ValueError, "cfg.option('f').value.set('4:3')")

View File

@ -1,339 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
import weakref
from tiramisu import BoolOption, IntOption, StrOption, IPOption, NetmaskOption, \
SymLinkOption, OptionDescription, DynOptionDescription, submulti, \
Config, GroupConfig, MetaConfig, Params, ParamOption
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
IS_DEREFABLE = True
def funcname(*args, **kwargs):
return value
def test_deref_storage():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_values()._p_)
del(c)
assert w() is None
def test_deref_value():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_values())
del(c)
assert w() is None
def test_deref_setting():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(c._config_bag.context.cfgimpl_get_settings())
del(c)
assert w() is None
def test_deref_config():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(c)
del(c)
assert w() is None
def test_deref_option():
global IS_DEREFABLE
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
w = weakref.ref(b)
del(b)
try:
assert w() is not None
except AssertionError:
IS_DEREFABLE = False
return
del(o)
assert w() is None
def test_deref_optiondescription():
if not IS_DEREFABLE:
return
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
w = weakref.ref(o)
del(b)
assert w() is not None
del(o)
assert w() is None
def test_deref_option_cache():
if not IS_DEREFABLE:
return
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
o._build_cache()
w = weakref.ref(b)
del(b)
assert w() is not None
del(o)
assert w() is None
def test_deref_optiondescription_cache():
if not IS_DEREFABLE:
return
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
o._build_cache()
w = weakref.ref(o)
del(b)
assert w() is not None
del(o)
assert w() is None
def test_deref_option_config():
if not IS_DEREFABLE:
return
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(b)
del(b)
assert w() is not None
del(o)
assert w() is not None
del(c)
assert w() is None
def test_deref_optiondescription_config():
if not IS_DEREFABLE:
return
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o)
w = weakref.ref(o)
del(b)
assert w() is not None
del(o)
assert w() is not None
del(c)
assert w() is None
#def test_deref_groupconfig():
# if not IS_DEREFABLE:
# return
# i1 = IntOption('i1', '')
# od1 = OptionDescription('od1', '', [i1])
# od2 = OptionDescription('od2', '', [od1])
# conf1 = Config(od2, 'conf1')
# conf2 = Config(od2, 'conf2')
# meta = GroupConfig([conf1, conf2])
# w = weakref.ref(conf1)
# del(conf1)
# assert w() is not None
# del(meta)
# assert w() is None
#def test_deref_metaconfig():
# if not IS_DEREFABLE:
# return
# i1 = IntOption('i1', '')
# od1 = OptionDescription('od1', '', [i1])
# od2 = OptionDescription('od2', '', [od1])
# conf1 = Config(od2, 'conf1')
# conf2 = Config(od2, 'conf2')
# meta = MetaConfig([conf1, conf2])
# w = weakref.ref(conf1)
# del(conf1)
# assert w() is not None
# del(meta)
# assert w() is None
def test_deref_consistency():
if not IS_DEREFABLE:
return
a = IPOption('a', '')
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [a, b])
b.impl_add_consistency('ip_netmask', a)
cfg = 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 y() is not None
assert z() is not None
del(a)
del(b)
assert w() is not None
assert x() is not None
assert y() is not None
assert z() is not None
del(od)
assert w() is not None
assert x() is not None
assert y() is not None
assert z() is not None
del(cfg)
assert y() is None
assert z() is None
#assert w() is None
#assert x() is None
def test_deref_validator():
if not IS_DEREFABLE:
return
a = StrOption('a', '', default='yes')
b = StrOption('b', '', validator=funcname, validator_params=Params((ParamOption(a),)), default='val')
od = OptionDescription('root', '', [a, b])
cfg = 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)
assert y() is None
assert z() is None
#assert w() is None
#assert x() is None
def test_deref_callback():
if not IS_DEREFABLE:
return
a = StrOption('a', "", 'val')
b = StrOption('b', "", callback=funcname, callback_params=Params((ParamOption(a),)))
od = OptionDescription('root', '', [a, b])
cfg = 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)
assert y() is None
assert z() is None
#assert w() is None
#assert x() is None
def test_deref_symlink():
if not IS_DEREFABLE:
return
a = BoolOption("a", "", default=False)
b = SymLinkOption("b", a)
od = OptionDescription('root', '', [a, b])
cfg = 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)
#assert w() is None
#assert x() is None
assert y() is None
assert z() is None
def test_deref_dyn():
if not IS_DEREFABLE:
return
a = StrOption('a', '', ['val1', 'val2'], multi=True)
b = StrOption('b', '')
dod = DynOptionDescription('dod', '', [b], callback=funcname, callback_params=Params((ParamOption(a),)))
od = OptionDescription('od', '', [dod, a])
cfg = 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)
#assert w() is None
#assert x() is None
assert y() is None
assert z() is None

View File

@ -1,99 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import groups
from tiramisu import Config, MetaConfig
from tiramisu import ChoiceOption, BoolOption, IntOption, \
StrOption, OptionDescription
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__)
def make_description():
numero_etab = StrOption('numero_etab', "identifiant de l'établissement")
nom_machine = StrOption('nom_machine', "nom de la machine", default="eoleng")
nombre_interfaces = IntOption('nombre_interfaces', "nombre d'interfaces à activer",
default=1)
activer_proxy_client = BoolOption('activer_proxy_client', "utiliser un proxy",
default=False)
mode_conteneur_actif = BoolOption('mode_conteneur_actif', "le serveur est en mode conteneur",
default=False)
mode_conteneur_actif2 = BoolOption('mode_conteneur_actif2', "le serveur est en mode conteneur2",
default=False, properties=('hidden',))
adresse_serveur_ntp = StrOption('serveur_ntp', "adresse serveur ntp", multi=True)
time_zone = ChoiceOption('time_zone', 'fuseau horaire du serveur',
('Paris', 'Londres'), 'Paris')
wantref_option = BoolOption('wantref', 'Test requires', default=False, properties=('force_store_value',))
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé")
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau")
leader = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1 = OptionDescription('interface1', '', [leader])
interface1.impl_set_group_type(groups.family)
general = OptionDescription('general', '', [numero_etab, nom_machine,
nombre_interfaces, activer_proxy_client,
mode_conteneur_actif, mode_conteneur_actif2,
adresse_serveur_ntp, time_zone, wantref_option])
general.impl_set_group_type(groups.family)
new = OptionDescription('new', '', [], properties=('hidden',))
new.impl_set_group_type(groups.family)
creole = OptionDescription('creole', 'first tiramisu configuration', [general, interface1, new])
descr = OptionDescription('baseconfig', 'baseconifgdescr', [creole])
return descr
def test_copy():
cfg = Config(make_description())
ncfg = cfg.config.copy()
assert cfg.option('creole.general.numero_etab').value.get() == None
cfg.option('creole.general.numero_etab').value.set('oui')
assert cfg.option('creole.general.numero_etab').value.get() == 'oui'
assert ncfg.option('creole.general.numero_etab').value.get() == None
# _diff_opts(cfg.cfgimpl_get_description(), ncfg.cfgimpl_get_description())
# _diff_conf(cfg, ncfg)
# cfg.creole.general.numero_etab = 'oui'
# raises(AssertionError, "_diff_conf(cfg, ncfg)")
# ncfg.creole.general.numero_etab = 'oui'
# _diff_conf(cfg, ncfg)
def to_tuple(val):
return tuple([tuple(v) for v in val])
def test_copy_force_store_value():
descr = make_description()
conf = Config(descr)
conf2 = Config(descr)
assert to_tuple(conf.value.exportation()) == ((), (), (), ())
assert to_tuple(conf2.value.exportation()) == ((), (), (), ())
#
conf.property.read_write()
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(conf2.value.exportation()) == ((), (), (), ())
#
conf2.property.read_only()
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
#
conf.option('creole.general.wantref').value.set(True)
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (True,), ('user',))
assert to_tuple(conf2.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
def test_copy_force_store_value_metaconfig():
descr = make_description()
meta = MetaConfig([], optiondescription=descr)
conf = meta.config.new(session_id='conf')
assert meta.property.get() == conf.property.get()
assert meta.permissive.get() == conf.permissive.get()
conf.property.read_write()
assert to_tuple(conf.value.exportation()) == (('creole.general.wantref',), (None,), (False,), ('forced',))
assert to_tuple(meta.value.exportation()) == ((), (), (), ())

View File

@ -1,1447 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import groups, owners
from tiramisu import BoolOption, StrOption, ChoiceOption, IPOption, \
NetworkOption, NetmaskOption, IntOption, FloatOption, \
UnicodeOption, PortOption, BroadcastOption, DomainnameOption, \
EmailOption, URLOption, UsernameOption, FilenameOption, SymLinkOption, \
OptionDescription, DynOptionDescription, SynDynOption, submulti, Leadership, \
Config, Params, ParamOption, ParamValue
from tiramisu.error import PropertiesOptionError, ConfigError, ConflictError
from tiramisu.storage import list_sessions
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
raise ValueError('no value')
def return_dynval(value='val', suffix=None):
return value
def return_list2(suffix=None):
return [str(suffix), 'val2']
def return_list(val=None, suffix=None):
if val:
return val
else:
return ['val1', 'val2']
def return_same_list(*args, **kwargs):
return ['val1', 'val1']
def return_wrong_list(*args, **kwargs):
return ['---', ' ']
def return_raise(suffix):
raise Exception('error')
def return_str(*args, **kwargs):
return 'str'
def test_build_dyndescription():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_list)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
assert cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None}
def test_build_dyndescription_raise():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_raise)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
raises(ConfigError, "cfg.value.dict()")
def test_build_dyndescription_not_list():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_str)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
raises(ValueError, "cfg.value.dict()")
def test_subpath_dyndescription():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_list)
od1 = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
assert api.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None}
def test_list_dyndescription():
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
def test_unknown_dyndescription():
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
raises(AttributeError, "api.option('od.dodval3').value.get()")
raises(AttributeError, "api.option('od.dodval1.novalue').value.get()")
raises(AttributeError, "api.option('od.dodval1.stnoval1').value.get()")
def test_getdoc_dyndescription():
st1 = StrOption('st', 'doc1')
dod = DynOptionDescription('dod', 'doc2', [st1], callback=return_list)
od1 = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
assert api.option('od.dodval1.stval1').option.name() == 'stval1'
assert api.option('od.dodval2.stval2').option.name() == 'stval2'
assert api.option('od.dodval1').option.name() == 'dodval1'
assert api.option('od.dodval2').option.name() == 'dodval2'
assert api.option('od.dodval1.stval1').option.doc() == 'doc1'
assert api.option('od.dodval2.stval2').option.doc() == 'doc1'
assert api.option('od.dodval1').option.doc() == 'doc2val1'
assert api.option('od.dodval2').option.doc() == 'doc2val2'
def test_mod_dyndescription():
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
#
api.option('od.dodval1.stval1').value.set('yes')
assert api.option('od.dodval1.stval1').value.get() == 'yes'
assert api.option('od.dodval2.stval2').value.get() is None
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
#
api.option('od.dodval2.stval2').value.set('no')
assert api.option('od.dodval1.stval1').value.get() == 'yes'
assert api.option('od.dodval2.stval2').value.get() == 'no'
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.get() == owner
def test_del_dyndescription():
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
api.option('od.dodval1.stval1').value.set('yes')
assert api.option('od.dodval1.stval1').owner.get() == owner
api.option('od.dodval1.stval1').value.reset()
assert api.option('od.dodval1.stval1').owner.isdefault()
def test_multi_dyndescription():
st = StrOption('st', '', multi=True)
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() == []
assert api.option('od.dodval2.stval2').value.get() == []
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set(['yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
assert api.option('od.dodval2.stval2').value.get() == []
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval2.stval2').value.set(['no'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
assert api.option('od.dodval2.stval2').value.get() == ['no']
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.get() == owner
api.option('od.dodval1.stval1').value.set(['yes', 'yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes', 'yes']
api.option('od.dodval1.stval1').value.set(['yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
def test_prop_dyndescription():
st = StrOption('st', '', properties=('test',))
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert set(api.option('od.dodval1.stval1').property.get()) == set(['test'])
assert set(api.option('od.dodval2.stval2').property.get()) == set(['test'])
api.option('od.dodval2.stval2').property.add('test2')
assert set(api.option('od.dodval1.stval1').property.get()) == set(['test'])
assert set(api.option('od.dodval2.stval2').property.get()) == set(['test', 'test2'])
api.option('od.dodval1.stval1').property.pop('test')
assert set(api.option('od.dodval1.stval1').property.get()) == set([])
#
assert set(api.option('od.dodval1').property.get()) == set([])
assert set(api.option('od.dodval2').property.get()) == set([])
api.option('od.dodval1').property.add('test1')
assert set(api.option('od.dodval1').property.get()) == set(['test1'])
assert set(api.option('od.dodval2').property.get()) == set([])
api.option('od.dodval1').property.pop('test1')
assert set(api.option('od.dodval1').property.get()) == set([])
assert set(api.option('od.dodval2').property.get()) == set([])
def test_prop_dyndescription_force_store_value():
st = StrOption('st', '', properties=('force_store_value',))
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
raises(ConfigError, "Config(od2)")
def test_callback_dyndescription():
st = StrOption('st', '', callback=return_dynval)
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() == 'val'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set('val2')
assert api.option('od.dodval1.stval1').value.get() == 'val2'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.reset()
assert api.option('od.dodval1.stval1').value.get() == 'val'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
def test_callback_list_dyndescription():
st = StrOption('st', '', callback=return_list2, multi=True)
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() == ['val1', 'val2']
assert api.option('od.dodval2.stval2').value.get() == ['val2', 'val2']
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set(['val3', 'val2'])
assert api.option('od.dodval1.stval1').value.get() == ['val3', 'val2']
assert api.option('od.dodval2.stval2').value.get() == ['val2', 'val2']
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
def test_mandatory_dyndescription():
st = StrOption('st', '', properties=('mandatory',))
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.property.read_only()
raises(PropertiesOptionError, "api.option('od.dodval1.stval1').value.get()")
raises(PropertiesOptionError, "api.option('od.dodval2.stval2').value.get()")
api.property.read_write()
api.option('od.dodval1.stval1').value.set('val')
api.property.read_only()
assert api.option('od.dodval1.stval1').value.get() == 'val'
raises(PropertiesOptionError, "api.option('od.dodval2.stval2').value.get()")
api.property.read_write()
api.option('od.dodval1.stval1').value.reset()
api.property.read_only()
raises(PropertiesOptionError, "api.option('od.dodval1.stval1').value.get()")
assert list(api.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2']
def test_build_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_list, callback_params=Params(ParamOption(val1)))
od1 = OptionDescription('od', '', [dod, val1])
cfg = Config(od1)
assert cfg.value.dict() == {'dodval1.stval1': None, 'dodval2.stval2': None, 'val1': ['val1', 'val2']}
def test_subpath_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_list, callback_params=Params(ParamOption(val1)))
od1 = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
assert api.value.dict() == {'od.dodval1.stval1': None, 'od.dodval2.stval2': None, 'od.val1': ['val1', 'val2']}
def test_list_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
raises(AttributeError, "api.option('od.dodval3').value.get()")
def test_mod_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set('yes')
assert api.option('od.dodval1.stval1').value.get() == 'yes'
assert api.option('od.dodval2.stval2').value.get() is None
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval2.stval2').value.set('no')
assert api.option('od.dodval1.stval1').value.get() == 'yes'
assert api.option('od.dodval2.stval2').value.get() == 'no'
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.get() == owner
def test_del_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
api.option('od.dodval1.stval1').value.set('yes')
assert api.option('od.dodval1.stval1').owner.get() == owner
api.option('od.dodval1.stval1').value.reset()
assert api.option('od.dodval1.stval1').owner.isdefault()
def test_multi_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', multi=True)
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() == []
assert api.option('od.dodval2.stval2').value.get() == []
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set(['yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
assert api.option('od.dodval2.stval2').value.get() == []
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval2.stval2').value.set(['no'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
assert api.option('od.dodval2.stval2').value.get() == ['no']
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.get() == owner
api.option('od.dodval1.stval1').value.set(['yes', 'yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes', 'yes']
api.option('od.dodval1.stval1').value.set(['yes'])
assert api.option('od.dodval1.stval1').value.get() == ['yes']
def test_prop_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', properties=('test',))
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert set(api.option('od.dodval1.stval1').property.get()) == set(['test'])
assert set(api.option('od.dodval2.stval2').property.get()) == set(['test'])
api.option('od.dodval2.stval2').property.add('test2')
assert set(api.option('od.dodval1.stval1').property.get()) == set(['test'])
assert set(api.option('od.dodval2.stval2').property.get()) == set(['test', 'test2'])
api.option('od.dodval1.stval1').property.pop('test')
assert set(api.option('od.dodval1.stval1').property.get()) == set([])
assert set(api.option('od.dodval2.stval2').property.get()) == set(['test', 'test2'])
def test_callback_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', callback=return_dynval)
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.dodval1.stval1').value.get() == 'val'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.set('val2')
assert api.option('od.dodval1.stval1').value.get() == 'val2'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.get() == owner
assert api.option('od.dodval2.stval2').owner.isdefault()
api.option('od.dodval1.stval1').value.reset()
assert api.option('od.dodval1.stval1').value.get() == 'val'
assert api.option('od.dodval2.stval2').value.get() == 'val'
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.isdefault()
def test_mandatory_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', properties=('mandatory',))
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.property.read_only()
raises(PropertiesOptionError, "api.option('od.dodval1.stval1').value.get()")
raises(PropertiesOptionError, "api.option('od.dodval2.stval2').value.get()")
api.property.read_write()
api.option('od.dodval1.stval1').value.set('val')
api.property.read_only()
assert api.option('od.dodval1.stval1').value.get() == 'val'
raises(PropertiesOptionError, "api.option('od.dodval2.stval2').value.get()")
api.property.read_write()
api.option('od.dodval1.stval1').value.reset()
api.property.read_only()
raises(PropertiesOptionError, "api.option('od.dodval1.stval1').value.get()")
assert list(api.value.mandatory()) == ['od.dodval1.stval1', 'od.dodval2.stval2']
def test_increase_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', properties=('mandatory',))
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.property.read_write()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
raises(AttributeError, "api.option('od.dodval3.stval3').value.get()")
api.option('od.val1').value.set(['val1', 'val2', 'val3'])
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
assert api.option('od.dodval3.stval3').value.get() is None
def test_decrease_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', properties=('mandatory',))
dod = DynOptionDescription('dod', '', [st], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
api.property.read_write()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
api.option('od.dodval2.stval2').value.set('yes')
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() == 'yes'
assert api.option('od.dodval1.stval1').owner.isdefault()
assert api.option('od.dodval2.stval2').owner.get() == owner
raises(AttributeError, "api.option('od.dodval3').value.get()")
api.option('od.val1').value.set(['val1'])
assert api.option('od.dodval1.stval1').value.get() is None
raises(AttributeError, "api.option('od.dodval2').value.get()")
raises(AttributeError, "api.option('od.dodval3').value.get()")
assert api.option('od.dodval1.stval1').owner.isdefault()
raises(AttributeError, "api.option('od.dodval2.stval2').owner.get()")
raises(AttributeError, "api.option('od.dodval2.stval2').value.get()")
def test_dyndescription_root():
boolean = BoolOption('boolean', '', True)
st1 = StrOption('st', '', requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
dod = DynOptionDescription('dod', '', [boolean, st1], callback=return_list)
raises(ConfigError, "Config(dod)")
def test_requires_dyndescription():
boolean = BoolOption('boolean', '', True)
st1 = StrOption('st', '', requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
dod = DynOptionDescription('dod', '', [st1], callback=return_list)
od1 = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od1, boolean])
api = Config(od2)
api.property.read_write()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
#
api.option('boolean').value.set(False)
props = []
try:
api.option('od.dodval1.stval1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
props = []
try:
api.option('od.dodval2.stval2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
api.option('boolean').value.set(True)
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
#transitive
api.option('boolean').property.add('disabled')
props = []
try:
api.option('od.dodval1.stval1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
props = []
try:
api.option('od.dodval2.stval2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_dyndescription_boolean():
boolean1 = BoolOption('boolean1', '', True)
boolean = BoolOption('boolean', '', True, requires=[{'option': boolean1,
'expected': False,
'action': 'disabled'}])
st = StrOption('st', '', requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od, boolean1, boolean])
cfg = Config(od2)
cfg.property.read_write()
assert cfg.value.dict() == {'boolean1': True,
'boolean': True,
'od.dodval1.stval1': None,
'od.dodval2.stval2': None}
#
cfg.option('boolean').value.set(False)
assert cfg.value.dict() == {'boolean1': True,
'boolean': False}
#
cfg.option('boolean').value.set(True)
assert cfg.value.dict() == {'boolean1': True,
'boolean': True,
'od.dodval1.stval1': None,
'od.dodval2.stval2': None}
#
cfg.option('boolean1').value.set(False)
assert cfg.value.dict() == {'boolean1': False}
def test_requires_dyndescription_in_dyn():
boolean = BoolOption('boolean', '', True)
st = StrOption('st', '', requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
dod = DynOptionDescription('dod', '', [boolean, st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od])
cfg = Config(od2)
cfg.property.read_write()
assert cfg.option('od.dodval1.stval1').value.get() is None
assert cfg.option('od.dodval2.stval2').value.get() is None
#
cfg.option('od.dodval1.booleanval1').value.set(False)
props = []
try:
cfg.option('od.dodval1.stval1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert props == frozenset(['disabled'])
props = []
cfg.option('od.dodval2.stval2').value.get()
#
cfg.option('od.dodval1.booleanval1').value.set(True)
assert cfg.option('od.dodval1.stval1').value.get() is None
assert cfg.option('od.dodval2.stval2').value.get() is None
def test_requires_dyndescription2():
boolean = BoolOption('boolean', '', True)
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_list,
requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
od1 = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od1, boolean])
api = Config(od2)
api.property.read_write()
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
#
api.option('boolean').value.set(False)
props = []
try:
api.option('od.dodval1.stval1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
props = []
try:
api.option('od.dodval2.stval2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
api.option('boolean').value.set(True)
assert api.option('od.dodval1.stval1').value.get() is None
assert api.option('od.dodval2.stval2').value.get() is None
#transitive
api.option('boolean').property.add('disabled')
props = []
try:
api.option('od.dodval1.stval1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
props = []
try:
api.option('od.dodval2.stval2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_validator_dyndescription():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '', validator=return_true, validator_params=Params((ParamValue('yes'),)), default='val')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert api.option('od.dodval1.stval1').value.get() == 'val'
raises(ValueError, "api.option('od.dodval1.stval1').value.set('no')")
api.option('od.dodval1.stval1').value.set('val')
def test_makedict_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.option('od.dodval1.stval1').value.set('yes')
assert api.value.dict() == {'od.val1': ['val1', 'val2'], 'od.dodval1.stval1': 'yes', 'od.dodval2.stval2': None}
assert api.value.dict(flatten=True) == {'val1': ['val1', 'val2'], 'stval1': 'yes', 'stval2': None}
assert api.value.dict(withoption='stval1') == {'od.dodval1.stval1': 'yes'}
assert api.option('od').value.dict(withoption='stval1') == {'dodval1.stval1': 'yes'}
assert api.option('od.dodval1').value.dict(withoption='stval1') == {'stval1': 'yes'}
def test_find_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.option('od.dodval1.stval1').value.set('yes')
assert api.option.find('stval1', first=True).value.get() == "yes"
assert isinstance(api.option.find('stval1', first=True).option.get(), SynDynOption)
#assert api.option.find(bytype=StrOption, type='path') == ['od.dodval1.stval1', 'od.dodval2.stval2', 'od.val1']
#opts = api.option.find(byvalue='yes')
#assert len(opts) == 1
#assert isinstance(opts[0], SynDynOption)
#assert opts[0].impl_getname() == 'stval1'
raises(AttributeError, "list(api.option.find('strnotexists'))")
def test_information_dyndescription_context():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod, val1])
od2 = OptionDescription('od', '', [od])
dod.impl_set_information('testod', 'val1')
st.impl_set_information('testst', 'val2')
api = Config(od2)
api.information.set('testcfgod', 'val3')
assert api.option('od.dodval1').information.get('testod') == 'val1'
assert api.option('od.dodval2').information.get('testod') == 'val1'
assert api.option('od.dodval1.stval1').information.get('testst') == 'val2'
assert api.option('od.dodval2.stval2').information.get('testst') == 'val2'
assert api.information.get('testcfgod') == 'val3'
def test_consistency_dyndescription():
st1 = StrOption('st', '')
st2 = StrOption('st2', '')
dod = DynOptionDescription('dod', '', [st1, st2], callback=return_list)
od1 = OptionDescription('od', '', [dod])
st1.impl_add_consistency('not_equal', st2)
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
api.option('od.dodval1.stval1').value.set('yes')
raises(ValueError, "api.option('od.dodval1.st2val1').value.set('yes')")
api.option('od.dodval2.stval2').value.set('yes')
raises(ValueError, "api.option('od.dodval2.st2val2').value.set('yes')")
raises(ValueError, "api.option('od.dodval1.st2val1').value.set('yes')")
api.option('od.dodval2.stval2').value.reset()
raises(ValueError, "api.option('od.dodval1.st2val1').value.set('yes')")
api.option('od.dodval2.st2val2').value.set('yes')
raises(ValueError, "api.option('od.dodval2.stval2').value.set('yes')")
#
api.option('od.dodval1.stval1').value.reset()
api.option('od.dodval2.st2val2').value.reset()
api.option('od.dodval1.st2val1').value.set('yes')
raises(ValueError, "api.option('od.dodval1.stval1').value.set('yes')")
def test_consistency_dyndescription_default():
st = StrOption('st', '', 'yes')
st2 = StrOption('st2', '')
dod = DynOptionDescription('dod', '', [st, st2], callback=return_list)
od = OptionDescription('od', '', [dod])
st.impl_add_consistency('not_equal', st2)
od2 = OptionDescription('od', '', [od])
api = Config(od2)
raises(ValueError, "api.option('od.dodval1.st2val1').value.set('yes')")
raises(ValueError, "api.option('od.dodval2.st2val2').value.set('yes')")
def test_consistency_dyndescription_default_multi2():
st = StrOption('st', '', ['yes'], multi=True)
st2 = StrOption('st2', '', ['yes'], multi=True)
dod = DynOptionDescription('dod', '', [st, st2], callback=return_list)
dod
raises(ValueError, "st.impl_add_consistency('not_equal', st2)")
def test_consistency_only_one_dyndescription():
st = StrOption('st', '')
st
st2 = StrOption('st2', '')
dod = DynOptionDescription('dod', '', [st2], callback=return_list)
raises(ConfigError, "st.impl_add_consistency('not_equal', st2)")
raises(ConfigError, "st2.impl_add_consistency('not_equal', st)")
def test_consistency_became_dyndescription():
st = StrOption('st', '')
st2 = StrOption('st2', '')
st2.impl_add_consistency('not_equal', st)
od = DynOptionDescription('dod', '', [st2], callback=return_list)
od2 = OptionDescription('od', '', [od, st])
od2
raises(ConfigError, "c = Config(od2)")
def test_consistency_became_dyndescription2():
st = StrOption('st', '')
st2 = StrOption('st2', '')
st.impl_add_consistency('not_equal', st2)
od = DynOptionDescription('dod', '', [st2], callback=return_list)
od2 = OptionDescription('od', '', [od, st])
od2
raises(ConfigError, "c = Config(od2)")
def test_consistency_external_dyndescription():
st = StrOption('st', '')
st1 = StrOption('st1', '')
st2 = StrOption('st2', '')
dod = DynOptionDescription('dod', '', [st1, st2], callback=return_list)
od = OptionDescription('od', '', [dod, st])
od
raises(ConfigError, "st.impl_add_consistency('not_equal', st2)")
def test_consistency_notsame_dyndescription():
st1 = StrOption('st1', '')
st2 = StrOption('st2', '')
dod = DynOptionDescription('dod', '', [st1, st2], callback=return_list)
tst1 = StrOption('tst1', '')
tst2 = StrOption('tst2', '')
tdod = DynOptionDescription('tdod', '', [tst1, tst2], callback=return_list)
od = OptionDescription('od', '', [dod, tdod])
od
raises(ConfigError, "st1.impl_add_consistency('not_equal', tst1)")
def test_all_dyndescription():
st = StrOption('st', '')
ip = IPOption('ip', '')
network = NetworkOption('network', '')
netmask = NetmaskOption('netmask', '')
ch = ChoiceOption('ch', '', ('val1', 'val2', 'val3'))
ch1 = ChoiceOption('ch1', '', return_list)
boo = BoolOption('boo', '')
intr = IntOption('intr', '')
floa = FloatOption('floa', '')
uni = UnicodeOption('uni', '')
port = PortOption('port', '')
broad = BroadcastOption('broad', '')
domain = DomainnameOption('domain', '')
email = EmailOption('email', '')
url = URLOption('url', '')
username = UsernameOption('username', '')
filename = FilenameOption('filename', '')
dod = DynOptionDescription('dod', '', [st, ip, network, netmask, ch, ch1,
boo, intr, floa, uni, port, broad,
domain, email, url, username,
filename], callback=return_list)
od = OptionDescription('od', '', [dod])
api = Config(od)
assert api.option('dodval1.stval1').value.get() is None
assert api.option('dodval1.ipval1').value.get() is None
assert api.option('dodval1.networkval1').value.get() is None
assert api.option('dodval1.netmaskval1').value.get() is None
assert api.option('dodval1.chval1').value.get() is None
assert api.option('dodval1.ch1val1').value.get() is None
assert api.option('dodval1.booval1').value.get() is None
assert api.option('dodval1.intrval1').value.get() is None
assert api.option('dodval1.floaval1').value.get() is None
assert api.option('dodval1.unival1').value.get() is None
assert api.option('dodval1.portval1').value.get() is None
assert api.option('dodval1.broadval1').value.get() is None
assert api.option('dodval1.domainval1').value.get() is None
assert api.option('dodval1.emailval1').value.get() is None
assert api.option('dodval1.urlval1').value.get() is None
assert api.option('dodval1.usernameval1').value.get() is None
assert api.option('dodval1.filenameval1').value.get() is None
#
api.option('dodval1.stval1').value.set("no")
api.option('dodval1.ipval1').value.set("1.1.1.1")
api.option('dodval1.networkval1').value.set("1.1.1.0")
api.option('dodval1.netmaskval1').value.set("255.255.255.0")
api.option('dodval1.chval1').value.set("val1")
api.option('dodval1.ch1val1').value.set("val2")
api.option('dodval1.booval1').value.set(True)
api.option('dodval1.intrval1').value.set(1)
api.option('dodval1.floaval1').value.set(0.1)
api.option('dodval1.unival1').value.set(u"no")
api.option('dodval1.portval1').value.set('80')
api.option('dodval1.broadval1').value.set("1.1.1.255")
api.option('dodval1.domainval1').value.set("test.com")
api.option('dodval1.emailval1').value.set("test@test.com")
api.option('dodval1.urlval1').value.set("http://test.com")
api.option('dodval1.usernameval1').value.set("user1")
api.option('dodval1.filenameval1').value.set("/tmp")
assert api.option('dodval1.stval1').value.get() == "no"
assert api.option('dodval1.ipval1').value.get() == "1.1.1.1"
assert api.option('dodval1.networkval1').value.get() == "1.1.1.0"
assert api.option('dodval1.netmaskval1').value.get() == "255.255.255.0"
assert api.option('dodval1.chval1').value.get() == "val1"
assert api.option('dodval1.ch1val1').value.get() == "val2"
assert api.option('dodval1.booval1').value.get() is True
assert api.option('dodval1.intrval1').value.get() == 1
assert api.option('dodval1.floaval1').value.get() == 0.1
assert api.option('dodval1.unival1').value.get() == u"no"
assert api.option('dodval1.portval1').value.get() == '80'
assert api.option('dodval1.broadval1').value.get() == "1.1.1.255"
assert api.option('dodval1.domainval1').value.get() == "test.com"
assert api.option('dodval1.emailval1').value.get() == "test@test.com"
assert api.option('dodval1.urlval1').value.get() == "http://test.com"
assert api.option('dodval1.usernameval1').value.get() == "user1"
assert api.option('dodval1.filenameval1').value.get() == "/tmp"
assert api.option('dodval2.stval2').value.get() is None
assert api.option('dodval2.ipval2').value.get() is None
assert api.option('dodval2.networkval2').value.get() is None
assert api.option('dodval2.netmaskval2').value.get() is None
assert api.option('dodval2.chval2').value.get() is None
assert api.option('dodval2.ch1val2').value.get() is None
assert api.option('dodval2.booval2').value.get() is None
assert api.option('dodval2.intrval2').value.get() is None
assert api.option('dodval2.floaval2').value.get() is None
assert api.option('dodval2.unival2').value.get() is None
assert api.option('dodval2.portval2').value.get() is None
assert api.option('dodval2.broadval2').value.get() is None
assert api.option('dodval2.domainval2').value.get() is None
assert api.option('dodval2.emailval2').value.get() is None
assert api.option('dodval2.urlval2').value.get() is None
assert api.option('dodval2.usernameval2').value.get() is None
assert api.option('dodval2.filenameval2').value.get() is None
def test_consistency_ip_netmask_dyndescription():
ipa = IPOption('a', '')
netb = NetmaskOption('b', '')
dod = DynOptionDescription('dod', '', [ipa, netb], callback=return_list)
netb.impl_add_consistency('ip_netmask', ipa)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
cfg.option('dodval1.aval1').value.set('192.168.1.1')
cfg.option('dodval1.bval1').value.set('255.255.255.0')
cfg.option('dodval2.aval2').value.set('192.168.1.2')
cfg.option('dodval2.bval2').value.set('255.255.255.128')
cfg.option('dodval2.bval2').value.set('255.255.255.0')
raises(ValueError, "cfg.option('dodval2.bval2').value.set('255.255.255.255')")
def test_consistency_ip_in_network_dyndescription():
neta = NetworkOption('a', '')
netb = NetmaskOption('b', '')
ipc = IPOption('c', '')
dod = DynOptionDescription('dod', '', [neta, netb, ipc], callback=return_list)
ipc.impl_add_consistency('in_network', neta, netb)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
cfg.option('dodval1.aval1').value.set('192.168.1.0')
cfg.option('dodval1.bval1').value.set('255.255.255.0')
cfg.option('dodval1.cval1').value.set('192.168.1.1')
def test_leadership_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True)
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []}
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']}
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == None
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st2val1', 0).value.set('no')
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.pop(0)
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
api.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
api.option('od.stval1.st1val1.st2val1', 0).value.reset()
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
api.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
api.option('od.stval1.st1val1.st1val1').value.reset()
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_leadership_default_multi_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, default_multi='no')
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_leadership_dyndescription_param():
val1 = StrOption('val1', '', ['val1', 'val2'], multi=True)
odval = OptionDescription('odval1', '', [val1])
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True)
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [st, odval])
od2 = OptionDescription('od', '', [od])
cfg = Config(od2)
owner = cfg.owner.get()
assert 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 cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert 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 cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no')
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.pop(0)
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st2val1', 0).value.reset()
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
cfg.option('od.stval1.st1val1.st1val1').value.reset()
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
def test_leadership_default_multi_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, default_multi='no')
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def _test_leadership(cfg):
owner = cfg.owner.get()
cfg.option('od.val1.val1').value.set(['val1', 'val2'])
cfg.option('od.val1.val2', 0).value.set('val1')
cfg.option('od.val1.val2', 1).value.set('val2')
assert cfg.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': [], 'od.val1.val1': ['val1', 'val2'], 'od.val1.val2': ['val1', 'val2']}
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert cfg.value.dict() == {'od.stval1.st1val1.st2val1': [None], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes'], 'od.val1.val1': ['val1', 'val2'], 'od.val1.val2': ['val1', 'val2']}
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == None
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('no')
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert cfg.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.pop(0)
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st2val1', 0).value.reset()
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert cfg.option('od.stval1.st1val1.st2val1', 0).owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
#
cfg.option('od.stval1.st1val1.st1val1').value.set(['yes'])
cfg.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
cfg.option('od.stval1.st1val1.st1val1').value.reset()
assert cfg.option('od.stval1.st1val1.st1val1').value.get() == []
assert cfg.option('od.stval2.st1val2.st1val2').value.get() == []
assert cfg.option('od.stval1.st1val1.st1val1').owner.get() == owners.default
assert cfg.option('od.stval2.st1val2.st1val2').owner.get() == owners.default
def test_leadership_dyndescription_param_leader():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True)
odval = Leadership('val1', '', [val1, val2])
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True)
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list, callback_params=Params(ParamOption(val1)))
od = OptionDescription('od', '', [st, odval])
od2 = OptionDescription('od', '', [od])
cfg = Config(od2)
_test_leadership(cfg)
def test_leadership_default_multi_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, default_multi='no')
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_leadership_dyndescription_param_follower():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True)
odval = Leadership('val1', '', [val1, val2])
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True)
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list, callback_params=Params(ParamOption(val2)))
od = OptionDescription('od', '', [st, odval])
od2 = OptionDescription('od', '', [od])
cfg = Config(od2)
_test_leadership(cfg)
def test_leadership_default_multi_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, default_multi='no')
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_leadership_submulti_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=submulti)
stm = Leadership('st1', '', [st1, st2])
std = DynOptionDescription('st', '', [stm], callback=return_list)
od1 = OptionDescription('od', '', [std])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
owner = api.owner.get()
#
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st2val1', 0).value.set(['no'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == ['no']
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_leadership_callback_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, callback=return_dynval, callback_params=Params(kwargs={'value': ParamOption(st1)}))
stm = Leadership('st1', '', [st1, st2])
st1 = DynOptionDescription('st', '', [stm], callback=return_list)
od1 = OptionDescription('od', '', [st1])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
owner = api.owner.get()
assert api.value.dict() == {'od.stval1.st1val1.st2val1': [], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': []}
assert api.option('od.stval1.st1val1.st1val1').value.get() ==[]
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.value.dict() == {'od.stval1.st1val1.st2val1': ['yes'], 'od.stval2.st1val2.st2val2': [], 'od.stval2.st1val2.st1val2': [], 'od.stval1.st1val1.st1val1': ['yes']}
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st2val1', 0).value.set('no')
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'no'
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.pop(0)
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
api.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
api.option('od.stval1.st1val1.st2val1', 0).value.reset()
assert api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
api.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
api.option('od.stval1.st1val1.st1val1').value.reset()
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'yes'
def test_leadership_callback_value_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, callback=return_dynval, callback_params=Params(kwargs={'value': ParamValue('val')}))
stm = Leadership('st1', '', [st1, st2])
st = DynOptionDescription('st', '', [stm], callback=return_list)
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
api.option('od.stval1.st1val1.st2val1', 0).value.set('val')
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val'
def test_leadership_callback_nomulti_dyndescription():
v11 = StrOption('v1', '', "val")
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, callback=return_dynval, callback_params=Params(ParamOption(v11)))
stm = Leadership('st1', '', [st1, st2])
stt = DynOptionDescription('st', '', [stm], callback=return_list)
od1 = OptionDescription('od', '', [stt])
od2 = OptionDescription('od', '', [od1, v11])
api = Config(od2)
assert api.option('od.stval1.st1val1.st1val1').value.get() == []
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.option('od.stval1.st1val1.st1val1').value.get() == ['yes']
assert api.option('od.stval1.st1val1.st2val1', 0).value.get() == 'val'
def test_leadership_callback_samegroup_dyndescription():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True)
st3 = StrOption('st3', "", multi=True, callback=return_dynval, callback_params=Params(ParamOption(st2)))
stm = Leadership('st1', '', [st1, st2, st3])
stt = DynOptionDescription('st', '', [stm], callback=return_list)
od1 = OptionDescription('od', '', [stt])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
owner = api.owner.get()
assert api.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 api.option('od.stval1.st1val1.st1val1').value.get() == []
assert api.option('od.stval2.st1val2.st1val2').value.get() == []
assert api.option('od.stval1.st1val1.st1val1').owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st1val1').value.set(['yes'])
assert api.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 api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.isdefault()
assert api.option('od.stval1.st1val1.st3val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
#
api.option('od.stval1.st1val1.st2val1', 0).value.set('yes')
assert api.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 api.option('od.stval1.st1val1.st1val1').owner.get() == owner
assert api.option('od.stval1.st1val1.st2val1', 0).owner.get() == owner
assert api.option('od.stval1.st1val1.st3val1', 0).owner.isdefault()
assert api.option('od.stval2.st1val2.st1val2').owner.isdefault()
def test_invalid_conflict_dyndescription():
st = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st], callback=return_list)
dodinvalid = StrOption('dodinvalid', '')
dod, dodinvalid
raises(ConflictError, "OptionDescription('od', '', [dod, dodinvalid])")
def test_invalid_subod_dyndescription():
st2 = StrOption('st2', '')
od1 = OptionDescription('od1', '', [st2])
od1
raises(ConfigError, "DynOptionDescription('dod', '', [od1], callback=return_list)")
def test_invalid_subdynod_dyndescription():
st2 = StrOption('st2', '')
od1 = DynOptionDescription('od1', '', [st2], callback=return_list)
od1
raises(ConfigError, "DynOptionDescription('dod', '', [od1], callback=return_list)")
def test_invalid_symlink_dyndescription():
st = StrOption('st', '')
st2 = SymLinkOption('st2', st)
st2
raises(ConfigError, "DynOptionDescription('dod', '', [st, st2], callback=return_list)")
def test_nocallback_dyndescription():
st = StrOption('st', '')
st2 = StrOption('st2', '')
st, st2
raises(ConfigError, "DynOptionDescription('dod', '', [st, st2])")
def test_invalid_samevalue_dyndescription():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_same_list)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
raises(ValueError, "cfg.value.dict()")
def test_invalid_name_dyndescription():
st1 = StrOption('st', '')
dod = DynOptionDescription('dod', '', [st1], callback=return_wrong_list)
od1 = OptionDescription('od', '', [dod])
cfg = Config(od1)
raises(ValueError, "cfg.value.dict()")

View File

@ -1,231 +0,0 @@
# coding: utf-8
"frozen and hidden values"
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import owners, groups
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription, SymLinkOption, Leadership, Config, \
Params, ParamContext, ParamOption, ParamValue
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__)
def compare(calculated, expected):
def convert_list(val):
if isinstance(val, list):
val = tuple(val)
return val
# convert to tuple
for idx in range(len(calculated[0])):
right_idx = expected[0].index(calculated[0][idx])
for typ in range(4):
assert convert_list(calculated[typ][idx]) == expected[typ][right_idx]
#____________________________________________________________
#freeze
def make_description_freeze():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=[True], multi=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False, properties=('force_store_value',),
requires=({'option': booloption, 'expected': True, 'action': 'hidden'},))
wantref2_option = BoolOption('wantref2', 'Test requires', default=False, properties=('force_store_value', 'hidden'))
wantref3_option = BoolOption('wantref3', 'Test requires', default=[False], multi=True, properties=('force_store_value',))
st2 = SymLinkOption('st2', wantref3_option)
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False,
requires=({'option': booloption, 'expected': True, 'action': 'hidden'},))
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiramisu', '', [gcgroup, booloption, objspaceoption,
wantref_option, wantref2_option, wantref3_option, st2, stroption,
wantframework_option,
intoption, boolop])
return descr
def return_val():
return 1
def return_val2(value):
return value
def return_val3(context, value):
return value
def test_freeze_whole_config():
descr = make_description_freeze()
api = Config(descr)
api.property.read_write()
api.property.add('everything_frozen')
assert api.option('gc.dummy').value.get() is False
prop = []
try:
api.option('gc.dummy').value.set(True)
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
assert api.option('gc.dummy').value.get() is False
#
api.property.pop('everything_frozen')
api.option('gc.dummy').value.set(True)
assert api.option('gc.dummy').value.get() is True
#
api.property.add('everything_frozen')
owners.addowner("everythingfrozen2")
prop = []
try:
api.option('gc.dummy').owner.set('everythingfrozen2')
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
def test_freeze_one_option():
"freeze an option "
descr = make_description_freeze()
api = Config(descr)
api.property.read_write()
#freeze only one option
api.option('gc.dummy').property.add('frozen')
assert api.option('gc.dummy').value.get() is False
prop = []
try:
api.option('gc.dummy').value.set(True)
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
def test_frozen_value():
"setattr a frozen value at the config level"
s = StrOption("string", "", default="string")
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.property.read_write()
api.property.add('frozen')
api.option('string').property.add('frozen')
prop = []
try:
api.option('string').value.set('egg')
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
def test_freeze():
"freeze a whole configuration object"
descr = make_description_freeze()
api = Config(descr)
api.property.read_write()
api.property.add('frozen')
api.option('gc.name').property.add('frozen')
prop = []
try:
api.option('gc.name').value.set('framework')
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
def test_freeze_multi():
descr = make_description_freeze()
api = Config(descr)
api.property.read_write()
api.property.add('frozen')
api.option('boolop').property.add('frozen')
prop = []
try:
api.option('boolop').value.set([True])
except PropertiesOptionError as err:
prop = err.proptype
assert 'frozen' in prop
def test_force_store_value():
descr = make_description_freeze()
conf = Config(descr)
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced')))
conf.option('wantref').value.set(True)
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (True, False, (False,)), ('user', 'forced', 'forced')))
conf.option('wantref').value.reset()
compare(conf.value.exportation(), (('wantref', 'wantref2', 'wantref3'), (None, None, None), (False, False, (False,)), ('forced', 'forced', 'forced')))
def test_force_store_value_no_requirement():
booloption = BoolOption('bool', 'Test boolean option', default=True)
try:
BoolOption('wantref', 'Test requires', default=False,
requires=({'option': booloption, 'expected': True, 'action': 'force_store_value'},))
except ValueError:
pass
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])
raises(ConfigError, "conf = Config(descr)")
#def test_force_store_value_leadership():
# b = IntOption('int', 'Test int option', multi=True, properties=('force_store_value',))
# c = StrOption('str', 'Test string option', multi=True)
# descr = Leadership("int", "", [b, c])
# api = Config(descr)
# assert api.value.get() == {'int': ('forced', ())}
def test_force_store_value_leadership_sub():
b = IntOption('int', 'Test int option', multi=True, properties=('force_store_value',))
c = StrOption('str', 'Test string option', multi=True)
descr = Leadership("int", "", [b, c])
odr = OptionDescription('odr', '', [descr])
api = Config(odr)
compare(api.value.exportation(), (('int.int',), (None,), (tuple(),), ('forced',)))
def test_force_store_value_callback():
b = IntOption('int', 'Test int option', properties=('force_store_value',), callback=return_val)
descr = OptionDescription("int", "", [b])
api = Config(descr)
compare(api.value.exportation(), (('int',), (None,), (1,), ('forced',)))
def test_force_store_value_callback_params():
b = IntOption('int', 'Test int option', properties=('force_store_value',), callback=return_val2, callback_params=Params(kwargs={'value': ParamValue(2)}))
descr = OptionDescription("int", "", [b])
api = Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',)))
def test_force_store_value_callback_params_2():
b = IntOption('int', 'Test int option', properties=('force_store_value',), callback=return_val3, callback_params=Params(ParamContext(), {'value': ParamValue(2)}))
descr = OptionDescription("int", "", [b])
api = Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',)))
def test_force_store_value_callback_params_with_opt():
a = IntOption('val1', "", 2)
b = IntOption('int', 'Test int option', properties=('force_store_value',), callback=return_val2, callback_params=Params(kwargs={'value': ParamOption(a)}))
descr = OptionDescription("int", "", [a, b])
api = Config(descr)
compare(api.value.exportation(), (('int',), (None,), (2,), ('forced',)))

View File

@ -1,791 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import groups, owners
from tiramisu import ChoiceOption, BoolOption, IntOption, IPOption, NetmaskOption, \
StrOption, OptionDescription, Leadership, Config
from tiramisu.error import LeadershipError, PropertiesOptionError, APIError, ConfigError
from tiramisu.storage import list_sessions
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):
val = tuple(val)
return val
# convert to tuple
for idx in range(len(calculated[0])):
right_idx = expected[0].index(calculated[0][idx])
for typ in range(4):
assert convert_list(calculated[typ][idx]) == expected[typ][right_idx]
def make_description():
numero_etab = StrOption('numero_etab', "identifiant de l'établissement")
nom_machine = StrOption('nom_machine', "nom de la machine", default="eoleng")
nombre_interfaces = IntOption('nombre_interfaces', "nombre d'interfaces à activer",
default=1)
activer_proxy_client = BoolOption('activer_proxy_client', "utiliser un proxy",
default=False)
mode_conteneur_actif = BoolOption('mode_conteneur_actif', "le serveur est en mode conteneur",
default=False)
mode_conteneur_actif2 = BoolOption('mode_conteneur_actif2', "le serveur est en mode conteneur2",
default=False, properties=('hidden',))
adresse_serveur_ntp = StrOption('serveur_ntp', "adresse serveur ntp", multi=True)
time_zone = ChoiceOption('time_zone', 'fuseau horaire du serveur',
('Paris', 'Londres'), 'Paris')
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé")
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau")
leader = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1 = OptionDescription('interface1', '', [leader])
interface1.impl_set_group_type(groups.family)
general = OptionDescription('general', '', [numero_etab, nom_machine,
nombre_interfaces, activer_proxy_client,
mode_conteneur_actif, mode_conteneur_actif2,
adresse_serveur_ntp, time_zone])
general.impl_set_group_type(groups.family)
new = OptionDescription('new', '', [], properties=('hidden',))
new.impl_set_group_type(groups.family)
creole = OptionDescription('creole', 'first tiramisu configuration', [general, interface1, new])
descr = OptionDescription('baseconfig', 'baseconifgdescr', [creole])
return descr
def test_base_config():
descr = make_description()
api = Config(descr)
api.property.read_write()
assert api.option('creole.general.activer_proxy_client').value.get() is False
assert api.option('creole.general.nom_machine').value.get() == "eoleng"
assert api.option.find('nom_machine', first=True).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 api.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 api.option('creole').value.dict(flatten=True) == result
def test_make_dict_filter():
descr = make_description()
api = Config(descr)
api.property.read_write()
subresult = {'numero_etab': None, 'nombre_interfaces': 1,
'serveur_ntp': [], 'mode_conteneur_actif': False,
'time_zone': 'Paris', 'nom_machine': 'eoleng',
'activer_proxy_client': False}
result = {}
for key, value in subresult.items():
result['general.' + key] = value
assert api.option('creole').value.dict(withoption='numero_etab') == result
raises(AttributeError, "api.option('creole').value.dict(withoption='numero_etab', withvalue='toto')")
assert api.option('creole').value.dict(withoption='numero_etab', withvalue=None) == result
assert api.option('creole.general').value.dict(withoption='numero_etab') == subresult
def test_get_group_type():
descr = make_description()
api = Config(descr)
api.property.read_write()
grp = api.option('creole.general')
assert grp.group_type() == groups.family
assert grp.group_type() == 'family'
assert isinstance(grp.group_type(), groups.GroupType)
def test_iter_on_groups():
descr = make_description()
api = Config(descr)
api.property.read_write()
result = api.option('creole').list('optiondescription',
group_type=groups.family)
group_names = [res.option.name() for res in result]
assert group_names == ['general', 'interface1']
for i in api.option('creole').list('optiondescription',
group_type=groups.family):
#test StopIteration
break
result = api.option('creole').list('option',
group_type=groups.family)
assert list(result) == []
result = api.option('creole.general').list('optiondescription',
group_type=groups.family)
assert list(result) == []
def test_list_recursive():
descr = make_description()
api = Config(descr)
api.property.read_write()
result = api.option('creole').list('all')
group_names = [res.option.name() for res in result]
assert group_names == ['general', 'interface1']
#
result = api.option.list(recursive=True)
group_names = [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(api.option.list(recursive=True, type='optiondescription'))
group_names = [res.option.name() for res in result]
assert group_names == ['general', 'ip_admin_eth0', 'interface1', 'creole']
def test_iter_on_groups_force_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
result = api.forcepermissive.option('creole.general').list()
group_names = [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 = api.option('creole.general').list()
group_names = [res.option.name() for res in result]
ass.remove('mode_conteneur_actif2')
assert group_names == ass
def test_iter_group_on_groups_force_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
result = api.forcepermissive.option('creole').list(type='optiondescription',
group_type=groups.family)
group_names = [res.option.name() for res in result]
assert group_names == ['general', 'interface1', 'new']
def test_iter_on_groups_props():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.option('creole.interface1').property.add('disabled')
result = api.option('creole').list(type='optiondescription',
group_type=groups.family)
group_names = [res.option.name() for res in result]
assert group_names == ['general']
def test_iter_on_empty_group():
api = Config(OptionDescription("name", "descr", []))
api.property.read_write()
result = list(api.option.list(type='optiondescription'))
assert result == []
def test_iter_not_group():
api = Config(OptionDescription("name", "descr", []))
api.property.read_write()
try:
list(api.option.list(type='optiondescription', group_type='family'))
except AssertionError:
pass
else:
raise Exception('must raise')
def test_groups_with_leader():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
assert interface1.impl_get_group_type() == groups.leadership
def test_groups_is_leader():
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, default_multi='value')
interface1 = Leadership('leadership', '', [ip_admin_eth0, netmask_admin_eth0])
var = StrOption('var', "ip réseau autorisé", multi=True)
od2 = OptionDescription('od2', '', [var])
od1 = OptionDescription('od', '', [interface1, od2])
api = Config(od1)
assert not api.option('od2').option.isleadership()
assert api.option('leadership').option.isleadership()
assert not api.option('od2.var').option.isleader()
assert not api.option('od2.var').option.isfollower()
assert api.option('leadership.ip_admin_eth0').option.ismulti()
assert api.option('leadership.netmask_admin_eth0').option.ismulti()
assert not api.option('leadership.ip_admin_eth0').option.issubmulti()
assert not api.option('leadership.netmask_admin_eth0').option.issubmulti()
assert api.option('leadership.ip_admin_eth0').option.isleader()
assert not api.option('leadership.ip_admin_eth0').option.isfollower()
assert not api.option('leadership.netmask_admin_eth0').option.isleader()
assert api.option('leadership.netmask_admin_eth0').option.isfollower()
assert api.option('leadership.netmask_admin_eth0').option.path() == 'leadership.netmask_admin_eth0'
assert api.option('leadership.netmask_admin_eth0').option.defaultmulti() == 'value'
def test_groups_with_leader_in_root():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1
raises(ConfigError, "Config(interface1)")
def test_groups_with_leader_in_config():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
Config(od)
assert interface1.impl_get_group_type() == groups.leadership
def test_groups_with_leader_make_dict():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
api = Config(od)
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': []}
assert api.option('ip_admin_eth0.ip_admin_eth0').value.len() == 0
assert api.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 0
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.len() == 2
assert api.option('ip_admin_eth0.netmask_admin_eth0').value.len() == 2
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['ip1', 'ip2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None]}
def test_groups_with_leader_default_value():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
api = Config(od)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert api.option('ip_admin_eth0.ip_admin_eth0').value.default() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip1', 'ip2'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2']
assert api.option('ip_admin_eth0.ip_admin_eth0').value.default() == []
def test_groups_with_leader_default_value_2():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", ['ip1', 'ip2'], multi=True)
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])
api = Config(od)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip1', 'ip2']
assert api.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2']
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip3', 'ip4'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip3', 'ip4']
assert api.option('ip_admin_eth0.ip_admin_eth0').value.default() == ['ip1', 'ip2']
#
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1']
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('netmask2')
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'netmask2'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.default() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.default() == 'netmask1'
assert api.option('ip_admin_eth0.netmask_admin_eth0').value.default() == ['netmask1', 'netmask1']
def test_groups_with_leader_hidden_in_config():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('hidden',))
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])
api = Config(od)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
assert api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
def test_groups_with_leader_hidden_in_config2():
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, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
api = Config(od)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
assert api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#del
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
api.property.pop('hidden')
assert api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
api.property.add('hidden')
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
api.property.pop('hidden')
assert api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
def test_groups_with_leader_reset_empty():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od_ = OptionDescription('root', '', [interface1])
api = Config(od_)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
raises(LeadershipError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()")
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
def test_groups_with_leader_reset_out_of_range():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od_ = OptionDescription('root', '', [interface1])
api = Config(od_)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
raises(LeadershipError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.reset()")
raises(IndexError, "api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)")
def test_groups_with_leader_hidden_in_config3():
#if leader is hidden, follower are hidden too
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, properties=('hidden',))
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])
api = Config(od)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
assert api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.forcepermissive.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert api.forcepermissive.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
def test_allowed_groups():
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)
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
interface1
raises(ValueError, "interface1.impl_set_group_type('toto')")
def test_values_with_leader_disabled_leader():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145")
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
api.option('ip_admin_eth0.ip_admin_eth0').property.add('disabled')
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('192.168.230.145')")
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", '', [])
raises(ValueError, "Leadership('ip_admin_eth0', '', [subgroup, ip_admin_eth0, netmask_admin_eth0])")
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")
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
#____________________________________________________________
def test_values_with_leader_and_followers():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"])
raises(APIError, "api.option('ip_admin_eth0.netmask_admin_eth0').value.set([None])")
raises(APIError, "api.option('ip_admin_eth0.netmask_admin_eth0').value.pop(0)")
def test_reset_values_with_leader_and_followers():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#reset
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
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'])
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
def test_reset_values_with_leader_and_followers_default():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.146'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None)
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(None)
def test_values_with_leader_and_followers_follower():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
raises(LeadershipError,
"api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')")
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0')
raises(APIError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.pop(1)")
#reset
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145',
'192.168.230.145',
'192.168.230.145'])
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_and_followers_pop():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.146'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0')
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.145', '192.168.230.146']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0'
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.230.146']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
def test_values_with_leader_and_followers_leader():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.0')
raises(LeadershipError, "api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])")
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0'
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_and_followers_leader_pop():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.146"])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.0.0')
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145", "192.168.230.146"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.0.0'
compare(api.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',))))
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
compare(api.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 api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.146"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
api.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"])
api.option('ip_admin_eth0.netmask_admin_eth0', 3).value.set('255.255.0.0')
api.option('ip_admin_eth0.netmask_admin_eth0', 4).value.set('255.255.0.0')
compare(api.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'))))
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(5)
compare(api.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'))))
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(2)
compare(api.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'))))
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(2)
compare(api.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'))))
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(2)
compare(api.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',))))
def test_values_with_leader_owner():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
def test_values_with_leader_disabled():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145")
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
api.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
#delete with value in disabled var
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145")
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
#append with value in disabled var
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set("192.168.230.145")
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", '192.168.230.43'])
def test_multi_non_valid_value():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
maconfig = OptionDescription('toto', '', [ip_admin_eth0])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0').value.set(['a'])
raises(ValueError, "api.option('ip_admin_eth0').value.set([1])")
def test_multi_leader_default_follower():
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", default_multi="255.255.255.0", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
def test_groups_with_leader_get_modified_value():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
compare(api.value.exportation(), ((), (), (), ()))
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
compare(api.value.exportation(), (('ip_admin_eth0.ip_admin_eth0',), (None,), (('192.168.1.1',),), ('user',)))
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255')
compare(api.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',))))
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255')
compare(api.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'))))
def test_groups_with_leader_importation():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.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'))))
api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1', '192.168.1.0']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.255'
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.0'
api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == 'user'
api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == 'user'
api.option('ip_admin_eth0.netmask_admin_eth0', 1).owner.get() == 'user'
def test_wrong_index():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
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('od', '', [interface1])
maconfig = OptionDescription('toto', '', [od1])
api = Config(maconfig)
api.property.read_write()
assert api.option('od.ip_admin_eth0.ip_admin_eth0').option.get()
raises(APIError, "api.option('od.ip_admin_eth0.ip_admin_eth0', 0).option.get()")
assert api.option('od.ip_admin_eth0.netmask_admin_eth0', 0).option.get()
assert api.option('od.ip_admin_eth0').option.get()
raises(APIError, "api.option('od.ip_admin_eth0', 0).option.get()")
assert api.option('od').option.get()
raises(APIError, "api.option('od', 0).option.get()")
def test_without_leader_or_follower():
raises(ValueError, "Leadership('ip_admin_eth0', '', [])")
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0])")
#empty optiondescription is allowed
OptionDescription('ip_admin_eth0', '', [])
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)
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
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")
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
def test_follower_not_same():
ip_admin_eth0 = IPOption('ip_admin_eth0', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth1 = IPOption('ip_admin_eth1', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
netmask_admin_eth1 = NetmaskOption('netmask_admin_eth1', "masque du sous-réseau", multi=True)
netmask_admin_eth1.impl_add_consistency('ip_netmask', ip_admin_eth0)
interface1 = Leadership('interface1', '', [ip_admin_eth1, netmask_admin_eth1])
od1 = OptionDescription('od', '', [interface0, interface1])
maconfig = OptionDescription('toto', '', [od1])
raises(ConfigError, "Config(maconfig)")
def test_follower_not_same_not_equal():
ip_admin_eth0 = IPOption('ip_admin_eth0', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth1 = IPOption('ip_admin_eth1', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
netmask_admin_eth1 = NetmaskOption('netmask_admin_eth1', "masque du sous-réseau", multi=True)
netmask_admin_eth1.impl_add_consistency('not_equal', netmask_admin_eth0)
interface1 = Leadership('interface1', '', [ip_admin_eth1, netmask_admin_eth1])
od1 = OptionDescription('od', '', [interface0, interface1])
maconfig = OptionDescription('toto', '', [od1])
api = Config(maconfig)
api.property.read_write()
def test_follower_force_store_value():
ip_admin_eth0 = IPOption('ip_admin_eth0', "ip réseau autorisé", multi=True, default=['1.1.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "masque du sous-réseau", multi=True, properties=('force_store_value',))
interface0 = Leadership('interface0', '', [ip_admin_eth0, netmask_admin_eth0])
od1 = OptionDescription('od', '', [interface0])
maconfig = OptionDescription('toto', '', [od1])
raises(ConfigError, "Config(maconfig)")

View File

@ -1,629 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.api import TIRAMISU_VERSION
from tiramisu import Config
from tiramisu import IntOption, StrOption, UnicodeOption, OptionDescription, \
SymLinkOption, Leadership, undefined, Params, ParamOption
from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.setting import groups
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():
stro = StrOption('str', '')
subdescr = OptionDescription('sub', '', [stro], properties=('disabled',))
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option',
properties=('mandatory', ))
stroption2 = UnicodeOption('unicode2', 'Test string option',
properties=('mandatory', ))
stroption3 = StrOption('str3', 'Test string option', multi=True,
properties=('mandatory', ))
stroption4 = StrOption('str4', 'Test string option', multi=True,
properties=('mandatory', ), allow_empty_list=True)
descr = OptionDescription('tiram', '', [subdescr, stroption, stroption1, stroption2, stroption3, stroption4])
return descr
def return_value(value):
return value
def make_description2():
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option',
properties=('mandatory', ))
stroption2 = SymLinkOption('unicode2', stroption1)
stroption3 = StrOption('str3', 'Test string option', multi=True,
properties=('mandatory', ))
unicode1 = UnicodeOption('unicode1', 'Test string option', callback=return_value, callback_params=Params(ParamOption(stroption)), properties=('mandatory', ))
descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3, unicode1])
return descr
def make_description_sym():
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option',
properties=('mandatory', ))
stroption2 = SymLinkOption('unicode2', stroption1)
stroption3 = StrOption('str3', 'Test string option', multi=True,
properties=('mandatory', ))
descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3])
return descr
def make_description3():
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option',
properties=('mandatory', ))
stroption2 = SymLinkOption('unicode2', stroption1)
stroption3 = StrOption('str3', 'Test string option', multi=True,
properties=('mandatory', ))
unicode1 = UnicodeOption('unicode1', 'Test string option', callback=return_value, callback_params=Params(ParamOption(stroption)), properties=('mandatory', ))
int1 = IntOption('int1', '', callback=return_value, callback_params=Params(ParamOption(stroption)), properties=('mandatory', ))
descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3, unicode1, int1])
return descr
def test_mandatory_ro():
descr = make_description()
api = Config(descr)
api.property.read_only()
prop = []
try:
api.option('str1').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('str1').value.set('yes')
api.property.read_only()
assert api.option('str1').value.get() == 'yes'
def test_mandatory_ro_dict():
descr = make_description()
api = Config(descr)
api.property.read_only()
prop = []
try:
api.value.dict()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('str1').value.set('yes')
api.option('unicode2').value.set('yes')
api.property.read_only()
try:
api.value.dict()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('str3').value.set(['yes'])
api.property.read_only()
assert api.value.dict() == {'str': 'abc', 'str1': 'yes', 'str3': ['yes'], 'str4': [], 'unicode2': 'yes'}
def test_mandatory_rw():
descr = make_description()
api = Config(descr)
api.property.read_write()
# not mandatory in rw
api.option('str1').value.get()
api.option('str1').value.set('yes')
assert api.option('str1').value.get() == 'yes'
def test_mandatory_default():
descr = make_description()
api = Config(descr)
api.property.read_only()
#not mandatory in rw
api.option('str').value.get()
api.property.read_write()
api.option('str').value.set('yes')
api.property.read_only()
api.option('str').value.get()
api.property.read_write()
api.option('str').value.set(None)
api.property.read_only()
prop = []
try:
api.option('str').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_delete():
descr = make_description()
api = Config(descr)
api.property.read_only()
api.option('str').value.get()
try:
api.option('str1').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('str1').value.set('yes')
api.property.read_only()
assert api.option('str1').value.get() == 'yes'
api.property.pop('everything_frozen')
prop = []
try:
api.option('str1').value.reset()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.option('str').value.reset()
assert api.option('str1').value.get() == 'yes'
#valeur vide : None, '', u'', ...
def test_mandatory_none():
descr = make_description()
api = Config(descr)
api.option('str1').value.set(None)
assert api.option('str1').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str1').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_empty():
descr = make_description()
api = Config(descr)
api.option('str1').value.set('')
assert api.option('str1').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str1').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_multi_none():
descr = make_description()
api = Config(descr)
api.option('str3').value.set([None])
assert api.option('str3').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str3').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('str3').value.set(['yes', None])
assert api.option('str3').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str3').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_multi_empty():
descr = make_description()
api = Config(descr)
api.option('str3').value.set([])
assert api.option('str3').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str3').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
#
api.property.read_write()
api.option('str3').value.set([''])
assert api.option('str3').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str3').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
#
api.property.read_write()
api.option('str3').value.set(['yes', ''])
assert api.option('str3').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str3').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_multi_empty_allow_empty_list():
descr = make_description()
api = Config(descr)
api.option('str4').value.set([])
assert api.option('str4').owner.get() == 'user'
api.property.read_only()
prop = []
api.option('str4').value.get()
#
api.property.read_write()
api.option('str4').value.set([''])
assert api.option('str4').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str4').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
#
api.property.read_write()
api.option('str4').value.set(['yes', ''])
assert api.option('str4').owner.get() == 'user'
api.property.read_only()
prop = []
try:
api.option('str4').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_multi_append():
descr = make_description()
api = Config(descr)
api.option('str3').value.set(['yes'])
api.property.read_write()
api.option('str3').value.get().append(None)
def test_mandatory_disabled():
descr = make_description()
api = Config(descr)
api.option('str1').value.get()
api.option('str1').property.add('disabled')
api.property.read_only()
pop = []
try:
api.option('str1').value.get()
except PropertiesOptionError as err:
prop = err.proptype
if TIRAMISU_VERSION == 2:
search_prop = {'disabled', 'mandatory'}
else:
search_prop = {'disabled'}
assert set(prop) == search_prop
def test_mandatory_unicode():
descr = make_description()
api = Config(descr)
api.option('unicode2').value.get()
api.property.read_only()
prop = []
try:
api.option('unicode2').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
api.property.read_write()
api.option('unicode2').value.set(u'')
api.property.read_only()
prop = []
try:
api.option('unicode2').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
def test_mandatory_warnings_ro():
descr = make_description()
api = Config(descr)
api.option('str').value.set('')
api.property.read_only()
proc = []
try:
api.option('str').value.get()
except PropertiesOptionError as err:
prop = err.proptype
assert 'mandatory' in prop
assert list(api.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3']
api.property.read_write()
api.option('str').value.set('a')
api.property.read_only()
assert list(api.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_rw():
descr = make_description()
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.option('str').value.get()
assert list(api.value.mandatory()) == ['str', 'str1', 'unicode2', 'str3']
api.option('str').value.set('a')
assert list(api.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_disabled():
descr = make_description()
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.option('str').value.get()
assert set(api.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
api.option('str').property.add('disabled')
assert set(api.value.mandatory()) == {'str1', 'unicode2', 'str3'}
def test_mandatory_warnings_hidden():
descr = make_description()
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
api.option('str').value.get()
assert set(api.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
api.option('str').property.add('hidden')
assert set(api.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
def test_mandatory_warnings_frozen():
descr = make_description()
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.option('str').value.get()
assert set(api.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
api.option('str').property.add('frozen')
api.property.read_only()
assert set(api.value.mandatory()) == {'str', 'str1', 'unicode2', 'str3'}
def test_mandatory_leader():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
properties=('mandatory', ))
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])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
api.property.read_only()
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
def test_mandatory_warnings_leader():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
properties=('mandatory', ))
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])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
assert list(api.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
def test_mandatory_leader_empty():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
api.property.read_write()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
api.property.read_only()
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set([''])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
api.property.read_only()
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
api.property.read_write()
#
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip2'])
api.property.read_only()
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.reset()")
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
def test_mandatory_warnings_leader_empty():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set([undefined])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [None]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert list(api.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set([''])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert list(api.value.mandatory()) == ['ip_admin_eth0.ip_admin_eth0']
#
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
assert list(api.value.mandatory()) == []
def test_mandatory_follower():
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, properties=('mandatory', ))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.property.read_write()
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('')
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.property.read_write()
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('ip')
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == 'ip'
def test_mandatory_warnings_follower():
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, properties=('mandatory', ))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
descr = OptionDescription('o', '', [interface1])
api = Config(descr)
api.property.read_only()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
api.property.read_write()
assert list(api.value.mandatory()) == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip'])
assert list(api.value.mandatory()) == ['ip_admin_eth0.netmask_admin_eth0']
def test_mandatory_warnings_symlink():
descr = make_description_sym()
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.option('str').value.get()
assert list(api.value.mandatory()) == ['str', 'str1', 'str3']
api.option('str').property.add('frozen')
api.property.read_only()
assert list(api.value.mandatory()) == ['str', 'str1', 'str3']
#def test_mandatory_warnings_validate():
# descr = make_description3()
# api = Config(descr)
# api.option('str').value.set('')
# raises(ValueError, "list(api.value.mandatory())")
# api.option('str').value.set('test')
# raises(ValueError, "list(api.value.mandatory())")
def test_mandatory_warnings_validate_empty():
descr = make_description2()
api = Config(descr)
api.option('str').value.set('')
api.property.read_only()
assert list(api.value.mandatory()) == ['str', 'str1', 'str3', 'unicode1']
def test_mandatory_warnings_requires():
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option',
properties=('mandatory', ))
stroption2 = UnicodeOption('unicode2', 'Test string option',
properties=('mandatory', ))
stroption3 = StrOption('str3', 'Test string option', multi=True, requires=[{'option': stroption, 'expected': 'yes', 'action': 'mandatory', 'transitive': False}])
descr = OptionDescription('tiram', '', [stroption, stroption1, stroption2, stroption3])
api = Config(descr)
api.option('str').value.set('')
api.property.read_write()
api.option('str').value.get()
assert list(api.value.mandatory()) == ['str', 'str1', 'unicode2']
api.property.read_only()
assert list(api.value.mandatory()) == ['str', 'str1', 'unicode2']
api.property.read_write()
api.option('str').value.set('yes')
assert list(api.value.mandatory()) == ['str1', 'unicode2', 'str3']
def test_mandatory_warnings_requires_leadership():
stroption = StrOption('str', 'Test string option', default="abc",
properties=('mandatory', ))
stroption1 = StrOption('str1', 'Test string option', multi=True)
stroption2 = StrOption('str2', 'Test string option', multi=True, requires=[{'option': stroption, 'expected': 'yes', 'action': 'mandatory', 'transitive': False}])
leadership = Leadership('leader', 'leadership', [stroption1, stroption2])
descr = OptionDescription('tiram', '', [stroption, leadership])
api = Config(descr)
api.option('str').value.set('')
api.option('leader.str1').value.set(['str'])
assert list(api.value.mandatory()) == ['str']
api.option('str').value.set('yes')
assert list(api.value.mandatory()) == ['leader.str2']
def test_mandatory_warnings_requires_leadership_follower():
stroption = StrOption('str', 'Test string option', multi=True)
stroption1 = StrOption('str1', 'Test string option', multi=True)
stroption2 = StrOption('str2', 'Test string option', multi=True, requires=[{'option': stroption1, 'expected': 'yes', 'action': 'mandatory', 'transitive': False}])
leadership = Leadership('leader', 'leadership', [stroption, stroption1, stroption2])
descr = OptionDescription('tiram', '', [leadership])
api = Config(descr)
api.option('leader.str').value.set(['str'])
assert list(api.value.mandatory()) == []
api.option('leader.str1', 0).value.set('yes')
assert list(api.value.mandatory()) == ['leader.str2']
def test_mandatory_od_disabled():
descr = make_description()
descr = OptionDescription('od', '', [descr])
api = Config(descr)
api.property.read_only()
assert list(api.value.mandatory()) == ['tiram.str1', 'tiram.unicode2', 'tiram.str3']
api.option('tiram').property.add('disabled')
assert list(api.value.mandatory()) == []

View File

@ -1,1079 +0,0 @@
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu.setting import groups, owners
from tiramisu import IntOption, StrOption, NetworkOption, NetmaskOption, BoolOption, ChoiceOption, \
IPOption, OptionDescription, Leadership, Config, GroupConfig, MetaConfig, \
Params, ParamOption, ParamValue
from tiramisu.error import ConfigError, ConflictError, PropertiesOptionError, LeadershipError, APIError
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
owners.addowner('config')
owners.addowner('meta1')
owners.addowner('meta2')
def return_value(value=None):
return value
def return_condition(val, condition, expected):
if condition == expected:
return val
return None
def raise_exception():
raise Exception('test')
def make_description():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
i5 = IntOption('i5', '', default=[2], multi=True)
i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1])
return od2
def make_metaconfig(double=False):
od2 = make_description()
conf1 = Config(od2, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
meta = MetaConfig([conf1, conf2], session_id='meta')
if double:
meta.owner.set(owners.meta2)
meta = MetaConfig([meta], session_id='doublemeta')
meta.property.read_write()
meta.owner.set(owners.meta1)
return meta
def test_unknown_config():
meta = make_metaconfig()
raises(ConfigError, "meta.config('unknown')")
def test_path():
meta = make_metaconfig()
assert meta.config.path() == 'meta'
assert meta.config('conf1').config.path() == 'meta.conf1'
assert meta.config('conf2').config.path() == 'meta.conf2'
#FIXME ne pas mettre 2 meta dans une config
#FIXME ne pas mettre 2 OD differents dans un meta
def test_none():
meta = make_metaconfig()
assert meta.option('od1.i3').value.get() is meta.config('conf1').option('od1.i3').value.get() is meta.config('conf2').option('od1.i3').value.get() is None
assert meta.option('od1.i3').owner.get() is meta.config('conf1').option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.default
#
meta.option('od1.i3').value.set(3)
assert meta.option('od1.i3').value.get() == meta.config('conf1').option('od1.i3').value.get() == meta.config('conf2').option('od1.i3').value.get() == 3
assert meta.option('od1.i3').owner.get() is meta.config('conf1').option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.meta1
#
meta.config('conf1').option('od1.i3').value.set(2)
assert meta.option('od1.i3').value.get() == meta.config('conf2').option('od1.i3').value.get() == 3
assert meta.config('conf1').option('od1.i3').value.get() == 2
assert meta.option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.meta1
assert meta.config('conf1').option('od1.i3').owner.get() is owners.user
#
meta.option('od1.i3').value.set(4)
assert meta.option('od1.i3').value.get() == meta.config('conf2').option('od1.i3').value.get() == 4
assert meta.config('conf1').option('od1.i3').value.get() == 2
assert meta.option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.meta1
assert meta.config('conf1').option('od1.i3').owner.get() is owners.user
#
meta.option('od1.i3').value.reset()
assert meta.option('od1.i3').value.get() is meta.config('conf2').option('od1.i3').value.get() is None
assert meta.config('conf1').option('od1.i3').value.get() == 2
assert meta.option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.default
assert meta.config('conf1').option('od1.i3').owner.get() is owners.user
#
meta.config('conf1').option('od1.i3').value.reset()
assert meta.option('od1.i3').value.get() is meta.config('conf1').option('od1.i3').value.get() is meta.config('conf2').option('od1.i3').value.get() is None
assert meta.option('od1.i3').owner.get() is meta.config('conf1').option('od1.i3').owner.get() is meta.config('conf2').option('od1.i3').owner.get() is owners.default
#
assert meta.config(None).config.name() == meta.config.name()
def test_reset():
meta = make_metaconfig()
assert meta.option('od1.i2').value.get() == 1
meta.option('od1.i2').value.set(2)
meta.config('conf1').option('od1.i2').value.set(3)
assert meta.option('od1.i2').value.get() == 2
assert meta.config('conf1').option('od1.i2').value.get() == 3
assert meta.config('conf2').option('od1.i2').value.get() == 2
meta.config.reset()
assert meta.option('od1.i2').value.get() == 1
assert meta.config('conf1').option('od1.i2').value.get() == 3
assert meta.config('conf2').option('od1.i2').value.get() == 1
def test_default():
meta = make_metaconfig()
assert meta.option('od1.i2').value.get() == meta.config('conf1').option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 1
assert meta.option('od1.i2').owner.get() is meta.config('conf1').option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.default
#
meta.option('od1.i2').value.set(3)
assert meta.option('od1.i2').value.get() == meta.config('conf1').option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 3
assert meta.option('od1.i2').owner.get() is meta.config('conf1').option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.meta1
#
meta.config('conf1').option('od1.i2').value.set(2)
assert meta.option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 3
assert meta.config('conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.meta1
assert meta.config('conf1').option('od1.i2').owner.get() is owners.user
#
meta.option('od1.i2').value.set(4)
assert meta.option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 4
assert meta.config('conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.meta1
assert meta.config('conf1').option('od1.i2').owner.get() is owners.user
#
meta.option('od1.i2').value.reset()
assert meta.option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 1
assert meta.config('conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.default
assert meta.config('conf1').option('od1.i2').owner.get() is owners.user
#
meta.config('conf1').option('od1.i2').value.reset()
assert meta.option('od1.i2').value.get() == meta.config('conf1').option('od1.i2').value.get() == meta.config('conf2').option('od1.i2').value.get() == 1
assert meta.option('od1.i2').owner.get() is meta.config('conf1').option('od1.i2').owner.get() is meta.config('conf2').option('od1.i2').owner.get() is owners.default
def test_contexts():
meta = make_metaconfig()
errors = meta.value.set('od1.i2', 6, only_config=True)
assert meta.option('od1.i2').value.get() == 1
assert meta.option('od1.i2').owner.get() == owners.default
assert meta.config('conf1').option('od1.i2').value.get() == meta.config('conf1').option('od1.i2').value.get() == 6
assert meta.config('conf1').option('od1.i2').owner.get() == meta.config('conf1').option('od1.i2').owner.get() is owners.user
assert len(errors) == 0
def test_find():
meta = make_metaconfig()
ret = list(meta.option.find('i2'))
assert len(ret) == 1
assert 1 == ret[0].value.get()
assert 1 == meta.option.find('i2', first=True).value.get()
assert meta.value.dict() == {'od1.i4': 2, 'od1.i1': None, 'od1.i3': None,
'od1.i2': 1, 'od1.i5': [2]}
def test_meta_meta():
meta = make_metaconfig(double=True)
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf1').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 1
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf1').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.default
#
meta.option('od1.i2').value.set(3)
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf1').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 3
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf1').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.meta1
#
meta.config('meta.conf1').option('od1.i2').value.set(2)
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 3
assert meta.config('meta.conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.meta1
assert meta.config('meta.conf1').option('od1.i2').owner.get() is owners.user
#
meta.config('meta').option('od1.i2').value.set(4)
assert meta.option('od1.i2').value.get() == 3
assert meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 4
assert meta.config('meta.conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is owners.meta1
assert meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.meta2
assert meta.config('meta.conf1').option('od1.i2').owner.get() is owners.user
#
meta.config('meta').option('od1.i2').value.reset()
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 3
assert meta.config('meta.conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.meta1
assert meta.config('meta.conf1').option('od1.i2').owner.get() is owners.user
#
meta.option('od1.i2').value.reset()
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 1
assert meta.config('meta.conf1').option('od1.i2').value.get() == 2
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.default
assert meta.config('meta.conf1').option('od1.i2').owner.get() is owners.user
#
meta.config('meta.conf1').option('od1.i2').value.reset()
assert meta.option('od1.i2').value.get() == meta.config('meta').option('od1.i2').value.get() == meta.config('meta.conf1').option('od1.i2').value.get() == meta.config('meta.conf2').option('od1.i2').value.get() == 1
assert meta.option('od1.i2').owner.get() is meta.config('meta').option('od1.i2').owner.get() is meta.config('meta.conf1').option('od1.i2').owner.get() is meta.config('meta.conf2').option('od1.i2').owner.get() is owners.default
def test_meta_new_config():
od = make_description()
meta = MetaConfig(['name1', 'name2'], optiondescription=od)
assert len(list(meta.config.list())) == 2
meta.config.new('newconf1')
assert len(list(meta.config.list())) == 3
def test_meta_new_config_owner():
od = make_description()
meta = MetaConfig(['name1', 'name2'], optiondescription=od)
meta.owner.set('meta')
meta.config.new('newconf1')
assert meta.owner.get() == 'meta'
def test_meta_new_metaconfig():
od = make_description()
meta = MetaConfig(['name1', 'name2'], optiondescription=od)
meta.config.new('newconf1', type='metaconfig')
meta.config('newconf1').config.new('newconf2', type='metaconfig')
meta.config('newconf1').config('newconf2').config.new('newconf3')
assert meta.config('newconf1').config('newconf2').config('newconf3').config.name() == 'newconf3'
def test_meta_pop_config():
od = make_description()
meta = MetaConfig(['name1', 'name2'], optiondescription=od)
assert len(list(meta.config.list())) == 2
meta.config.new('newconf1')
assert len(list(meta.config.list())) == 3
meta.config.pop('newconf1')
assert len(list(meta.config.list())) == 2
raises(ConfigError, "meta.config.pop('newconf1')")
def test_meta_new_config_wrong_name():
od = make_description()
meta = MetaConfig(['name1', 'name2'], optiondescription=od)
assert len(list(meta.config.list())) == 2
raises(ConflictError, "meta.config.new('name1')")
assert len(list(meta.config.list())) == 2
def test_meta_meta_set():
meta = make_metaconfig(double=True)
errors1 = meta.value.set('od1.i1', 7, only_config=True)
errors2 = meta.value.set('od1.i6', 7, only_config=True)
assert len(errors1) == 0
assert len(errors2) == 2
conf1 = meta.config('meta.conf1')._config_bag.context
conf2 = meta.config('meta.conf2')._config_bag.context
assert meta.config('meta.conf1').option('od1.i1').value.get() == meta.config('meta.conf2').option('od1.i1').value.get() == 7
#
dconfigs = []
for conf in meta.config.find('i1', value=7).config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
meta.config('meta.conf1').option('od1.i1').value.set(8)
#
dconfigs = []
for conf in meta.config.find('i1').config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
assert conf2 == list(meta.config.find('i1', value=7).config.list())[0]._config_bag.context
assert conf1 == list(meta.config.find('i1', value=8).config.list())[0]._config_bag.context
#
dconfigs = []
for conf in meta.config.find('i5', value=2).config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
#
raises(AttributeError, "meta.config.find('i1', value=10)")
raises(AttributeError, "meta.config.find('not', value=10)")
raises(AttributeError, "meta.config.find('i6')")
raises(ValueError, "meta.value.set('od1.i6', 7, only_config=True, force_default=True)")
raises(ValueError, "meta.value.set('od1.i6', 7, only_config=True, force_default_if_same=True)")
raises(ValueError, "meta.value.set('od1.i6', 7, only_config=True, force_dont_change_value=True)")
def test_not_meta():
i1 = IntOption('i1', '')
od1 = OptionDescription('od1', '', [i1])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
conf3 = Config(od2)
conf4 = Config(od2, session_id='conf4')
raises(TypeError, "GroupConfig(conf1)")
#same name
#raises(ConflictError, "GroupConfig([conf2, conf4], session_id='conf2')")
raises(ConflictError, "GroupConfig([conf2, conf2], session_id='conf8')")
grp = GroupConfig([conf1, conf2])
raises(APIError, "grp.option('od1.i1').value.get()")
conf1, conf2 = grp.config.list()
errors = grp.value.set('od1.i1', 7)
assert len(errors) == 0
assert grp.config('conf1').option('od1.i1').value.get() == grp.config('conf2').option('od1.i1').value.get() == 7
assert grp.config('conf1').option('od1.i1').owner.get() is grp.config('conf2').option('od1.i1').owner.get() is owners.user
grp.option('od1.i1').value.reset()
assert grp.config('conf1').option('od1.i1').owner.get() is grp.config('conf2').option('od1.i1').owner.get() is owners.default
def test_group_find_firsts():
i1 = IntOption('i1', '')
od1 = OptionDescription('od1', '', [i1])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
grp = GroupConfig([conf1, conf2])
itr = grp.config.find('i1').config.list()
conf1._config_bag.context == next(itr)._config_bag.context
conf2._config_bag.context == next(itr)._config_bag.context
try:
next(itr)
except StopIteration:
pass
except:
raise Exception('no')
else:
raise Exception('no')
def test_group_group():
i1 = IntOption('i1', '')
od1 = OptionDescription('od1', '', [i1])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf9')
conf2 = Config(od2, session_id='conf10')
grp = GroupConfig([conf1, conf2], 'grp')
grp2 = GroupConfig([grp])
errors = grp2.value.set('od1.i1', 2)
assert len(errors) == 0
assert grp2.config('grp.conf9').option('od1.i1').value.get() == 2
assert grp2.config('grp.conf9').option('od1.i1').owner.get() is owners.user
def test_group_group_path():
i1 = IntOption('i1', '')
od1 = OptionDescription('od1', '', [i1])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf9')
conf2 = Config(od2, session_id='conf10')
grp = GroupConfig([conf1, conf2], 'grp')
grp2 = GroupConfig([grp], 'grp2')
assert grp2.config.path() == 'grp2'
assert grp2.config('grp').config.path() == 'grp'
assert grp2.config('grp.conf9').config.path() == 'conf9'
assert grp2.config('grp.conf10').config.path() == 'conf10'
def test_meta_unconsistent():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
od1 = OptionDescription('od1', '', [i1, i2, i3, i4])
od2 = OptionDescription('od2', '', [od1])
i5 = IntOption('i5', '')
od3 = OptionDescription('od3', '', [i5])
conf1 = Config(od2, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
conf3 = Config(od2, session_id='conf3')
conf4 = Config(od3, session_id='conf4')
meta = MetaConfig([conf1, conf2])
meta.owner.set(owners.meta1)
raises(TypeError, 'MetaConfig("string")')
#same descr but conf1 already in meta
raises(ValueError, "MetaConfig([conf1, conf3])")
#not same descr
raises(ValueError, "MetaConfig([conf3, conf4])")
def test_meta_leadership():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_only()
itr = meta.config.find('ip_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
itr = meta.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
meta.property.read_write()
raises(AttributeError, "meta.config.find('netmask_admin_eth0')")
itr = meta.unrestraint.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
meta.property.read_only()
itr = meta.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
def test_meta_leadership_value2():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2], session_id="meta")
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.8'])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#FIXME devrait raise ! assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0', 0).value.get() == None
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.reset()
#
meta.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
def test_meta_leadership_value_default():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#
meta.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
#
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
def test_meta_leadership_owners():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.owner.set(owners.meta1)
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
raises(LeadershipError, "meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()")
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
#
meta.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.meta1
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
#
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.meta1
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.meta1
#
meta.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.meta1
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.meta1
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user
assert meta.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
def test_meta_force_default():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1'])
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
#
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.3'])
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
#
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
def test_meta_force_dont_change_value():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_dont_change_value=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
def test_meta_force_default_if_same():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
#
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default_if_same=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.3'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.5'], force_default_if_same=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1
def test_meta_force_default_if_same_and_dont_change():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
#
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default_if_same=True, force_dont_change_value=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.meta1
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
#
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.3'])
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.5'], force_default_if_same=True, force_dont_change_value=True)
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
def test_meta_force_default_and_dont_change():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='rconf1')
conf2 = Config(od, session_id='rconf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
raises(ValueError, "meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True, force_dont_change_value=True)")
def test_meta_properties_meta():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
netmask_admin_eth0.impl_add_consistency('network_netmask', ip_admin_eth0)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
assert meta.config('conf1').value.dict() == {}
def test_meta_exception_meta():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, callback=raise_exception)
netmask_admin_eth0.impl_add_consistency('network_netmask', ip_admin_eth0)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
raises(Exception, "conf1.make_dict()")
def test_meta_properties_requires_mandatory():
probes = BoolOption('probes', 'probes available', False)
eth0_method = ChoiceOption('eth0_method', '', ('static', 'dhcp'), 'static')
ip_address = IPOption('ip_address', '')
ip_eth0 = IPOption('ip_eth0', "ip", requires=({'option': probes, 'expected': True, 'action': 'mandatory'},), callback=return_condition, callback_params=Params(kwargs={'val': ParamOption(ip_address), 'condition': ParamOption(eth0_method), 'expected': ParamValue('dhcp')}))
ip_gw = IPOption('ip_gw', 'gw')
ip_gw.impl_add_consistency('not_equal', ip_eth0)
od = OptionDescription('root', '', [ip_gw, probes, eth0_method, ip_address, ip_eth0])
conf1 = Config(od, session_id='conf1')
conf1.property.read_write()
meta = MetaConfig([conf1], 'meta')
#
meta.option('probes').value.set(True)
meta.option('ip_address').value.set('1.1.1.1')
meta.option('ip_gw').value.set('1.1.1.2')
conf1.option('eth0_method').value.set('dhcp')
conf1.property.read_only()
assert 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'}
def test_meta_callback():
val1 = StrOption('val1', "", 'val')
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1)))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(ParamValue('yes')))
val4 = StrOption('val4', "", callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
val5 = StrOption('val5', "", callback=return_value, callback_params=Params(kwargs={'value': ParamValue('yes')}))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5])
cfg = Config(maconfig, session_id='cfg')
meta = MetaConfig([cfg])
meta.property.read_write()
assert meta.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'val', 'val1': 'val', 'val5': 'yes', 'val4': 'val'}
meta.config('cfg').option('val1').value.set('new')
assert meta.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new'}
meta.config('cfg').option('val1').value.reset()
meta.option('val1').value.set('new')
assert meta.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new'}
meta.config('cfg').option('val4').value.set('new1')
assert meta.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'}
meta.config('cfg').option('val4').value.reset()
meta.option('val4').value.set('new1')
assert meta.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'}
meta.option('val4').value.reset()
def test_meta_callback_follower():
val = StrOption('val', "", default='val')
val1 = StrOption('val1', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val)))
val3 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
val4 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
interface1 = Leadership('val1', '', [val1, val3, val4])
od = OptionDescription('root', '', [interface1])
maconfig = OptionDescription('rootconfig', '', [val, interface1])
cfg = Config(maconfig, session_id='cfg1')
meta = MetaConfig([cfg])
meta.property.read_write()
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
meta.config('cfg1').option('val').value.set('val1')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val1'], 'val1.val1': ['val1'], 'val1.val3': ['val1'], 'val': 'val1'}
meta.config('cfg1').option('val').value.reset()
meta.option('val').value.set('val1')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val1'], 'val1.val1': ['val1'], 'val1.val3': ['val1'], 'val': 'val1'}
meta.option('val').value.reset()
meta.config('cfg1').option('val1.val2', 0).value.set('val2')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
meta.config('cfg1').option('val1.val2', 0).value.reset()
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
meta.option('val1.val2', 0).value.set('val2')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
meta.config('cfg1').option('val1.val3', 0).value.set('val6')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val6'], 'val': 'val'}
meta.option('val1.val2', 0).value.reset()
meta.config('cfg1').option('val1.val3', 0).value.reset()
meta.config('cfg1').option('val1.val1').value.set(['val3'])
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val3'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
meta.config('cfg1').option('val1.val1').value.reset()
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
meta.option('val1.val1').value.set(['val3'])
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val3'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
meta.config('cfg1').option('val1.val2', 0).value.set('val2')
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
meta.option('val1.val1').value.set(['val3', 'rah'])
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2', 'rah'], 'val1.val1': ['val3', 'rah'], 'val1.val3': ['val3', 'rah'], 'val': 'val'}
meta.option('val1.val1').value.pop(1)
meta.option('val1.val1').value.set(['val4'])
assert meta.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val4'], 'val1.val3': ['val4'], 'val': 'val'}
def test_meta_reset():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.owner.set('meta1')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1'])
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
meta.value.reset('ip_admin_eth0.ip_admin_eth0')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_meta_properties_meta_copy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface1, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
meta = MetaConfig([conf1, conf2], session_id='meta1')
meta.property.read_write()
conf3 = meta.config('conf1').config.copy(session_id='conf3')
meta2 = conf3.config.metaconfig()
assert meta.config.name() == meta2.config.name()
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert meta.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
meta.option('ip_admin_eth0').value.set(['192.168.1.2'])
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert meta.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
ret = meta.value.set('ip_admin_eth0', ['192.168.1.3'], force_default_if_same=True)
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert meta.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
def test_meta_properties_meta_deepcopy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface1, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
meta = MetaConfig([conf1, conf2])
meta.permissive.set(frozenset({'hidden'}))
meta.property.read_write()
meta2 = meta.config('conf1').config.deepcopy(session_id='conf3')
assert meta != meta2
assert meta.permissive.get() == meta2.permissive.get()
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert meta2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
meta.option('ip_admin_eth0').value.set(['192.168.1.2'])
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert meta2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
meta.value.set('ip_admin_eth0', ['192.168.1.3'], force_default_if_same=True)
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert meta.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert meta2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
def test_meta_properties_submeta_deepcopy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface1, session_id='conf1')
conf1.property.read_write()
meta1 = MetaConfig([conf1], session_id='meta1')
meta2 = MetaConfig([meta1], session_id='meta2')
meta_copy = conf1.config.deepcopy(session_id='conf2',
metaconfig_prefix='copy_')
assert meta_copy.config.name() == 'copy_meta2'
assert meta_copy.config('copy_meta1').config.name() == 'copy_meta1'
assert meta_copy.config('copy_meta1').config('conf2').config.name() == 'conf2'
def test_meta_properties_submeta_deepcopy_owner():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip")
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask")
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface1, session_id='conf1')
conf1.owner.set('conf1_user')
conf1.property.read_write()
meta1 = MetaConfig([conf1], session_id='meta1')
meta1.owner.set('meta1_user')
meta2 = MetaConfig([meta1], session_id='meta2')
meta2.owner.set('meta2_user')
#
conf1.option('ip_admin_eth0').value.set('192.168.0.1')
assert conf1.option('ip_admin_eth0').owner.get() == 'conf1_user'
meta1.option('ip_admin_eth0').value.set('192.168.0.2')
assert meta1.option('ip_admin_eth0').owner.get() == 'meta1_user'
meta2.option('ip_admin_eth0').value.set('192.168.0.3')
assert meta2.option('ip_admin_eth0').owner.get() == 'meta2_user'
#
meta2_copy = conf1.config.deepcopy(session_id='conf2',
metaconfig_prefix='copy_')
meta2_copy.option('netmask_admin_eth0').value.set('255.255.255.255')
assert meta2_copy.option('ip_admin_eth0').value.get() == '192.168.0.3'
assert meta2_copy.option('ip_admin_eth0').owner.get() == 'meta2_user'
assert meta2_copy.option('netmask_admin_eth0').owner.get() == 'meta2_user'
#
meta1_copy = meta2_copy.config('copy_meta1')
meta1_copy.option('netmask_admin_eth0').value.set('255.255.255.255')
assert meta1_copy.option('ip_admin_eth0').value.get() == '192.168.0.2'
assert meta1_copy.option('ip_admin_eth0').owner.get() == 'meta1_user'
assert meta1_copy.option('netmask_admin_eth0').owner.get() == 'meta1_user'
#
conf2 = meta1_copy.config('conf2')
conf2.owner.set('conf2_user')
conf2.option('netmask_admin_eth0').value.set('255.255.255.255')
assert conf2.option('netmask_admin_eth0').owner.get() == 'conf2_user'
assert conf2.option('ip_admin_eth0').value.get() == '192.168.0.1'
assert conf2.option('ip_admin_eth0').owner.get() == 'conf1_user'
def test_meta_properties_meta_set_value():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface1, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
assert meta.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
ret = meta.value.set('netmask_admin_eth0', ['255.255.255.255'], only_config=True)
assert len(ret) == 2
assert isinstance(ret[0], PropertiesOptionError)
assert isinstance(ret[1], PropertiesOptionError)
del ret[1]
del ret[0]
del ret
ret = meta.value.set('netmask_admin_eth0', ['255.255.255.255'], force_default=True)
assert len(ret) == 1
assert isinstance(ret[0], PropertiesOptionError)
del ret[0]
del ret
ret = meta.value.set('netmask_admin_eth0', ['255.255.255.255'], force_dont_change_value=True)
assert len(ret) == 3
assert isinstance(ret[0], PropertiesOptionError)
assert isinstance(ret[1], PropertiesOptionError)
assert isinstance(ret[2], PropertiesOptionError)
del ret[2]
del ret[1]
del ret[0]
del ret
ret = meta.value.set('netmask_admin_eth0', ['255.255.255.255'], force_default_if_same=True)
assert len(ret) == 1
assert isinstance(ret[0], PropertiesOptionError)
del ret[0]
del ret
ret = meta.value.set('ip_admin_eth0', '255.255.255.255', only_config=True)
assert len(ret) == 2
assert isinstance(ret[0], ValueError)
assert isinstance(ret[1], ValueError)
del ret[1]
del ret[0]
del ret
ret = meta.value.set('ip_admin_eth0', '255.255.255.255', force_default=True)
assert len(ret) == 1
assert isinstance(ret[0], ValueError)
del ret[0]
del ret
ret = meta.value.set('ip_admin_eth0', '255.255.255.255', force_dont_change_value=True)
assert len(ret) == 1
assert isinstance(ret[0], ValueError)
del ret[0]
del ret
ret = meta.value.set('ip_admin_eth0', '255.255.255.255', force_default_if_same=True)
assert len(ret) == 1
assert isinstance(ret[0], ValueError)
del ret[0]
del ret
def test_metaconfig_force_metaconfig_on_freeze():
dummy1 = StrOption('dummy1', 'doc dummy', default='default', properties=('force_metaconfig_on_freeze',))
group = OptionDescription('group', '', [dummy1])
config = Config(group, session_id='config')
config.owner.set(owners.config)
meta1 = MetaConfig([config], session_id='meta1')
meta1.owner.set(owners.meta1)
meta2 = MetaConfig([meta1], session_id='meta2')
meta2.owner.set(owners.meta2)
config.property.read_write()
config.option('dummy1').property.add('frozen')
#
assert config.option('dummy1').value.get() == 'default'
assert config.option('dummy1').owner.get() == 'default'
#
meta2.option('dummy1').value.set('meta2')
#
assert config.option('dummy1').value.get() == 'meta2'
assert config.option('dummy1').owner.get() == 'meta2'
#
config.option('dummy1').property.pop('frozen')
config.option('dummy1').value.set('config')
config.option('dummy1').property.add('frozen')
#
assert config.option('dummy1').value.get() == 'meta2'
assert config.option('dummy1').owner.get() == 'meta2'
#
meta1.option('dummy1').value.set('meta1')
#
assert config.option('dummy1').value.get() == 'meta1'
assert config.option('dummy1').owner.get() == 'meta1'
#
config.option('dummy1').property.pop('frozen')
assert config.option('dummy1').value.get() == 'config'
assert config.option('dummy1').owner.get() == 'config'
def test_metaconfig_force_metaconfig_on_freeze_option():
dummy1 = StrOption('dummy1', 'doc dummy', default='default')
dummy2 = StrOption('dummy2', 'doc dummy', default='default', properties=('force_default_on_freeze',))
group = OptionDescription('group', '', [dummy1, dummy2])
config = Config(group, session_id='config')
config.owner.set(owners.config)
meta1 = MetaConfig([config], session_id='meta1')
meta1.owner.set(owners.meta1)
meta2 = MetaConfig([meta1], session_id='meta2')
meta2.owner.set(owners.meta2)
config.property.read_write()
config.option('dummy1').property.add('frozen')
config.option('dummy1').property.add('force_metaconfig_on_freeze')
config.option('dummy2').property.add('frozen')
#
assert config.option('dummy1').value.get() == 'default'
assert config.option('dummy1').owner.get() == 'default'
assert config.option('dummy2').value.get() == 'default'
assert config.option('dummy2').owner.get() == 'default'
#
meta2.option('dummy1').value.set('meta2')
meta2.option('dummy2').value.set('meta2')
#
assert config.option('dummy1').value.get() == 'meta2'
assert config.option('dummy1').owner.get() == 'meta2'
assert config.option('dummy2').value.get() == 'default'
assert config.option('dummy2').owner.get() == 'default'
#
config.option('dummy1').property.pop('frozen')
config.option('dummy2').property.pop('frozen')
config.option('dummy1').value.set('config')
config.option('dummy2').value.set('config')
config.option('dummy1').property.add('frozen')
config.option('dummy2').property.add('frozen')
#
assert config.option('dummy1').value.get() == 'meta2'
assert config.option('dummy1').owner.get() == 'meta2'
assert config.option('dummy2').value.get() == 'default'
assert config.option('dummy2').owner.get() == 'default'
#
meta1.option('dummy1').value.set('meta1')
meta1.option('dummy2').value.set('meta1')
#
assert config.option('dummy1').value.get() == 'meta1'
assert config.option('dummy1').owner.get() == 'meta1'
assert config.option('dummy2').value.get() == 'default'
assert config.option('dummy2').owner.get() == 'default'
#
meta1.option('dummy1').property.add('force_metaconfig_on_freeze')
assert config.option('dummy1').value.get() == 'meta2'
assert config.option('dummy1').owner.get() == 'meta2'
#
meta2.option('dummy1').property.add('force_metaconfig_on_freeze')
assert config.option('dummy1').value.get() == 'default'
assert config.option('dummy1').owner.get() == 'default'
#
meta1.option('dummy1').property.pop('force_metaconfig_on_freeze')
assert config.option('dummy1').value.get() == 'meta1'
assert config.option('dummy1').owner.get() == 'meta1'
#
config.option('dummy1').property.pop('frozen')
assert config.option('dummy1').value.get() == 'config'
assert config.option('dummy1').owner.get() == 'config'

View File

@ -1,1074 +0,0 @@
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import groups, owners
from tiramisu import IntOption, StrOption, NetworkOption, NetmaskOption, \
OptionDescription, Leadership, Config, GroupConfig, MixConfig, \
Params, ParamOption, ParamValue
from tiramisu.error import ConfigError, ConflictError, PropertiesOptionError, LeadershipError, APIError
from tiramisu.storage import list_sessions
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
def raise_exception():
raise Exception('test')
def make_description():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
i5 = IntOption('i5', '', default=[2], multi=True)
i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1])
return od2
def make_description1():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
i5 = IntOption('i5', '', default=[2], multi=True)
i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1])
return od2
def make_description2():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
i5 = IntOption('i5', '', default=[2], multi=True)
i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1])
return od2
def make_description3():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
i5 = IntOption('i5', '', default=[2], multi=True)
i6 = IntOption('i6', '', properties=('disabled',))
od1 = OptionDescription('od1', '', [i1, i2, i3, i4, i5, i6])
od2 = OptionDescription('od2', '', [od1])
return od2
def make_mixconfig(double=False):
od1 = make_description()
od2 = make_description1()
od3 = make_description2()
conf1 = Config(od1, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
mix = MixConfig(od3, [conf1, conf2], session_id='mix')
if double:
od4 = make_description3()
mix.owner.set(owners.mix2)
mix = MixConfig(od4, [mix], session_id='doublemix')
mix.property.read_write()
mix.owner.set(owners.mix1)
return mix
def test_mix_name():
mix = make_mixconfig(True)
assert mix.config.path() == 'doublemix'
assert mix.config('mix').config.path() == 'doublemix.mix'
assert mix.config('mix.conf1').config.path() == 'doublemix.mix.conf1'
assert mix.config('mix.conf2').config.path() == 'doublemix.mix.conf2'
def test_mix_not_group():
i1 = IntOption('i1', '')
od1 = OptionDescription('od1', '', [i1])
od2 = OptionDescription('od2', '', [od1])
conf1 = Config(od2, session_id='conf1')
grp = GroupConfig([conf1])
raises(TypeError, "MixConfig(od2, [grp])")
def test_unknown_config():
mix = make_mixconfig()
raises(ConfigError, "mix.config('unknown')")
def test_none():
mix = make_mixconfig()
assert mix.option('od1.i3').value.get() is mix.config('conf1').option('od1.i3').value.get() is mix.config('conf2').option('od1.i3').value.get() is None
assert mix.option('od1.i3').owner.get() is mix.config('conf1').option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.default
#
mix.option('od1.i3').value.set(3)
assert mix.option('od1.i3').value.get() == mix.config('conf1').option('od1.i3').value.get() == mix.config('conf2').option('od1.i3').value.get() == 3
assert mix.option('od1.i3').owner.get() is mix.config('conf1').option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.mix1
#
mix.config('conf1').option('od1.i3').value.set(2)
assert mix.option('od1.i3').value.get() == mix.config('conf2').option('od1.i3').value.get() == 3
assert mix.config('conf1').option('od1.i3').value.get() == 2
assert mix.option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.mix1
assert mix.config('conf1').option('od1.i3').owner.get() is owners.user
#
mix.option('od1.i3').value.set(4)
assert mix.option('od1.i3').value.get() == mix.config('conf2').option('od1.i3').value.get() == 4
assert mix.config('conf1').option('od1.i3').value.get() == 2
assert mix.option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.mix1
assert mix.config('conf1').option('od1.i3').owner.get() is owners.user
#
mix.option('od1.i3').value.reset()
assert mix.option('od1.i3').value.get() is mix.config('conf2').option('od1.i3').value.get() is None
assert mix.config('conf1').option('od1.i3').value.get() == 2
assert mix.option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.default
assert mix.config('conf1').option('od1.i3').owner.get() is owners.user
#
mix.config('conf1').option('od1.i3').value.reset()
assert mix.option('od1.i3').value.get() is mix.config('conf1').option('od1.i3').value.get() is mix.config('conf2').option('od1.i3').value.get() is None
assert mix.option('od1.i3').owner.get() is mix.config('conf1').option('od1.i3').owner.get() is mix.config('conf2').option('od1.i3').owner.get() is owners.default
#
assert mix.config(None).config.name() == mix.config.name()
def test_reset():
mix = make_mixconfig()
assert mix.option('od1.i2').value.get() == 1
mix.option('od1.i2').value.set(2)
mix.config('conf1').option('od1.i2').value.set(3)
assert mix.option('od1.i2').value.get() == 2
assert mix.config('conf1').option('od1.i2').value.get() == 3
assert mix.config('conf2').option('od1.i2').value.get() == 2
mix.config.reset()
assert mix.option('od1.i2').value.get() == 1
assert mix.config('conf1').option('od1.i2').value.get() == 3
assert mix.config('conf2').option('od1.i2').value.get() == 1
def test_default():
mix = make_mixconfig()
assert mix.option('od1.i2').value.get() == mix.config('conf1').option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 1
assert mix.option('od1.i2').owner.get() is mix.config('conf1').option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.default
#
mix.option('od1.i2').value.set(3)
assert mix.option('od1.i2').value.get() == mix.config('conf1').option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 3
assert mix.option('od1.i2').owner.get() is mix.config('conf1').option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.mix1
#
mix.config('conf1').option('od1.i2').value.set(2)
assert mix.option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 3
assert mix.config('conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.mix1
assert mix.config('conf1').option('od1.i2').owner.get() is owners.user
#
mix.option('od1.i2').value.set(4)
assert mix.option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 4
assert mix.config('conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.mix1
assert mix.config('conf1').option('od1.i2').owner.get() is owners.user
#
mix.option('od1.i2').value.reset()
assert mix.option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 1
assert mix.config('conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.default
assert mix.config('conf1').option('od1.i2').owner.get() is owners.user
#
mix.config('conf1').option('od1.i2').value.reset()
assert mix.option('od1.i2').value.get() == mix.config('conf1').option('od1.i2').value.get() == mix.config('conf2').option('od1.i2').value.get() == 1
assert mix.option('od1.i2').owner.get() is mix.config('conf1').option('od1.i2').owner.get() is mix.config('conf2').option('od1.i2').owner.get() is owners.default
def test_contexts():
mix = make_mixconfig()
errors = mix.value.set('od1.i2', 6, only_config=True)
assert mix.option('od1.i2').value.get() == 1
assert mix.option('od1.i2').owner.get() == owners.default
assert mix.config('conf1').option('od1.i2').value.get() == mix.config('conf1').option('od1.i2').value.get() == 6
assert mix.config('conf1').option('od1.i2').owner.get() == mix.config('conf1').option('od1.i2').owner.get() is owners.user
assert len(errors) == 0
def test_find():
mix = make_mixconfig()
ret = list(mix.option.find('i2'))
assert len(ret) == 1
assert 1 == ret[0].value.get()
assert 1 == mix.option.find('i2', first=True).value.get()
assert mix.value.dict() == {'od1.i4': 2, 'od1.i1': None, 'od1.i3': None,
'od1.i2': 1, 'od1.i5': [2]}
def test_mix_mix():
mix = make_mixconfig(double=True)
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf1').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 1
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf1').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.default
#
mix.option('od1.i2').value.set(3)
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf1').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 3
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf1').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.mix1
#
mix.config('mix.conf1').option('od1.i2').value.set(2)
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 3
assert mix.config('mix.conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.mix1
assert mix.config('mix.conf1').option('od1.i2').owner.get() is owners.user
#
mix.config('mix').option('od1.i2').value.set(4)
assert mix.option('od1.i2').value.get() == 3
assert mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 4
assert mix.config('mix.conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is owners.mix1
assert mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.mix2
assert mix.config('mix.conf1').option('od1.i2').owner.get() is owners.user
#
mix.config('mix').option('od1.i2').value.reset()
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 3
assert mix.config('mix.conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.mix1
assert mix.config('mix.conf1').option('od1.i2').owner.get() is owners.user
#
mix.option('od1.i2').value.reset()
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 1
assert mix.config('mix.conf1').option('od1.i2').value.get() == 2
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.default
assert mix.config('mix.conf1').option('od1.i2').owner.get() is owners.user
#
mix.config('mix.conf1').option('od1.i2').value.reset()
assert mix.option('od1.i2').value.get() == mix.config('mix').option('od1.i2').value.get() == mix.config('mix.conf1').option('od1.i2').value.get() == mix.config('mix.conf2').option('od1.i2').value.get() == 1
assert mix.option('od1.i2').owner.get() is mix.config('mix').option('od1.i2').owner.get() is mix.config('mix.conf1').option('od1.i2').owner.get() is mix.config('mix.conf2').option('od1.i2').owner.get() is owners.default
def test_mix_mix_set():
mix = make_mixconfig(double=True)
errors1 = mix.value.set('od1.i1', 7, only_config=True)
errors2 = mix.value.set('od1.i6', 7, only_config=True)
assert len(errors1) == 0
assert len(errors2) == 2
conf1 = mix.config('mix.conf1')._config_bag.context
conf2 = mix.config('mix.conf2')._config_bag.context
assert mix.config('mix.conf1').option('od1.i1').value.get() == mix.config('mix.conf2').option('od1.i1').value.get() == 7
#
dconfigs = []
for conf in mix.config.find('i1', value=7).config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
mix.config('mix.conf1').option('od1.i1').value.set(8)
#
dconfigs = []
for conf in mix.config.find('i1').config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
assert conf2 == list(mix.config.find('i1', value=7).config.list())[0]._config_bag.context
assert conf1 == list(mix.config.find('i1', value=8).config.list())[0]._config_bag.context
#
dconfigs = []
for conf in mix.config.find('i5', value=2).config.list():
dconfigs.append(conf._config_bag.context)
assert [conf1, conf2] == dconfigs
#
raises(AttributeError, "mix.config.find('i1', value=10)")
raises(AttributeError, "mix.config.find('not', value=10)")
raises(AttributeError, "mix.config.find('i6')")
raises(ValueError, "mix.value.set('od1.i6', 7, only_config=True, force_default=True)")
raises(ValueError, "mix.value.set('od1.i6', 7, only_config=True, force_default_if_same=True)")
raises(ValueError, "mix.value.set('od1.i6', 7, only_config=True, force_dont_change_value=True)")
def test_mix_unconsistent():
i1 = IntOption('i1', '')
i2 = IntOption('i2', '', default=1)
i3 = IntOption('i3', '')
i4 = IntOption('i4', '', default=2)
od1 = OptionDescription('od1', '', [i1, i2, i3, i4])
od2 = OptionDescription('od2', '', [od1])
od3 = OptionDescription('od3', '', [od1])
conf1 = Config(od2, session_id='conf1')
conf2 = Config(od2, session_id='conf2')
conf3 = Config(od2, session_id='conf3')
i5 = IntOption('i5', '')
od4 = OptionDescription('od4', '', [i5])
conf4 = Config(od4, session_id='conf4')
mix = MixConfig(od2, [conf1, conf2])
mix.owner.set(owners.mix1)
raises(TypeError, 'MixConfig(od2, "string")')
# same descr but conf1 already in mix
raises(ValueError, "MixConfig(od2, [conf1, conf3])")
# not same descr
MixConfig(od2, [conf3, conf4])
def test_mix_leadership():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_only()
itr = mix.config.find('ip_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
itr = mix.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
mix.property.read_write()
raises(AttributeError, "mix.config.find('netmask_admin_eth0')")
itr = mix.unrestraint.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
mix.property.read_only()
itr = mix.config.find('netmask_admin_eth0').config.list()
assert conf1._config_bag.context == next(itr)._config_bag.context
assert conf2._config_bag.context == next(itr)._config_bag.context
def test_mix_leadership_value2():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2], session_id="mix")
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.8'])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#FIXME devrait raise ! assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0', 0).value.get() == None
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.reset()
#
mix.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
def test_mix_leadership_value_default():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#
mix.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
#
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.255.0'
#
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == '255.255.0.0'
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
def test_mix_leadership_owners():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.owner.set(owners.mix1)
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
raises(LeadershipError, "mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()")
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
#
mix.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.mix1
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
#
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.mix1
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.mix1
#
mix.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.0.0')
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.mix1
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.mix1
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.user
assert mix.config('conf1').option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
def test_mix_force_default():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
mix.owner.set('mix1')
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1'])
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
#
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.3'])
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
#
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
def test_mix_force_dont_change_value():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
mix.owner.set('mix1')
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_dont_change_value=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
def test_mix_force_default_if_same():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
mix.owner.set('mix1')
#
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default_if_same=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.3'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.5'], force_default_if_same=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1
def test_mix_force_default_if_same_and_dont_change():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
mix.owner.set('mix1')
#
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.4'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default_if_same=True, force_dont_change_value=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.4']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.mix1
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
#
mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.3'])
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
errors = mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.5'], force_default_if_same=True, force_dont_change_value=True)
assert len(errors) == 0
assert mix.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.5']
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.3']
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert mix.config('conf1').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
assert mix.config('conf2').option('ip_admin_eth0.ip_admin_eth0').owner.get() is owners.user
def test_mix_force_default_and_dont_change():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='rconf1')
conf2 = Config(od, session_id='rconf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
mix.owner.set('mix1')
raises(ValueError, "mix.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.4'], force_default=True, force_dont_change_value=True)")
def test_mix_properties_mix():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
netmask_admin_eth0.impl_add_consistency('network_netmask', ip_admin_eth0)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
assert mix.config('conf1').value.dict() == {}
def test_mix_exception_mix():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, callback=raise_exception)
netmask_admin_eth0.impl_add_consistency('network_netmask', ip_admin_eth0)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
conf1 = Config(od, session_id='conf1')
conf2 = Config(od, session_id='conf2')
mix = MixConfig(od, [conf1, conf2])
mix.property.read_write()
raises(Exception, "conf1.make_dict()")
def test_mix_callback():
val1 = StrOption('val1', "", 'val')
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1)))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(ParamValue('yes')))
val4 = StrOption('val4', "", callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
val5 = StrOption('val5', "", callback=return_value, callback_params=Params(kwargs={'value': ParamValue('yes')}))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5])
cfg = Config(maconfig, session_id='cfg')
mix = MixConfig(maconfig, [cfg])
mix.property.read_write()
assert mix.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'val', 'val1': 'val', 'val5': 'yes', 'val4': 'val'}
mix.config('cfg').option('val1').value.set('new')
assert mix.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new'}
mix.config('cfg').option('val1').value.reset()
mix.option('val1').value.set('new')
assert mix.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new'}
mix.config('cfg').option('val4').value.set('new1')
assert mix.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'}
mix.config('cfg').option('val4').value.reset()
mix.option('val4').value.set('new1')
assert mix.config('cfg').value.dict() == {'val3': 'yes', 'val2': 'new', 'val1': 'new', 'val5': 'yes', 'val4': 'new1'}
mix.option('val4').value.reset()
def test_mix_callback_follower():
val = StrOption('val', "", default='val')
val1 = StrOption('val1', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val)))
val3 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
val4 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
interface1 = Leadership('val1', '', [val1, val3, val4])
od = OptionDescription('root', '', [interface1])
maconfig = OptionDescription('rootconfig', '', [val, interface1])
cfg = Config(maconfig, session_id='cfg1')
mix = MixConfig(maconfig, [cfg])
mix.property.read_write()
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
mix.config('cfg1').option('val').value.set('val1')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val1'], 'val1.val1': ['val1'], 'val1.val3': ['val1'], 'val': 'val1'}
mix.config('cfg1').option('val').value.reset()
mix.option('val').value.set('val1')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val1'], 'val1.val1': ['val1'], 'val1.val3': ['val1'], 'val': 'val1'}
mix.option('val').value.reset()
mix.config('cfg1').option('val1.val2', 0).value.set('val2')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
mix.config('cfg1').option('val1.val2', 0).value.reset()
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
mix.option('val1.val2', 0).value.set('val2')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
mix.config('cfg1').option('val1.val3', 0).value.set('val6')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val'], 'val1.val3': ['val6'], 'val': 'val'}
mix.option('val1.val2', 0).value.reset()
mix.config('cfg1').option('val1.val3', 0).value.reset()
mix.config('cfg1').option('val1.val1').value.set(['val3'])
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val3'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
mix.config('cfg1').option('val1.val1').value.reset()
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val'], 'val1.val1': ['val'], 'val1.val3': ['val'], 'val': 'val'}
mix.option('val1.val1').value.set(['val3'])
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val3'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
mix.config('cfg1').option('val1.val2', 0).value.set('val2')
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val3'], 'val1.val3': ['val3'], 'val': 'val'}
mix.option('val1.val1').value.set(['val3', 'rah'])
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2', 'rah'], 'val1.val1': ['val3', 'rah'], 'val1.val3': ['val3', 'rah'], 'val': 'val'}
mix.option('val1.val1').value.pop(1)
mix.option('val1.val1').value.set(['val4'])
assert mix.config('cfg1').value.dict() == {'val1.val2': ['val2'], 'val1.val1': ['val4'], 'val1.val3': ['val4'], 'val': 'val'}
def test_meta_reset():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od0 = OptionDescription('root', '', [interface1])
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od1 = OptionDescription('root', '', [interface1])
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "mask", multi=True, properties=('hidden',))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od2 = OptionDescription('root', '', [interface1])
conf1 = Config(od0, session_id='conf1')
conf2 = Config(od1, session_id='conf2')
meta = MixConfig(od2, [conf1, conf2])
meta.property.read_write()
meta.owner.set('mix1')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
errors = meta.value.set('ip_admin_eth0.ip_admin_eth0', ['192.168.1.1'])
assert len(errors) == 0
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.1']
meta.value.reset('ip_admin_eth0.ip_admin_eth0')
assert meta.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf1').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
assert meta.config('conf2').option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_mix_properties_mix_copy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
mix = MixConfig(interface2, [conf1, conf2], session_id='mix1')
mix.property.read_write()
conf3 = mix.config('conf1').config.copy(session_id='conf3')
mix2 = conf3.config.metaconfig()
assert mix.config.name() == mix2.config.name()
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert mix.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
mix.option('ip_admin_eth0').value.set(['192.168.1.2'])
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert mix.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
ret = mix.value.set('ip_admin_eth0', ['192.168.1.3'], force_default_if_same=True)
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert mix.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
def test_mix_properties_mix_deepcopy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
mix = MixConfig(interface2, [conf1, conf2])
mix.permissive.set(frozenset({'hidden'}))
mix.property.read_write()
mix2 = mix.config('conf1').config.deepcopy(session_id='conf3')
assert mix != mix2
assert mix.permissive.get() == mix2.permissive.get()
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
assert mix2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
mix.option('ip_admin_eth0').value.set(['192.168.1.2'])
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.2']}
assert mix2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
mix.value.set('ip_admin_eth0', ['192.168.1.3'], force_default_if_same=True)
assert mix.config('conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.3']}
assert mix2.config('conf3').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
def test_mix_properties_submix_deepcopy():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True,
properties=('disabled',))
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf1.property.read_write()
mix1 = MixConfig(interface1, [conf1], session_id='mix1')
mix2 = MixConfig(interface2, [mix1], session_id='mix2')
mix_copy = conf1.config.deepcopy(session_id='conf2',
metaconfig_prefix='copy_')
assert mix_copy.config.name() == 'copy_mix2'
assert mix_copy.config('copy_mix1').config.name() == 'copy_mix1'
assert mix_copy.config('copy_mix1').config('conf2').config.name() == 'conf2'
def test_mix_properties_submix_deepcopy_owner():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip")
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth1', "mask")
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip")
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask")
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip")
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask")
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf1.owner.set('conf1_user')
conf1.property.read_write()
mix1 = MixConfig(interface1, [conf1], session_id='mix1')
mix1.owner.set('mix1_user')
mix2 = MixConfig(interface2, [mix1], session_id='mix2')
mix2.owner.set('mix2_user')
#
conf1.option('ip_admin_eth0').value.set('192.168.0.1')
assert conf1.option('ip_admin_eth0').owner.get() == 'conf1_user'
mix2.option('ip_admin_eth0').value.set('192.168.0.3')
assert mix2.option('ip_admin_eth0').owner.get() == 'mix2_user'
#
mix2_copy = conf1.config.deepcopy(session_id='conf2',
metaconfig_prefix='copy_')
mix2_copy.option('netmask_admin_eth0').value.set('255.255.255.255')
assert mix2_copy.option('ip_admin_eth0').value.get() == '192.168.0.3'
assert mix2_copy.option('ip_admin_eth0').owner.get() == 'mix2_user'
assert mix2_copy.option('netmask_admin_eth0').owner.get() == 'mix2_user'
#
mix1_copy = mix2_copy.config('copy_mix1')
mix1_copy.option('netmask_admin_eth0').value.set('255.255.255.255')
#
conf2 = mix1_copy.config('conf2')
conf2.owner.set('conf2_user')
conf2.option('netmask_admin_eth1').value.set('255.255.255.255')
assert conf2.option('netmask_admin_eth1').owner.get() == 'conf2_user'
assert conf2.option('ip_admin_eth0').value.get() == '192.168.0.1'
assert conf2.option('ip_admin_eth0').owner.get() == 'conf1_user'
def test_mix_properties_mix_set_value():
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth1', "mask", multi=True, properties=('disabled',))
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
netmask_admin_eth0 = NetmaskOption('netmask_admin_eth0', "mask", multi=True, properties=('disabled',))
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf2 = Config(interface1, session_id='conf2')
conf1.property.read_write()
conf2.property.read_write()
mix = MixConfig(interface2, [conf1, conf2])
mix.property.read_write()
assert mix.config('conf2').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
ret = mix.value.set('netmask_admin_eth0', ['255.255.255.255'], only_config=True)
assert len(ret) == 2
assert isinstance(ret[0], PropertiesOptionError)
assert isinstance(ret[1], AttributeError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('netmask_admin_eth0', ['255.255.255.255'], force_default=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], PropertiesOptionError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('netmask_admin_eth0', ['255.255.255.255'], force_dont_change_value=True)
assert len(ret) == 3
assert isinstance(ret[0], PropertiesOptionError)
assert isinstance(ret[1], AttributeError)
assert isinstance(ret[2], PropertiesOptionError)
del ret[2]
del ret[1]
del ret[0]
del ret
ret = mix.value.set('netmask_admin_eth0', ['255.255.255.255'], force_default_if_same=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], PropertiesOptionError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('ip_admin_eth0', '255.255.255.255', only_config=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], ValueError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('ip_admin_eth0', '255.255.255.255', force_default=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], ValueError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('ip_admin_eth0', '255.255.255.255', force_dont_change_value=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], ValueError)
del ret[1]
del ret[0]
del ret
ret = mix.value.set('ip_admin_eth0', '255.255.255.255', force_default_if_same=True)
assert len(ret) == 2
assert isinstance(ret[0], AttributeError)
assert isinstance(ret[1], ValueError)
del ret[1]
del ret[0]
del ret
def test_mix_different_default():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.2'])
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.3'])
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.4'])
ip_admin_eth1 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.5'])
interface3 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, ip_admin_eth1])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.6'])
interface4 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf1.property.read_write()
conf2 = Config(interface1, session_id='conf2')
conf2.property.read_write()
mix = MixConfig(interface2, [conf1, conf2], session_id='submix1')
mix = MixConfig(interface3, [mix], session_id='submix2')
mix = MixConfig(interface4, [mix])
mix.property.read_write()
#
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.6']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.4'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
#
mix.option('ip_admin_eth0').value.set(['192.168.1.7'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.7'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
#
mix.config('submix2').option('ip_admin_eth0').value.set(['192.168.1.8'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.8']}
#
raises(AttributeError, "mix.config('submix2.submix1').option('ip_admin_eth0').value.set(['192.168.1.9'])")
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.8']}
#
raises(AttributeError, "mix.config('submix2.submix1.conf2').option('ip_admin_eth0').value.set(['192.168.1.9'])")
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.8']}
#
mix.config('submix2.submix1.conf1').option('ip_admin_eth0').value.set(['192.168.1.9'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
raises(AttributeError, "mix.option('ip_admin_eth1').value.set(['192.168.1.10'])")
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
mix.config('submix2').option('ip_admin_eth1').value.set(['192.168.1.10'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
mix.config('submix2.submix1').option('ip_admin_eth1').value.set(['192.168.1.11'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
mix.config('submix2.submix1.conf2').option('ip_admin_eth1').value.set(['192.168.1.12'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.12']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
raises(AttributeError, "mix.config('submix2.submix1.conf1').option('ip_admin_eth1').value.set(['192.168.1.13'])")
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.12']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
def test_mix_different_default_reset():
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.1'])
interface0 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.2'])
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.3'])
interface2 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.4'])
ip_admin_eth1 = NetworkOption('ip_admin_eth1', "ip", multi=True, default=['192.168.1.5'])
interface3 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, ip_admin_eth1])
ip_admin_eth0 = NetworkOption('ip_admin_eth0', "ip", multi=True, default=['192.168.1.6'])
interface4 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0])
conf1 = Config(interface0, session_id='conf1')
conf1.property.read_write()
conf2 = Config(interface1, session_id='conf2')
conf2.property.read_write()
mix = MixConfig(interface2, [conf1, conf2], session_id='submix1')
mix = MixConfig(interface3, [mix], session_id='submix2')
mix = MixConfig(interface4, [mix])
mix.property.read_write()
#
mix.option('ip_admin_eth0').value.set(['192.168.1.7'])
mix.config('submix2').option('ip_admin_eth0').value.set(['192.168.1.8'])
mix.config('submix2').option('ip_admin_eth1').value.set(['192.168.1.10'])
mix.config('submix2.submix1').option('ip_admin_eth1').value.set(['192.168.1.11'])
mix.config('submix2.submix1.conf2').option('ip_admin_eth1').value.set(['192.168.1.12'])
mix.config('submix2.submix1.conf1').option('ip_admin_eth0').value.set(['192.168.1.9'])
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.7']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.8'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.12']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.9']}
#
mix.value.reset('ip_admin_eth0')
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.6']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.4'], 'ip_admin_eth1': ['192.168.1.10']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.11']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.12']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}
#
mix.value.reset('ip_admin_eth1')
assert mix.value.dict() == {'ip_admin_eth0': ['192.168.1.6']}
assert mix.config('submix2').value.dict() == {'ip_admin_eth0': ['192.168.1.4'], 'ip_admin_eth1': ['192.168.1.5']}
assert mix.config('submix2.submix1').value.dict() == {'ip_admin_eth1': ['192.168.1.3']}
assert mix.config('submix2.submix1.conf2').value.dict() == {'ip_admin_eth1': ['192.168.1.2']}
assert mix.config('submix2.submix1.conf1').value.dict() == {'ip_admin_eth0': ['192.168.1.1']}

View File

@ -1,229 +0,0 @@
"""these tests are here to create some :class:`tiramisu.option.Option`'s
and to compare them
"""
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.error import APIError, ConfigError
from tiramisu import IntOption, SymLinkOption, OptionDescription, Config
from tiramisu.setting import groups
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def a_func():
return None
def test_option_valid_name():
IntOption('test', '')
raises(ValueError, 'IntOption(1, "")')
# raises(ValueError, 'IntOption("1test", "")')
i = IntOption("test1", "")
# raises(ValueError, 'IntOption("_test", "")')
# raises(ValueError, 'IntOption(" ", "")')
raises(ValueError, 'SymLinkOption(1, i)')
i = SymLinkOption("test1", i)
def test_option_with_callback():
# no default value with callback
raises(ValueError, "IntOption('test', '', default=1, callback=a_func)")
def test_option_get_information():
description = "it's ok"
string = 'some informations'
i = IntOption('test', description)
raises(ValueError, "i.impl_get_information('noinfo')")
i.impl_set_information('info', string)
assert i.impl_get_information('info') == string
raises(ValueError, "i.impl_get_information('noinfo')")
assert i.impl_get_information('noinfo', 'default') == 'default'
assert i.impl_get_information('doc') == description
def test_option_get_information_config():
description = "it's ok"
string = 'some informations'
string
i = IntOption('test', description)
od = OptionDescription('od', '', [i])
Config(od)
raises(ValueError, "i.impl_get_information('noinfo')")
raises(AttributeError, "i.impl_set_information('info', string)")
# assert i.impl_get_information('info') == string
raises(ValueError, "i.impl_get_information('noinfo')")
assert i.impl_get_information('noinfo', 'default') == 'default'
assert i.impl_get_information('doc') == description
def test_option_get_information_config2():
description = "it's ok"
string = 'some informations'
i = IntOption('test', description)
i.impl_set_information('info', string)
od = OptionDescription('od', '', [i])
Config(od)
raises(ValueError, "i.impl_get_information('noinfo')")
raises(AttributeError, "i.impl_set_information('info', 'hello')")
assert i.impl_get_information('info') == string
raises(ValueError, "i.impl_get_information('noinfo')")
assert i.impl_get_information('noinfo', 'default') == 'default'
assert i.impl_get_information('doc') == description
def test_optiondescription_get_information():
description = "it's ok"
string = 'some informations'
o = OptionDescription('test', description, [])
o.impl_set_information('info', string)
assert o.impl_get_information('info') == string
raises(ValueError, "o.impl_get_information('noinfo')")
assert o.impl_get_information('noinfo', 'default') == 'default'
assert o.impl_get_information('doc') == description
def test_option_isoptiondescription():
i = IntOption('test', '')
od = OptionDescription('od', '', [i])
od = OptionDescription('od', '', [od])
cfg = Config(od)
assert cfg.option('od').option.isoptiondescription()
assert not cfg.option('od.test').option.isoptiondescription()
def test_option_multi():
IntOption('test', '', multi=True)
IntOption('test', '', multi=True, default_multi=1)
IntOption('test', '', default=[1], multi=True, default_multi=1)
#add default_multi to not multi's option
raises(ValueError, "IntOption('test', '', default_multi=1)")
#unvalid default_multi
raises(ValueError, "IntOption('test', '', multi=True, default_multi='yes')")
#not default_multi with callback
raises(ValueError, "IntOption('test', '', multi=True, default_multi=1, callback=a_func)")
def test_unknown_option():
i = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
# test is an option, not an optiondescription
raises(TypeError, "api.option('od.test.unknown').value.get()")
# unknown is an unknown option
raises(AttributeError, "api.option('unknown').value.get()")
# unknown is an unknown option
raises(AttributeError, "api.option('od.unknown').value.get()")
# unknown is an unknown optiondescription
raises(AttributeError, "api.option('od.unknown.suboption').value.get()")
def test_optiondescription_list():
groups.notfamily1 = groups.GroupType('notfamily1')
i = IntOption('test', '')
i2 = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
od1.impl_set_group_type(groups.family)
od3 = OptionDescription('od2', '', [i2])
od3.impl_set_group_type(groups.notfamily1)
od2 = OptionDescription('od', '', [od1, od3])
od4 = OptionDescription('od', '', [od2])
api = Config(od4)
assert len(list(api.option('od').list('option'))) == 0
assert len(list(api.option('od').list('optiondescription'))) == 2
assert len(list(api.option('od').list('optiondescription', group_type=groups.family))) == 1
assert len(list(api.option('od').list('optiondescription', group_type=groups.notfamily1))) == 1
assert len(list(api.option('od.od').list('option'))) == 1
assert len(list(api.option('od.od2').list('option'))) == 1
try:
list(api.option('od').list('unknown'))
except AssertionError:
pass
else:
raise Exception('must raise')
try:
list(api.option('od').list('option', group_type='toto'))
except AssertionError:
pass
else:
raise Exception('must raise')
def test_optiondescription_group():
groups.notfamily = groups.GroupType('notfamily')
i = IntOption('test', '')
i2 = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
od1.impl_set_group_type(groups.family)
od3 = OptionDescription('od2', '', [i2])
od3.impl_set_group_type(groups.notfamily)
od2 = OptionDescription('od', '', [od1, od3])
api = Config(od2)
assert len(list(api.option.list('option'))) == 0
assert len(list(api.option.list('optiondescription'))) == 2
assert len(list(api.option.list('optiondescription', group_type=groups.family))) == 1
assert len(list(api.option.list('optiondescription', group_type=groups.notfamily))) == 1
try:
list(api.option.list('unknown'))
except AssertionError:
pass
else:
raise Exception('must raise')
try:
list(api.option.list('option', group_type='toto'))
except AssertionError:
pass
else:
raise Exception('must raise')
def test_optiondescription_group_redefined():
try:
groups.notfamily = groups.GroupType('notfamily')
except:
pass
i = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
od1.impl_set_group_type(groups.family)
raises(ValueError, "od1.impl_set_group_type(groups.notfamily)")
def test_optiondescription_group_leadership():
i = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
raises(ConfigError, "od1.impl_set_group_type(groups.leadership)")
def test_asign_optiondescription():
i = IntOption('test', '')
od1 = OptionDescription('od', '', [i])
od2 = OptionDescription('od', '', [od1])
api = Config(od2)
raises(APIError, "api.option('od').value.set('test')")
raises(APIError, "api.option('od').value.reset()")
def test_intoption():
i1 = IntOption('test1', 'description', min_number=3)
i2 = IntOption('test2', 'description', max_number=3)
od = OptionDescription('od', '', [i1, i2])
cfg = Config(od)
raises(ValueError, "cfg.option('test1').value.set(2)")
cfg.option('test1').value.set(3)
cfg.option('test1').value.set(4)
cfg.option('test2').value.set(2)
cfg.option('test2').value.set(3)
raises(ValueError, "cfg.option('test2').value.set(4)")
def test_get_display_type():
i1 = IntOption('test1', 'description', min_number=3)
assert i1.get_display_type() == 'integer'

View File

@ -1,1196 +0,0 @@
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu import Config
from tiramisu.config import KernelConfig
from tiramisu.setting import groups, owners
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription, SymLinkOption, IPOption, NetmaskOption, Leadership, \
undefined, Params, ParamOption, ParamValue, ParamContext
from tiramisu.api import TIRAMISU_VERSION
from tiramisu.error import PropertiesOptionError, ConflictError, LeadershipError, ConfigError
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__)
def return_val():
return 'val'
def return_concat(*args):
return '.'.join(list(args))
def return_list(value=None):
return ['val', 'val']
def return_list2(*args):
l = []
for arg in args:
if isinstance(arg, list):
l.extend(arg)
else:
l.append(arg)
return l
def return_value(value=None):
return value
def return_value2(*args, **kwargs):
value = list(args)
value.extend(kwargs.values())
return value
def return_value3(value=None, index=None):
if index is not None and isinstance(value, list):
if len(value) > index:
return value[index]
return None
return value
def return_index(val1, val2=None, index=None, self=None):
if index is None:
return [val1, val2]
if index == 0:
return val1
if index == 1:
return val2
def return_calc(i, j, k):
return i + j + k
def is_config(config, **kwargs):
if isinstance(config, KernelConfig):
return 'yes'
else:
return 'no'
def ret_from_config(config):
api = Config(config)
return api.option('val1').value.get()
def return_raise(*arg):
raise Exception('test')
def return_valueerror(*arg):
raise ValueError('test')
def make_description_duplicates():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
## dummy 1
gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=({'option': boolop, 'expected': True, 'action': 'hidden'},))
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False,
requires=({'option': boolop, 'expected': True, 'action': 'hidden'},))
# dummy2 (same path)
gcdummy2 = BoolOption('dummy', 'dummy2', default=True)
# dummy3 (same name)
gcdummy3 = BoolOption('dummy', 'dummy2', default=True)
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, gcdummy2, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop, gcdummy3])
return descr
def test_identical_paths():
"""If in the schema (the option description) there is something that
have the same name, an exection is raised
"""
raises(ConflictError, "make_description_duplicates()")
def test_hidden_if_in():
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc",
requires=({'option': intoption, 'expected': 1, 'action': 'hidden'},))
descr = OptionDescription('constraints', '', [stroption, intoption])
api = Config(descr)
api.property.read_write()
assert not 'hidden' in api.option('str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('str').value.get()")
raises(PropertiesOptionError, "api.option('str').value.set('uvw')")
assert 'hidden' in api.unrestraint.option('str').property.get()
def test_hidden_if_in_with_group():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False)
floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc")
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption],
requires=({'option': intoption, 'expected': 1, 'action': 'hidden'},))
descr = OptionDescription('constraints', '', [gcgroup, booloption,
objspaceoption, stroption, intoption])
api = Config(descr)
api.property.read_write()
assert not 'hidden' in api.option('str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('gc.name').value.get()")
def test_disabled_with_group():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False)
floatoption = FloatOption('float', 'Test float option', default=2.3)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc")
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption],
requires=({'option': intoption, 'expected': 1, 'action': 'disabled'},))
descr = OptionDescription('constraints', '', [gcgroup, booloption,
objspaceoption, stroption, intoption])
api = Config(descr)
api.property.read_write()
assert api.option('gc.name').value.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('gc.name').value.get()")
#____________________________________________________________
def make_description_callback():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy')
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=({'option': boolop, 'expected': True, 'action': 'hidden'},))
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False,
requires=({'option': boolop, 'expected': True, 'action': 'hidden'},))
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('constraints', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop])
return descr
def test_has_callback():
descr = make_description_callback()
# here the owner is 'default'
api = Config(descr)
api.property.read_write()
api.option('bool').value.set(False)
# because dummy has a callback
api.property.add('freeze')
api.option('gc.dummy').property.add('frozen')
raises(PropertiesOptionError, "api.option('gc.dummy').value.set(True)")
def test_freeze_and_has_callback():
descr = make_description_callback()
api = Config(descr)
api.property.read_write()
api.option('bool').value.set(False)
api.property.add('freeze')
api.option('gc.dummy').property.add('frozen')
raises(PropertiesOptionError, "api.option('gc.dummy').value.set(True)")
def test_callback():
val1 = StrOption('val1', "", callback=return_val)
val2 = StrOption('val2', "")
maconfig = OptionDescription('rootconfig', '', [val1, val2])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').option.callbacks() != (None, None)
assert api.option('val2').option.callbacks() == (None, None)
assert api.option('val1').value.get() == 'val'
api.option('val1').value.set('new-val')
assert api.option('val1').value.get() == 'new-val'
api.option('val1').value.reset()
assert api.option('val1').value.get() == 'val'
def test_callback_params_without_callback():
raises(ValueError, "StrOption('val2', '', callback_params=Params(ParamValue('yes')))")
def test_params():
raises(ValueError, "Params([ParamContext()])")
raises(ValueError, "Params('str')")
raises(ValueError, "Params(('str',))")
raises(ValueError, "Params(kwargs=[ParamContext()])")
raises(ValueError, "Params(kwargs={'a': 'str'})")
def test_param_option():
val1 = StrOption('val1', "")
raises(ValueError, "ParamOption('str')")
raises(ValueError, "ParamOption(val1, 'str')")
def test_callback_invalid():
raises(AssertionError, 'val1 = StrOption("val1", "", callback="string")')
raises(AssertionError, 'val1 = StrOption("val1", "", callback=return_val, callback_params="string")')
val1 = StrOption('val1', "", 'val')
val1
raises(AssertionError, "StrOption('val2', '', callback=return_value, callback_params={'': 'string'})")
raises(AssertionError, "StrOption('val4', '', callback=return_value, callback_params={'value': (('string', False),)})")
raises(AssertionError, "StrOption('val4', '', callback=return_value, callback_params={'value': ((val1, 'string'),)})")
raises(AssertionError, "StrOption('val4', '', callback=return_value, callback_params={'value': ((val1, False, 'unknown'),)})")
raises(AssertionError, "StrOption('val4', '', callback=return_value, callback_params={'value': ((val1,),)})")
def test_callback_with_context():
context = ParamContext()
value = ParamValue('string')
params = Params((context,), {'value': value})
val1 = StrOption("val1", "", callback=is_config, callback_params=params)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
assert api.option('val1').value.get() == 'yes'
def test_callback_with_context_named():
context = ParamContext()
params = Params(kwargs={'config': context})
val1 = StrOption("val1", "", callback=is_config, callback_params=params)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
assert api.option('val1').value.get() == 'yes'
def test_callback_with_error():
val1 = StrOption("val1", "", callback=is_config, callback_params=Params(ParamValue('string'), kwargs={'value': ParamValue('string')}))
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
assert api.option('val1').value.get() == 'no'
def test_callback_with_context_value():
context = ParamContext()
params = Params((context,))
val1 = StrOption("val1", "")
val2 = StrOption("val2", "", callback=ret_from_config, callback_params=params)
maconfig = OptionDescription('rootconfig', '', [val1, val2])
api = Config(maconfig)
api.option('val1').value.set('yes')
assert api.option('val1').value.get() == 'yes'
assert api.option('val2').value.get() == 'yes'
api.option('val1').value.set('no')
assert api.option('val1').value.get() == 'no'
assert api.option('val2').value.get() == 'no'
def test_callback_value():
val1 = StrOption('val1', "", 'val')
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1)))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(ParamValue('yes')))
val4 = StrOption('val4', "", callback=return_value, callback_params=Params(kwargs={'value': ParamOption(val1)}))
val5 = StrOption('val5', "", callback=return_value, callback_params=Params(ParamValue('yes')))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4, val5])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == 'val'
assert api.option('val2').value.get() == 'val'
assert api.option('val4').value.get() == 'val'
api.option('val1').value.set('new-val')
assert api.option('val1').value.get() == 'new-val'
assert api.option('val2').value.get() == 'new-val'
assert api.option('val4').value.get() == 'new-val'
api.option('val1').value.reset()
assert api.option('val1').value.get() == 'val'
assert api.option('val2').value.get() == 'val'
assert api.option('val3').value.get() == 'yes'
assert api.option('val4').value.get() == 'val'
assert api.option('val5').value.get() == 'yes'
def test_callback_value_tuple():
val1 = StrOption('val1', "", 'val1')
val2 = StrOption('val2', "", 'val2')
val3 = StrOption('val3', "", callback=return_concat, callback_params=Params((ParamOption(val1), ParamOption(val2))))
val4 = StrOption('val4', "", callback=return_concat, callback_params=Params((ParamValue('yes'), ParamValue('no'))))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == 'val1'
assert api.option('val2').value.get() == 'val2'
assert api.option('val3').value.get() == 'val1.val2'
assert api.option('val4').value.get() == 'yes.no'
api.option('val1').value.set('new-val')
assert api.option('val3').value.get() == 'new-val.val2'
api.option('val1').value.reset()
assert api.option('val3').value.get() == 'val1.val2'
def test_callback_value_force_permissive():
val1 = StrOption('val1', "", 'val', properties=('disabled',))
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1)))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(ParamOption(val1, True)))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3])
api = Config(maconfig)
api.property.read_only()
raises(ConfigError, "api.option('val2').value.get()")
api.option('val3').value.get() is None
def test_callback_value_force_permissive_kwargs():
val1 = StrOption('val1', "", 'val', properties=('disabled',))
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(value=ParamOption(val1)))
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(value=ParamOption(val1, True)))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3])
api = Config(maconfig)
api.property.read_only()
raises(ConfigError, "api.option('val2').value.get()")
api.option('val3').value.get() is None
def test_callback_symlink():
val1 = StrOption('val1', "", 'val')
val2 = SymLinkOption('val2', val1)
val3 = StrOption('val3', "", callback=return_value, callback_params=Params(ParamOption(val2)))
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == 'val'
assert api.option('val2').value.get() == 'val'
assert api.option('val3').value.get() == 'val'
api.option('val1').value.set('new-val')
assert api.option('val1').value.get() == 'new-val'
assert api.option('val3').value.get() == 'new-val'
api.option('val1').value.reset()
assert api.option('val1').value.get() == 'val'
assert api.option('val3').value.get() == 'val'
def test_callback_list():
val1 = StrOption('val1', "", callback=return_list)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
api.property.read_write()
raises(ValueError, "api.option('val1').value.get()")
def test_callback_list2():
val1 = StrOption('val1', "", callback=return_list)
#val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1)))
val2 = StrOption('val2', "", callback=return_value, callback_params=Params(ParamOption(val1))) # , 'forcepermissive': False}]})
maconfig = OptionDescription('rootconfig', '', [val1, val2])
api = Config(maconfig)
api.property.read_write()
raises(ValueError, "api.option('val1').value.get()")
#cfg.val2
raises(ValueError, "api.option('val2').value.get()")
def test_callback_multi():
val1 = StrOption('val1', "", callback=return_val, multi=True)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == ['val']
api.option('val1').value.set(['new-val'])
assert api.option('val1').value.get() == ['new-val']
api.option('val1').value.set(['new-val', 'new-val2'])
assert api.option('val1').value.get() == ['new-val', 'new-val2']
api.option('val1').value.reset()
assert api.option('val1').value.get() == ['val']
def test_callback_multi_value():
val1 = StrOption('val1', "", ['val'], multi=True)
#val2 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
#val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamValue('yes')))
#val4 = StrOption('val4', "", multi=True, callback=return_list2, callback_params={'': ((val1, False), 'yes')})
option = ParamOption(val1)
params1 = Params((option,))
value = ParamValue('yes')
params2 = Params((value,))
params3 = Params((option, value))
val2 = StrOption('val2', "", multi=True, callback=return_value, callback_params=params1)
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=params2)
val4 = StrOption('val4', "", multi=True, callback=return_list2, callback_params=params3)
maconfig = OptionDescription('rootconfig', '', [val1, val2, val3, val4])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == ['val']
assert api.option('val2').value.get() == ['val']
assert api.option('val4').value.get() == ['val', 'yes']
api.option('val1').value.set(['new-val'])
assert api.option('val1').value.get() == ['new-val']
assert api.option('val2').value.get() == ['new-val']
assert api.option('val4').value.get() == ['new-val', 'yes']
api.option('val1').value.set(['new-val', 'new-val2'])
assert api.option('val1').value.get() == ['new-val', 'new-val2']
assert api.option('val2').value.get() == ['new-val', 'new-val2']
assert api.option('val4').value.get() == ['new-val', 'new-val2', 'yes']
api.option('val1').value.reset()
assert api.option('val1').value.get() == ['val']
assert api.option('val2').value.get() == ['val']
assert api.option('val3').value.get() == ['yes']
assert api.option('val4').value.get() == ['val', 'yes']
api.option('val2').value.set(['val', 'new'])
assert api.option('val1').value.get() == ['val']
assert api.option('val2').value.get() == ['val', 'new']
def test_callback_multi_list():
val1 = StrOption('val1', "", callback=return_list, multi=True)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == ['val', 'val']
api.option('val1').value.set(['new-val'])
assert api.option('val1').value.get() == ['new-val']
api.option('val1').value.set(['new-val', 'new-val2'])
assert api.option('val1').value.get() == ['new-val', 'new-val2']
api.option('val1').value.reset()
assert api.option('val1').value.get() == ['val', 'val']
def test_callback_multi_list_extend():
val1 = StrOption('val1', "", callback=return_list2, callback_params=Params((ParamValue(['1', '2', '3']), ParamValue(['4', '5']))), multi=True)
maconfig = OptionDescription('rootconfig', '', [val1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1').value.get() == ['1', '2', '3', '4', '5']
def test_callback_multi_callback():
val1 = StrOption('val1', "", multi=True, callback=return_val)
interface1 = OptionDescription('val1', '', [val1])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == ['val']
api.option('val1.val1').value.set(['val1', undefined])
assert api.option('val1.val1').value.get() == ['val1', 'val']
def test_callback_leader_and_followers_leader():
val1 = StrOption('val1', "", multi=True, callback=return_val)
val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == ['val']
api.option('val1.val1').value.set([undefined, undefined])
assert api.option('val1.val1').value.get() == ['val', 'val']
assert api.option('val1.val2', 0).value.get() == None
assert api.option('val1.val2', 1).value.get() == None
def test_callback_follower():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_value3, callback_params=Params(ParamValue(['string', 'new'])))
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('val1.val1').value.set(['val'])
assert api.option('val1.val2', 0).value.get() == 'string'
api.option('val1.val1').value.set(['val', 'val1'])
assert api.option('val1.val2', 0).value.get() == 'string'
assert api.option('val1.val2', 1).value.get() == 'new'
api.option('val1.val1').value.set(['val', 'val1', 'val2'])
assert api.option('val1.val2', 0).value.get() == 'string'
assert api.option('val1.val2', 1).value.get() == 'new'
assert api.option('val1.val2', 2).value.get() == None
api.option('val1.val1').value.set(['val', 'val1', 'val2', 'val3'])
assert api.option('val1.val2', 0).value.get() == 'string'
assert api.option('val1.val2', 1).value.get() == 'new'
assert api.option('val1.val2', 2).value.get() == None
assert api.option('val1.val2', 3).value.get() == None
def test_callback_leader_and_followers_leader2():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, default_multi='val2')
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val2)))
val4 = StrOption('val4', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val3)))
interface1 = Leadership('val1', '', [val1, val2, val3, val4])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('val1.val1').value.set(['val'])
assert api.option('val1.val4', 0).value.get() == 'val2'
assert api.option('val1.val3', 0).value.get() == 'val2'
assert api.option('val1.val2', 0).value.get() == 'val2'
def test_callback_leader_and_followers_leader_mandatory():
val = StrOption('val', "", default='val')
val1 = StrOption('val1', "", multi=True, callback=return_value2, callback_params=Params(ParamOption(val)), properties=('mandatory',))
val3 = StrOption('val3', "", multi=True, callback=return_index, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
val4 = StrOption('val4', "", multi=True, callback=return_index, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
interface1 = Leadership('val1', '', [val1, val3, val4])
maconfig = OptionDescription('rootconfig', '', [val, interface1])
api = Config(maconfig)
api.property.read_only()
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val1').value.get() == ['val']
api.property.read_write()
api.option('val1.val1').value.set([undefined, 'val3'])
api.property.read_only()
assert api.option('val1.val1').value.get() == ['val', 'val3']
assert api.option('val1.val3', 0).value.get() == 'val'
raises(PropertiesOptionError, "api.option('val1.val3', 1).value.get()")
raises(PropertiesOptionError, "api.option('val1.val4', 1).value.get()")
def test_callback_leader_and_followers_leader_mandatory2():
val = StrOption('val', "", default='val')
val_ = StrOption('val_', "", default='val_')
val1 = StrOption('val1', "", multi=True, callback=return_index, callback_params=Params(ParamOption(val), {'val2': ParamOption(val_)}), properties=('mandatory',))
val3 = StrOption('val3', "", multi=True, callback=return_index, callback_params=Params(ParamOption(val1), {'val2': ParamOption(val_)}), properties=('mandatory',))
val4 = StrOption('val4', "", multi=True, callback=return_index, callback_params=Params(ParamOption(val1), {'val2': ParamOption(val_)}), properties=('mandatory',))
interface1 = Leadership('val1', '', [val1, val3, val4])
maconfig = OptionDescription('rootconfig', '', [val, val_, interface1])
api = Config(maconfig)
api.property.read_only()
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val3', 1).value.get() == 'val_'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val4', 1).value.get() == 'val_'
assert api.option('val1.val1').value.get() == ['val', 'val_']
api.property.read_write()
api.option('val1.val1').value.set(['val', 'val_', 'val3'])
assert api.option('val1.val1').value.get() == ['val', 'val_', 'val3']
api.property.read_only()
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val3', 1).value.get() == 'val_'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val4', 1).value.get() == 'val_'
raises(PropertiesOptionError, "api.option('val1.val3', 2).value.get()")
raises(PropertiesOptionError, "api.option('val1.val4', 2).value.get()")
assert api.option('val1.val1').value.get() == ['val', 'val_', 'val3']
def test_callback_leader_and_followers_leader_mandatory3():
val = StrOption('val', "", default='val')
val_ = StrOption('val_', "", default='val_')
val1 = StrOption('val1', "", multi=True, callback=return_value2, callback_params=Params(ParamOption(val), {'val': ParamOption(val_)}), properties=('mandatory',))
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
val4 = StrOption('val4', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
interface1 = Leadership('val1', '', [val1, val3, val4])
maconfig = OptionDescription('rootconfig', '', [val, val_, interface1])
api = Config(maconfig)
api.property.read_only()
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val3', 1).value.get() == 'val_'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val4', 1).value.get() == 'val_'
assert api.option('val1.val1').value.get() == ['val', 'val_']
api.property.read_write()
api.option('val1.val1').value.set(['val', 'val_', 'val3'])
api.property.read_only()
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val3', 1).value.get() == 'val_'
assert api.option('val1.val3', 2).value.get() == 'val3'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val4', 1).value.get() == 'val_'
assert api.option('val1.val4', 2).value.get() == 'val3'
assert api.option('val1.val1').value.get() == ['val', 'val_', 'val3']
def test_callback_leader_and_followers_leader_mandatory4():
val = StrOption('val', "", default='val')
val1 = StrOption('val1', "", multi=True, callback=return_value2, callback_params=Params(ParamOption(val)), properties=('mandatory',))
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
val4 = StrOption('val4', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)), properties=('mandatory',))
interface1 = Leadership('val1', '', [val1, val3, val4])
maconfig = OptionDescription('rootconfig', '', [val, interface1])
api = Config(maconfig)
api.property.read_only()
#raises(IndexError, "api.option('val1.val3').value.get()")
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val1').value.get() == ['val']
api.property.read_write()
api.option('val1.val1').value.set(['val', 'val3'])
api.property.read_only()
assert api.option('val1.val1').value.get() == ['val', 'val3']
assert api.option('val1.val3', 0).value.get() == 'val'
assert api.option('val1.val3', 1).value.get() == 'val3'
assert api.option('val1.val4', 0).value.get() == 'val'
assert api.option('val1.val4', 1).value.get() == 'val3'
def test_callback_leader_and_followers_leader3():
val1 = StrOption('val1', "", multi=True, properties=('mandatory', 'empty'))
val2 = StrOption('val2', "", multi=True, default_multi='val2', properties=('expert',))
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val2)))
val4 = StrOption('val4', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val3)))
interface1 = Leadership('val1', '', [val1, val2, val3, val4])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert list(api.value.mandatory()) == ['val1.val1']
def test_callback_leader_and_followers_leader4():
val1 = StrOption('val1', "", ['val1'], multi=True, properties=('mandatory',))
val2 = StrOption('val2', "", multi=True, default_multi='val2', properties=('expert', 'mandatory'))
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val2)))
val4 = StrOption('val4', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val3)))
interface1 = Leadership('val1', '', [val1, val2, val3, val4])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.property.add('expert')
api.permissive.set(frozenset(['expert']))
assert list(api.value.mandatory()) == []
def test_consistency_leader_and_followers_leader_mandatory_transitive():
#default value
val1 = IPOption('val1', "", ['192.168.0.1'], multi=True, properties=('mandatory',))
val2 = NetmaskOption('val2', "", multi=True, default_multi='255.255.255.0', properties=('disabled', 'mandatory'))
val2.impl_add_consistency('ip_netmask', val1)
#no value
val3 = IPOption('val3', "", multi=True, properties=('mandatory',))
val4 = NetmaskOption('val4', "", multi=True, default_multi='255.255.255.0', properties=('disabled', 'mandatory'))
val4.impl_add_consistency('ip_netmask', val3)
interface1 = Leadership('val1', '', [val1, val2])
interface2 = Leadership('val3', '', [val3, val4])
maconfig = OptionDescription('rootconfig', '', [interface1, interface2])
api = Config(maconfig)
api.property.read_write()
try:
api.option('val1.val1').value.get()
except PropertiesOptionError as error:
assert str(error) == str(_('cannot access to {0} "{1}" because "{2}" has {3} {4}').format('option', 'val1', 'val2', 'property', '"disabled"'))
else:
raise Exception('must raises')
raises(PropertiesOptionError, "api.option('val3.val3').value.get()")
assert list(api.value.mandatory()) == []
def test_consistency_leader_and_followers_leader_mandatory_non_transitive():
#no value
val1 = IPOption('val1', "", multi=True, properties=('mandatory',))
val2 = NetmaskOption('val2', "", multi=True, default_multi='255.255.255.0', properties=('disabled', 'mandatory'))
val2.impl_add_consistency('ip_netmask', val1, transitive=False)
#default value
val3 = IPOption('val3', "", ['192.168.0.1'], multi=True, properties=('mandatory',))
val4 = NetmaskOption('val4', "", multi=True, default_multi='255.255.255.0', properties=('disabled', 'mandatory'))
val4.impl_add_consistency('ip_netmask', val3, transitive=False)
interface1 = Leadership('val1', '', [val1, val2])
interface2 = Leadership('val3', '', [val3, val4])
maconfig = OptionDescription('rootconfig', '', [interface1, interface2])
api = Config(maconfig)
api.property.read_write()
if TIRAMISU_VERSION == 2:
assert list(api.value.mandatory()) == ["val1.val1", "val1.val2"]
else:
assert list(api.value.mandatory()) == ["val1.val1"]
def test_callback_leader_and_followers_leader_list():
val1 = StrOption('val1', "", multi=True, callback=return_list)
val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == ['val', 'val']
assert api.option('val1.val2', 0).value.get() == None
assert api.option('val1.val2', 1).value.get() == None
api.option('val1.val1').value.set(['val', 'val', undefined])
assert api.option('val1.val1').value.get() == ['val', 'val', None]
assert api.option('val1.val2', 0).value.get() == None
assert api.option('val1.val2', 1).value.get() == None
assert api.option('val1.val2', 1).value.get() == None
api.option('val1.val1').value.reset()
assert api.option('val1.val1').value.get() == ['val', 'val']
assert api.option('val1.val2', 0).value.get() == None
assert api.option('val1.val2', 1).value.get() == None
api.option('val1.val1').value.pop(1)
assert api.option('val1.val1').value.get() == ['val']
assert api.option('val1.val2', 0).value.get() == None
def test_callback_leader_and_followers_leader_follower_list():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_list)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == []
api.option('val1.val1').value.set(['val1'])
raises(LeadershipError, "api.option('val1.val2', 0).value.get()")
def test_callback_leader_and_followers_follower():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_val)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == []
#
api.option('val1.val1').value.set(['val1'])
assert api.option('val1.val1').value.get() == ['val1']
assert api.option('val1.val2', 0).value.get() == 'val'
#
api.option('val1.val1').value.set(['val1', 'val2'])
assert api.option('val1.val1').value.get() == ['val1', 'val2']
assert api.option('val1.val2', 0).value.get() == 'val'
assert api.option('val1.val2', 1).value.get() == 'val'
#
api.option('val1.val1').value.set(['val1', 'val2', 'val3'])
assert api.option('val1.val1').value.get() == ['val1', 'val2', 'val3']
assert api.option('val1.val2', 0).value.get() == 'val'
assert api.option('val1.val2', 1).value.get() == 'val'
assert api.option('val1.val2', 2).value.get() == 'val'
#
api.option('val1.val1').value.pop(2)
assert api.option('val1.val1').value.get() == ['val1', 'val2']
assert api.option('val1.val2', 0).value.get() == 'val'
assert api.option('val1.val2', 1).value.get() == 'val'
#
api.option('val1.val2', 0).value.set('val2')
api.option('val1.val2', 1).value.set('val2')
assert api.option('val1.val2', 0).value.get() == 'val2'
assert api.option('val1.val2', 1).value.get() == 'val2'
#
api.option('val1.val1').value.set(['val1', 'val2', 'val3'])
assert api.option('val1.val2', 0).value.get() == 'val2'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val2', 2).value.get() == 'val'
def test_callback_leader_and_followers():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_val)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
def test_callback_leader_and_followers_follower_cal():
val3 = StrOption('val3', "", multi=True)
val1 = StrOption('val1', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val3)))
val2 = StrOption('val2', "", multi=True, callback=return_val)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1, val3])
api = Config(maconfig)
api.property.read_write()
#
assert api.option('val3').value.get() == []
assert api.option('val1.val1').value.get() == []
#
api.option('val1.val1').value.set(['val1'])
api.option('val3').value.set(['val1'])
assert api.option('val1.val1').value.get() == ['val1']
assert api.option('val1.val2', 0).value.get() == 'val'
#
api.option('val1.val1').value.reset()
api.option('val1.val2', 0).value.set('val')
#
api.option('val3').value.set(['val1', 'val2'])
assert api.option('val1.val2', 0).value.get() == 'val'
assert api.option('val1.val2', 1).value.get() == 'val'
assert api.option('val1.val1').value.get() == ['val1', 'val2']
# len of follower is higher than leader's one
api.option('val1.val2', 0).value.set('val1')
api.option('val1.val2', 1).value.set('val2')
api.option('val3').value.set(['val1'])
assert api.option('val1.val1').value.get() == ['val1']
raises(LeadershipError, "api.option('val1.val2', 0).value.get()")
#
api.option('val3').value.set(['val1', 'val2', 'val3'])
assert api.option('val1.val2', 0).value.get() == 'val1'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val2', 2).value.get() == 'val'
def test_callback_leader_and_followers_leader_disabled():
#properties must be transitive
val1 = StrOption('val1', "", ['val1'], multi=True, properties=('disabled',))
val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
raises(PropertiesOptionError, "api.option('val1.val1').value.get()")
raises(PropertiesOptionError, "api.option('val1.val1').value.set(['yes'])")
raises(PropertiesOptionError, "api.option('val1.val2', 0).value.get()")
def test_callback_leader_and_followers_leader_callback_disabled():
val0 = StrOption('val0', "", multi=True, properties=('disabled',))
val1 = StrOption('val1', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val0)))
val2 = StrOption('val2', "", multi=True)
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1, val0])
api = Config(maconfig)
api.property.read_write()
raises(ConfigError, "api.option('val1.val1').value.get()")
raises(ConfigError, "api.option('val1.val2').value.get()")
api.property.pop('disabled')
api.option('val1.val1').value.set([])
api.property.add('disabled')
assert api.option('val1.val1').value.get() == []
def test_callback_leader_and_followers_follower_disabled():
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, properties=('disabled',))
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == []
#raises(PropertiesOptionError, "api.option('val1.val2').value.get()")
api.option('val1.val1').value.set(['yes'])
assert api.option('val1.val1').value.get() == ['yes']
api.property.pop('disabled')
assert api.option('val1.val2', 0).value.get() == None
api.option('val1.val2', 0).value.set('no')
api.option('val1.val1').value.set(['yes', 'yes2', 'yes3'])
api.option('val1.val2', 2).value.set('no1')
assert api.option('val1.val2', 0).value.get() == 'no'
assert api.option('val1.val2', 1).value.get() == None
assert api.option('val1.val2', 2).value.get() == 'no1'
api.property.add('disabled')
api.option('val1.val1').value.pop(0)
assert api.option('val1.val1').value.get() == ['yes2', 'yes3']
api.property.pop('disabled')
assert api.option('val1.val2', 0).value.get() == None
assert api.option('val1.val2', 1).value.get() == 'no1'
def test_callback_leader_and_followers_follower_callback_disabled():
val0 = StrOption('val0', "", multi=True, properties=('disabled',))
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val0)))
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1, val0])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == []
api.option('val1.val1').value.set(['yes'])
assert api.option('val1.val1').value.get() == ['yes']
api.property.pop('disabled')
api.option('val1.val2', 0).value.set('no')
api.option('val1.val1').value.set(['yes', 'yes1'])
assert api.option('val1.val2', 0).value.get() == 'no'
api.property.add('disabled')
api.option('val1.val1').value.pop(1)
def test_callback_leader_and_followers_value():
val4 = StrOption('val4', '', multi=True, default=['val10', 'val11'])
val1 = StrOption('val1', "", multi=True)
val2 = StrOption('val2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val1)))
val3 = StrOption('val3', "", multi=True, callback=return_value, callback_params=Params(ParamValue('yes')))
val5 = StrOption('val5', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val4)))
val6 = StrOption('val6', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val5)))
interface1 = Leadership('val1', '', [val1, val2, val3, val5, val6])
maconfig = OptionDescription('rootconfig', '', [interface1, val4])
api = Config(maconfig)
api.property.read_write()
api.option('val4').value.get() == ['val10', 'val11']
assert api.option('val1.val1').value.get() == []
#raises(LeadershipError, "cfg.val1.val1")
#raises(LeadershipError, "cfg.val1.val2")
#raises(LeadershipError, "cfg.val1.val3")
#raises(LeadershipError, "cfg.val1.val5")
#raises(LeadershipError, "cfg.val1.val6")
#
#default calculation has greater length
#raises(LeadershipError, "api.option('val1.val1').value.set(['val1']")
#
api.option('val1.val1').value.set(['val1', 'val2'])
assert api.option('val1.val1').value.get() == ['val1', 'val2']
assert api.option('val1.val2', 0).value.get() == 'val1'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val3', 0).value.get() == 'yes'
assert api.option('val1.val3', 1).value.get() == 'yes'
raises(LeadershipError, "api.option('val1.val5', 0).value.get()")
raises(LeadershipError, "api.option('val1.val5', 1).value.get()")
raises(LeadershipError, "api.option('val1.val6', 0).value.get()")
raises(LeadershipError, "api.option('val1.val6', 1).value.get()")
#
api.option('val1.val1').value.set(['val1', 'val2', 'val3'])
assert api.option('val1.val1').value.get() == ['val1', 'val2', 'val3']
assert api.option('val1.val2', 0).value.get() == 'val1'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val2', 2).value.get() == 'val3'
assert api.option('val1.val3', 0).value.get() == 'yes'
assert api.option('val1.val3', 1).value.get() == 'yes'
assert api.option('val1.val3', 2).value.get() == 'yes'
raises(LeadershipError, "api.option('val1.val5', 2).value.get()")
raises(LeadershipError, "api.option('val1.val6', 2).value.get()")
#
api.option('val1.val1').value.pop(2)
assert api.option('val1.val1').value.get() == ['val1', 'val2']
assert api.option('val1.val2', 0).value.get() == 'val1'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val3', 0).value.get() == 'yes'
assert api.option('val1.val3', 1).value.get() == 'yes'
#
api.option('val1.val2', 0).value.set('val2')
api.option('val1.val2', 1).value.set('val2')
api.option('val1.val3', 0).value.set('val2')
api.option('val1.val3', 1).value.set('val2')
api.option('val1.val5', 0).value.set('val2')
api.option('val1.val5', 1).value.set('val2')
assert api.option('val1.val2', 0).value.get() == 'val2'
assert api.option('val1.val2', 1).value.get() == 'val2'
assert api.option('val1.val3', 0).value.get() == 'val2'
assert api.option('val1.val3', 1).value.get() == 'val2'
assert api.option('val1.val5', 0).value.get() == 'val2'
assert api.option('val1.val5', 1).value.get() == 'val2'
assert api.option('val1.val6', 0).value.get() == 'val2'
assert api.option('val1.val6', 1).value.get() == 'val2'
#
api.option('val1.val1').value.set(['val1', 'val2', 'val3'])
assert api.option('val1.val2', 2).value.get() == 'val3'
assert api.option('val1.val3', 2).value.get() == 'yes'
def test_callback_leader():
val2 = StrOption('val2', "", multi=True, callback=return_value)
val1 = StrOption('val1', "", multi=True, callback=return_value, callback_params=Params(ParamOption(val2)))
raises(ValueError, "Leadership('val1', '', [val1, val2])")
def test_callback_different_type():
val = IntOption('val', "", default=2)
val_ = IntOption('val_', "", default=3)
val1 = IntOption('val1', "", multi=True)
val2 = IntOption('val2', "", multi=True, callback=return_calc, callback_params=Params((ParamOption(val), ParamOption(val1)), {'k': ParamOption(val_)}))
interface1 = Leadership('val1', '', [val1, val2])
maconfig = OptionDescription('rootconfig', '', [interface1, val, val_])
api = Config(maconfig)
api.property.read_write()
assert api.option('val1.val1').value.get() == []
api.option('val1.val1').value.set([1])
assert api.option('val1.val1').value.get() == [1]
assert api.option('val1.val2', 0).value.get() == 6
api.option('val1.val1').value.set([1, 3])
assert api.option('val1.val1').value.get() == [1, 3]
assert api.option('val1.val2', 0).value.get() == 6
assert api.option('val1.val2', 1).value.get() == 8
api.option('val1.val1').value.set([1, 3, 5])
assert api.option('val1.val1').value.get() == [1, 3, 5]
assert api.option('val1.val2', 0).value.get() == 6
assert api.option('val1.val2', 1).value.get() == 8
assert api.option('val1.val2', 2).value.get() == 10
def test_callback_hidden():
opt1 = BoolOption('opt1', '')
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)))
od1 = OptionDescription('od1', '', [opt1], properties=('hidden',))
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od1.opt1').value.get()")
# do not raise, forcepermissive
api.option('od2.opt2').value.get()
def test_callback_hidden_permissive():
opt1 = BoolOption('opt1', '')
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)))
od1 = OptionDescription('od1', '', [opt1], properties=('hidden',))
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.permissive.set(frozenset(['hidden']))
api.property.read_write()
raises(PropertiesOptionError, "api.option('od1.opt1').value.get()")
api.option('od2.opt2').value.get()
def test_callback_hidden_permissive_callback():
opt1 = BoolOption('opt1', '')
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1, True)))
od1 = OptionDescription('od1', '', [opt1], properties=('hidden',))
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od1.opt1').value.get()")
api.option('od2.opt2').value.get()
def test_callback_two_disabled():
opt1 = BoolOption('opt1', '', properties=('disabled',))
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)), properties=('disabled',))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od2.opt2').value.get()")
def test_callback_two_disabled2():
opt1 = BoolOption('opt1', '', properties=('hidden',))
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)), properties=('hidden',))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
raises(PropertiesOptionError, "api.option('od2.opt2').value.get()")
assert api.forcepermissive.option('od2.opt2').owner.isdefault()
def test_callback_calculating_invalid():
opt1 = IntOption('opt1', '', 1)
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(ValueError, "api.option('od2.opt2').value.get()")
api.unrestraint.option('od2.opt2').property.add('disabled')
raises(PropertiesOptionError, "api.option('od2.opt2').value.get()")
def test_callback_calculating_disabled():
opt1 = BoolOption('opt1', '', properties=('disabled',))
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(ConfigError, "api.option('od2.opt2').value.get()")
def test_callback_calculating_mandatory():
opt1 = BoolOption('opt1', '', properties=('disabled',))
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)), properties=('mandatory',))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_only()
raises(ConfigError, "api.option('od2.opt2').value.get()")
def test_callback_calculating_mandatory_multi():
opt1 = BoolOption('opt1', '', multi=True, properties=('disabled',))
opt2 = BoolOption('opt2', '', multi=True, callback=return_value, callback_params=Params(ParamOption(opt1)), properties=('mandatory',))
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_only()
raises(ConfigError, "api.option('od2.opt2').value.get()")
def test_callback_two_disabled_multi():
opt1 = BoolOption('opt1', '', properties=('disabled',))
opt2 = BoolOption('opt2', '', callback=return_value, callback_params=Params(ParamOption(opt1)), properties=('disabled',), multi=True)
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od2.opt2').value.get()")
def test_callback_multi_list_params():
val1 = StrOption('val1', "", multi=True, default=['val1', 'val2'])
val2 = StrOption('val2', "", multi=True, callback=return_list, callback_params=Params(ParamOption(val1)))
oval2 = OptionDescription('val2', '', [val2])
maconfig = OptionDescription('rootconfig', '', [val1, oval2])
api = Config(maconfig)
api.property.read_write()
assert api.option('val2.val2').value.get() == ['val', 'val']
def test_callback_multi_list_params_key():
val1 = StrOption('val1', "", multi=True, default=['val1', 'val2'])
val2 = StrOption('val2', "", multi=True, callback=return_list, callback_params=Params(kwargs={'value': ParamOption(val1)}))
oval2 = OptionDescription('val2', '', [val2])
maconfig = OptionDescription('rootconfig', '', [val1, oval2])
api = Config(maconfig)
api.property.read_write()
assert api.option('val2.val2').value.get() == ['val', 'val']
def test_leadership_callback_description():
st1 = StrOption('st1', "", multi=True)
st2 = StrOption('st2', "", multi=True, callback=return_value, callback_params=Params(ParamOption(st1)))
stm = Leadership('st1', '', [st1, st2])
st = OptionDescription('st', '', [stm])
od = OptionDescription('od', '', [st])
od2 = OptionDescription('od', '', [od])
api = Config(od2)
owner = api.owner.get()
assert api.option('od.st.st1.st1').value.get() == []
assert api.option('od.st.st1.st1').owner.isdefault()
##
api.option('od.st.st1.st1').value.set(['yes'])
api.option('od.st.st1.st2', 0).value.set('yes')
assert api.option('od.st.st1.st1').owner.get() == owner
assert api.option('od.st.st1.st2', 0).owner.get() == owner
def test_callback_raise():
opt1 = BoolOption('opt1', 'Option 1', callback=return_raise)
opt2 = BoolOption('opt2', 'Option 2', callback=return_valueerror)
od1 = OptionDescription('od1', '', [opt1])
od2 = OptionDescription('od2', '', [opt2])
maconfig = OptionDescription('rootconfig', '', [od1, od2])
api = Config(maconfig)
api.property.read_write()
try:
api.option('od1.opt1').value.get()
except ConfigError as err:
assert '"Option 1"' in str(err)
try:
api.option('od2.opt2').value.get()
except ConfigError as err:
assert '"Option 2"' in str(err)

View File

@ -1,1043 +0,0 @@
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import owners, groups
from tiramisu import IPOption, NetworkOption, NetmaskOption, IntOption,\
BroadcastOption, StrOption, SymLinkOption, OptionDescription, submulti, Leadership,\
Config, undefined, Params, ParamOption
from tiramisu.error import ConfigError, ValueWarning, PropertiesOptionError
from tiramisu.api import TIRAMISU_VERSION
import warnings
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_consistency():
a = IntOption('a', '')
b = IntOption('b', '')
a.impl_add_consistency('not_equal', b)
#consistency to itself
raises(ConfigError, "a.impl_add_consistency('not_equal', a)")
def test_consistency_not_exists():
a = IntOption('a', '')
b = IntOption('b', '')
a, b
raises(ConfigError, "a.impl_add_consistency('not_exists', b)")
def test_consistency_unknown_params():
a = IntOption('a', '')
b = IntOption('b', '')
a, b
raises(ValueError, "a.impl_add_consistency('not_equal', b, unknown=False)")
def test_consistency_warnings_only_default():
a = IntOption('a', '', 1)
b = IntOption('b', '', 1)
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
a.impl_add_consistency('not_equal', b, warnings_only=True)
assert w != []
def test_consistency_warnings_only():
a = IntOption('a', '')
b = IntOption('b', '')
c = IntOption('c', '')
od = OptionDescription('od', '', [a, b, c])
a.impl_add_consistency('not_equal', b, warnings_only=True)
api = Config(od)
assert api.option('a').option.consistencies()
assert not api.option('b').option.consistencies()
assert not api.option('c').option.consistencies()
api.option('a').value.set(1)
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set(1)
assert w != []
def test_consistency_warnings_only_more_option():
a = IntOption('a', '')
b = IntOption('b', '')
d = IntOption('d', '')
od = OptionDescription('od', '', [a, b, d])
a.impl_add_consistency('not_equal', b, d, warnings_only=True)
api = Config(od)
api.option('a').value.set(1)
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set(1)
assert w != []
assert len(w) == 1
with warnings.catch_warnings(record=True) as w:
api.option('d').value.get()
assert w != []
assert len(w) == 1
with warnings.catch_warnings(record=True) as w:
api.option('d').value.set(1)
assert w != []
assert len(w) == 1
def test_consistency_warnings_only_option():
a = IntOption('a', '')
b = IntOption('b', '', warnings_only=True)
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
api.option('a').value.set(1)
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set(1)
assert w != []
api.option('a').value.reset()
api.option('b').value.set(1)
raises(ValueError, "api.option('a').value.set(1)")
#
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set(1)
assert len(w) == 1
def test_consistency_not_equal():
a = IntOption('a', '')
b = IntOption('b', '')
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
assert api.option('a').value.get() is None
assert api.option('b').value.get() is None
api.option('a').value.set(1)
api.option('a').value.reset()
api.option('a').value.set(1)
raises(ValueError, "api.option('b').value.set(1)")
api.option('b').value.set(2)
#
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set(1)
assert len(w) == 1
def test_consistency_not_equal_many_opts():
a = IntOption('a', '')
b = IntOption('b', '')
c = IntOption('c', '')
d = IntOption('d', '')
e = IntOption('e', '')
f = IntOption('f', '')
od = OptionDescription('od', '', [a, b, c, d, e, f])
a.impl_add_consistency('not_equal', b, c, d, e, f)
api = Config(od)
assert api.option('a').value.get() is None
assert api.option('b').value.get() is None
#
api.option('a').value.set(1)
api.option('a').value.reset()
#
api.option('a').value.set(1)
raises(ValueError, "api.option('b').value.set(1)")
#
api.option('b').value.set(2)
raises(ValueError, "api.option('f').value.set(2)")
raises(ValueError, "api.option('f').value.set(1)")
#
api.option('d').value.set(3)
raises(ValueError, "api.option('f').value.set(3)")
raises(ValueError, "api.option('a').value.set(3)")
api.option('d').value.set(3)
raises(ValueError, "api.option('c').value.set(3)")
raises(ValueError, "api.option('e').value.set(3)")
#
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('c').value.set(3)
assert len(w) == 1
with warnings.catch_warnings(record=True) as w:
api.option('e').value.set(3)
assert len(w) == 1
def test_consistency_not_equal_many_opts_one_disabled():
a = IntOption('a', '')
b = IntOption('b', '')
c = IntOption('c', '')
d = IntOption('d', '')
e = IntOption('e', '')
f = IntOption('f', '')
g = IntOption('g', '', properties=('disabled',))
od = OptionDescription('od', '', [a, b, c, d, e, f, g])
a.impl_add_consistency('not_equal', b, c, d, e, f, g, transitive=False)
api = Config(od)
api.property.read_write()
assert api.option('a').value.get() is None
assert api.option('b').value.get() is None
#
api.option('a').value.set(1)
api.option('a').value.reset()
#
api.option('a').value.set(1)
raises(ValueError, "api.option('b').value.set(1)")
#
api.option('b').value.set(2)
raises(ValueError, "api.option('f').value.set(2)")
raises(ValueError, "api.option('f').value.set(1)")
#
api.option('d').value.set(3)
raises(ValueError, "api.option('f').value.set(3)")
raises(ValueError, "api.option('a').value.set(3)")
raises(ValueError, "api.option('c').value.set(3)")
raises(ValueError, "api.option('e').value.set(3)")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('c').value.set(3)
assert len(w) == 1
def test_consistency_not_in_config_1():
a = IntOption('a', '')
b = IntOption('b', '')
a.impl_add_consistency('not_equal', b)
od1 = OptionDescription('od1', '', [a])
od = OptionDescription('root', '', [od1])
od
raises(ConfigError, "Config(od)")
def test_consistency_not_in_config_2():
a = IntOption('a', '')
b = IntOption('b', '')
a.impl_add_consistency('not_equal', b)
od1 = OptionDescription('od1', '', [a])
od2 = OptionDescription('od2', '', [b])
od = OptionDescription('root', '', [od1, od2])
Config(od)
def test_consistency_not_in_config_3():
a = IntOption('a', '')
b = IntOption('b', '')
a.impl_add_consistency('not_equal', b)
od1 = OptionDescription('od1', '', [a])
od2 = OptionDescription('od2', '', [b])
od = OptionDescription('root', '', [od1, od2])
od
#with subconfig
raises(ConfigError, "Config(od1)")
def test_consistency_after_config():
a = IntOption('a', '')
b = IntOption('b', '')
od1 = OptionDescription('od1', '', [a])
od2 = OptionDescription('od2', '', [b])
od = OptionDescription('root', '', [od1, od2])
Config(od)
raises(AttributeError, "a.impl_add_consistency('not_equal', b)")
def test_consistency_not_equal_symlink():
a = IntOption('a', '')
b = IntOption('b', '')
c = SymLinkOption('c', a)
od = OptionDescription('od', '', [a, b, c])
a.impl_add_consistency('not_equal', b)
api = Config(od)
assert set(od._cache_consistencies.keys()) == set([a, b])
def test_consistency_mix():
b = IntOption('b', '', multi=True)
c = IntOption('c', '', multi=True)
d = IntOption('d', '', multi=True)
od = Leadership('c', '', [c, d])
od2 = OptionDescription('a', '', [b, od])
c.impl_add_consistency('not_equal', b, d)
cfg = Config(od2)
cfg.option('b').value.set([1, 2, 3])
cfg.option('c.c').value.set([4, 5])
raises(ValueError, "cfg.option('c.c').value.set([1, 2])")
raises(ValueError, "cfg.option('c.d', 0).value.set(1)")
raises(ValueError, "cfg.option('c.d', 1).value.set(4)")
#
cfg.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
cfg.option('c.d', 1).value.set(4)
assert len(w) == 1
def test_consistency_not_equal_submulti():
a = IntOption('a', '', multi=submulti)
b = IntOption('b', '', multi=submulti)
od = OptionDescription('a', '', [a, b])
raises(ConfigError, 'a.impl_add_consistency("not_equal", b)')
def test_consistency_not_equal_default_submulti():
a = IntOption('a', '', [[1, 2]], multi=submulti)
b = IntOption('b', '', [[1]], multi=submulti)
od = OptionDescription('od', '', [a, b])
od
raises(ConfigError, "a.impl_add_consistency('not_equal', b)")
def test_consistency_not_equal_leadership():
a = IntOption('a', '', multi=True)
b = IntOption('b', '', multi=True)
od = Leadership('a', '', [a, b])
od2 = OptionDescription('b', '', [od])
a.impl_add_consistency('not_equal', b)
api = Config(od2)
assert api.option('a.a').value.get() == []
api.option('a.a').value.set([1])
api.option('a.a').value.reset()
api.option('a.a').value.set([1])
raises(ValueError, "api.option('a.b', 0).value.set(1)")
api.option('a.b', 0).value.set(2)
api.option('a.a').value.reset()
api.option('a.a').value.set([1])
api.value.dict()
def test_consistency_not_equal_leadership_error_multi1():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = NetmaskOption('c', '', multi=True)
od = Leadership('a', '', [a, b])
od2 = OptionDescription('b', '', [od, c])
c.impl_add_consistency('ip_netmask', a)
raises(ConfigError, "Config(od2)")
def test_consistency_not_equal_leadership_error_multi2():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = IPOption('c', '', multi=True)
od = Leadership('a', '', [a, b])
od2 = OptionDescription('b', '', [od, c])
b.impl_add_consistency('ip_netmask', c)
raises(ConfigError, "Config(od2)")
def test_consistency_ip_netmask_leadership_error_not_leader():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
od = OptionDescription('a', '', [a, b])
od2 = OptionDescription('b', '', [od])
b.impl_add_consistency('ip_netmask', a)
raises(ConfigError, "Config(od2)")
def test_consistency_ip_netmask_leadership_error_leader_and_not():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = IPOption('c', '', multi=True)
d = NetmaskOption('d', '', multi=True)
od = Leadership('a', '', [a, b])
od2 = OptionDescription('c', '', [c, d])
od3 = OptionDescription('b', '', [od, od2])
d.impl_add_consistency('ip_netmask', a)
raises(ConfigError, "Config(od3)")
def test_consistency_ip_netmask_leadership_error_otherleader():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = IPOption('c', '', multi=True)
d = NetmaskOption('d', '', multi=True)
od = Leadership('a', '', [a, b])
od2 = Leadership('c', '', [c, d])
od3 = OptionDescription('b', '', [od, od2])
d.impl_add_consistency('ip_netmask', a)
raises(ConfigError, "Config(od2)")
def test_consistency_not_equal_leadership_default():
a = IntOption('a', '', multi=True)
b = IntOption('b', '', multi=True, default_multi=1)
od = Leadership('a', '', [a, b])
od2 = OptionDescription('a', '', [od])
a.impl_add_consistency('not_equal', b)
api = Config(od2)
assert api.option('a.a').value.get() == []
raises(ValueError, "api.option('a.a').value.set([1])")
api.option('a.a').value.set([2])
api.option('a.a').value.reset()
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('a.a').value.set([1])
assert len(w) == 1
def test_consistency_not_equal_multi():
a = IntOption('a', '', multi=True)
b = IntOption('b', '', multi=True)
od = OptionDescription('a', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
assert api.option('a').value.get() == []
assert api.option('b').value.get() == []
api.option('a').value.set([1])
api.option('a').value.reset()
api.option('a').value.set([1])
raises(ValueError, "api.option('b').value.set([1])")
api.option('a').value.set([2])
raises(ValueError, "api.option('b').value.set([2, 1])")
api.option('a').value.set([2, 3])
raises(ValueError, "api.option('a').value.set([2, 3, 3])")
raises(ValueError, "api.option('b').value.set([2, 3])")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set([2, 3])
assert len(w) == 1
def test_consistency_not_equal_multi_default1():
a = IntOption('a', '', multi=True, default=[1])
b = IntOption('b', '', multi=True, default=[3, 1])
od = OptionDescription('a', '', [a, b])
raises(ValueError, "b.impl_add_consistency('not_equal', a)")
def test_consistency_not_equal_multi_default2():
a = IntOption('a', '', multi=True, default=[1])
b = IntOption('b', '', multi=True, default_multi=1)
od = OptionDescription('a', '', [a, b])
#default_multi not tested now
a.impl_add_consistency('not_equal', b)
def test_consistency_not_equal_leader_default():
a = IntOption('a', '', multi=True, default=[2, 1])
b = IntOption('b', '', multi=True, default_multi=1)
od = Leadership('a', '', [a, b])
a.impl_add_consistency('not_equal', b)
od2 = OptionDescription('a', '', [od])
api = Config(od2)
# default_multi not tested
raises(ValueError, "api.option('a.b', 0).value.get()")
api.option('a.b', 0).value.set(3)
api.option('a.b', 1).value.set(3)
assert api.option('a.b', 1).value.get() == 3
def test_consistency_not_equal_multi_default_modif():
a = IntOption('a', '', multi=True)
b = IntOption('b', '', multi=True, default=[1, 2])
od = OptionDescription('a', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
assert api.option('a').value.get() == []
assert api.option('b').value.get() == [1, 2]
raises(ValueError, "api.option('a').value.set([1])")
raises(ValueError, "api.option('b').value.set([1, 2, 1])")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set([1, 2, 1])
assert len(w) == 1
def test_consistency_default():
a = IntOption('a', '', 1)
b = IntOption('b', '', 1)
a, b
raises(ValueError, "a.impl_add_consistency('not_equal', b)")
def test_consistency_default_multi():
a = IntOption('a', '', [2, 1], multi=True)
b = IntOption('b', '', [1, 1], multi=True)
c = IntOption('c', '', [1, 2], multi=True)
b
raises(ValueError, "a.impl_add_consistency('not_equal', b)")
if TIRAMISU_VERSION != 2:
raises(ValueError, "a.impl_add_consistency('not_equal', c)")
def test_consistency_default_diff():
a = IntOption('a', '', 3)
b = IntOption('b', '', 1)
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
raises(ValueError, "api.option('a').value.set(1)")
api.option('a').value.set(2)
api.option('b').value.set(3)
owner = api.owner.get()
assert api.option('a').owner.get() == owner
raises(ValueError, "api.option('a').value.reset()")
assert api.option('a').owner.get() == owner
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('a').value.reset()
assert len(w) == 1
def test_consistency_ip_netmask():
a = IPOption('a', '')
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [a, b])
b.impl_add_consistency('ip_netmask', a)
api = Config(od)
api.option('a').value.set('192.168.1.1')
api.option('b').value.set('255.255.255.0')
api.option('a').value.set('192.168.1.2')
api.option('b').value.set('255.255.255.128')
api.option('b').value.set('255.255.255.0')
raises(ValueError, "api.option('a').value.set('192.168.1.0')")
raises(ValueError, "api.option('a').value.set('192.168.1.255')")
api.option('a').value.reset()
api.option('b').value.reset()
api.option('a').value.set('192.168.1.255')
raises(ValueError, "api.option('b').value.set('255.255.255.0')")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('b').value.set('255.255.255.0')
assert len(w) == 1
def test_consistency_ip_netmask_invalid():
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [b])
raises(ConfigError, "b.impl_add_consistency('ip_netmask')")
def test_consistency_network_netmask():
a = NetworkOption('a', '')
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [a, b])
b.impl_add_consistency('network_netmask', a)
api = Config(od)
api.option('a').value.set('192.168.1.1')
api.option('b').value.set('255.255.255.255')
api.option('b').value.reset()
api.option('a').value.set('192.168.1.0')
api.option('b').value.set('255.255.255.0')
raises(ValueError, "api.option('a').value.set('192.168.1.1')")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.1.1')
assert len(w) == 1
def test_consistency_network_netmask_invalid():
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [b])
raises(ConfigError, "b.impl_add_consistency('network_netmask')")
def test_consistency_ip_in_network():
a = NetworkOption('a', '')
b = NetmaskOption('b', '')
c = IPOption('c', '')
d = IPOption('d', '')
od = OptionDescription('od', '', [a, b, c, d])
c.impl_add_consistency('in_network', a, b)
d.impl_add_consistency('in_network', a, b, warnings_only=True)
warnings.simplefilter("always", ValueWarning)
api = Config(od)
api.option('a').value.set('192.168.1.0')
api.option('b').value.set('255.255.255.0')
api.option('c').value.set('192.168.1.1')
raises(ValueError, "api.option('c').value.set('192.168.2.1')")
raises(ValueError, "api.option('c').value.set('192.168.1.0')")
raises(ValueError, "api.option('c').value.set('192.168.1.255')")
with warnings.catch_warnings(record=True) as w:
api.option('d').value.set('192.168.2.1')
assert len(w) == 1
def test_consistency_ip_in_network_cidr():
a = NetworkOption('a', '', cidr=True)
c = IPOption('c', '')
d = IPOption('d', '')
od = OptionDescription('od', '', [a, c, d])
c.impl_add_consistency('in_network', a)
d.impl_add_consistency('in_network', a, warnings_only=True)
warnings.simplefilter("always", ValueWarning)
api = Config(od)
api.option('a').value.set('192.168.1.0/24')
api.option('c').value.set('192.168.1.1')
raises(ValueError, "api.option('c').value.set('192.168.2.1')")
raises(ValueError, "api.option('c').value.set('192.168.1.0')")
raises(ValueError, "api.option('c').value.set('192.168.1.255')")
with warnings.catch_warnings(record=True) as w:
api.option('d').value.set('192.168.2.1')
assert len(w) == 1
def test_consistency_ip_in_network_invalid():
a = NetworkOption('a', '')
b = NetmaskOption('b', '')
c = IPOption('c', '')
d = IPOption('d', '')
od = OptionDescription('od', '', [a, b, c, d])
raises(ConfigError, "c.impl_add_consistency('in_network', a)")
def test_consistency_ip_netmask_error_multi():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '')
OptionDescription('od', '', [a, b])
raises(ConfigError, "b.impl_add_consistency('ip_netmask', a)")
def test_consistency_ip_netmask_multi():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
od = Leadership('a', '', [a, b])
b.impl_add_consistency('ip_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.option('a.a').value.set(['192.168.1.1'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.a').value.set(['192.168.1.2'])
api.option('a.b', 0).value.set('255.255.255.128')
api.option('a.b', 0).value.set('255.255.255.0')
raises(ValueError, "api.option('a.a').value.set(['192.168.1.0'])")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('a.a').value.set(['192.168.1.0'])
assert len(w) == 1
def test_consistency_network_netmask_multi():
a = NetworkOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od', '', [od])
api = Config(od2)
api.option('a.a').value.set(['192.168.1.1'])
api.option('a.b', 0).value.set('255.255.255.255')
api.option('a.b', 0).value.reset()
api.option('a.a').value.set(['192.168.1.0'])
api.option('a.b', 0).value.set('255.255.255.0')
raises(ValueError, "api.option('a.a').value.set(['192.168.1.1'])")
def test_consistency_network_netmask_multi_follower_default_multi():
a = NetworkOption('a', '', default_multi=u'192.168.1.0', multi=True, properties=('mandatory',))
b = NetmaskOption('b', '', default_multi=u'255.255.255.0', multi=True, properties=('mandatory',))
od = Leadership('a', '', [a, b])
od2 = OptionDescription('od2', '', [od])
b.impl_add_consistency('network_netmask', a)
api = Config(od2)
api.property.read_write()
api.option('a.a').value.set([undefined])
assert api.option('a.a').value.get() == ['192.168.1.0']
assert api.option('a.b', 0).value.get() == '255.255.255.0'
def test_consistency_network_netmask_multi_follower_default():
a = NetworkOption('a', '', multi=True, properties=('mandatory',))
b = NetmaskOption('b', '', default_multi=u'255.255.255.0', multi=True, properties=('mandatory',))
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.property.read_write()
api.property.pop('cache')
assert api.option('a.a').value.get() == []
api.option('a.a').value.set(['192.168.1.0'])
api.property.read_only()
assert api.option('a.a').value.get() == [u'192.168.1.0']
assert api.option('a.b', 0).value.get() == u'255.255.255.0'
api.property.read_write()
raises(ValueError, "api.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1'])")
api.option('a.a').value.set(['192.168.1.0', undefined])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.b', 1).value.set('255.255.255.255')
api.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1'])
def return_netmask(*args, **kwargs):
return u'255.255.255.0'
def return_netmask2(leader):
if leader is not None:
if leader.endswith('2.1'):
return u'255.255.255.0'
if not leader.endswith('.0'):
return u'255.255.255.255'
return u'255.255.255.0'
def test_consistency_network_netmask_multi_follower_callback():
a = NetworkOption('a', '', multi=True, properties=('mandatory',))
b = NetmaskOption('b', '', callback=return_netmask, multi=True, properties=('mandatory',))
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.property.read_write()
api.property.pop('cache')
assert api.option('a.a').value.get() == []
api.option('a.a').value.set(['192.168.1.0'])
api.property.read_only()
assert api.option('a.a').value.get() == [u'192.168.1.0']
assert api.option('a.b', 0).value.get() == '255.255.255.0'
api.property.read_write()
raises(ValueError, "assert api.option('a.a').value.set([u'192.168.1.0', u'192.168.1.1'])")
api.option('a.a').value.set(['192.168.1.0', undefined])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.b', 1).value.set('255.255.255.255')
api.option('a.a').value.set(['192.168.1.0', '192.168.1.1'])
def test_consistency_network_netmask_multi_follower_callback_value():
a = NetworkOption('a', '', multi=True, properties=('mandatory',))
b = NetmaskOption('b', '', callback=return_netmask2, callback_params=Params(ParamOption(a)), multi=True, properties=('mandatory',))
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.property.read_write()
api.property.pop('cache')
assert api.option('a.a').value.get() == []
api.option('a.a').value.set(['192.168.1.0'])
assert api.option('a.a').value.get() == ['192.168.1.0']
assert api.option('a.b', 0).value.get() == '255.255.255.0'
raises(ValueError, "api.option('a.a').value.set(['192.168.1.0', '192.168.2.1'])")
assert api.option('a.a').value.get() == [u'192.168.1.0']
assert api.option('a.b', 0).value.get() == '255.255.255.0'
raises(ValueError, "api.option('a.a').value.set(['192.168.2.1'])")
assert api.option('a.a').value.get() == [u'192.168.1.0']
assert api.option('a.b', 0).value.get() == '255.255.255.0'
api.option('a.a').value.set(['192.168.1.0', '192.168.1.1'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.b', 1).value.set('255.255.255.255')
def test_consistency_ip_netmask_multi_leader():
a = IPOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
od = Leadership('a', '', [a, b])
b.impl_add_consistency('ip_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.option('a.a').value.set(['192.168.1.1'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.a').value.set(['192.168.1.2'])
api.option('a.b', 0).value.set('255.255.255.128')
api.option('a.b', 0).value.set('255.255.255.0')
raises(ValueError, "api.option('a.a').value.set(['192.168.1.0'])")
api.option('a.a').value.set(['192.168.1.128'])
raises(ValueError, "api.option('a.b', 0).value.set('255.255.255.128')")
api.option('a.a').value.set(['192.168.1.2', '192.168.1.3'])
def test_consistency_network_netmask_multi_leader():
a = NetworkOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.option('a.a').value.set(['192.168.1.1'])
api.option('a.b', 0).value.set('255.255.255.255')
api.option('a.b', 0).value.reset()
api.option('a.a').value.set(['192.168.1.0'])
api.option('a.b', 0).value.set('255.255.255.0')
raises(ValueError, "api.option('a.a').value.set(['192.168.1.1'])")
def test_consistency_broadcast():
a = NetworkOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = BroadcastOption('c', '', multi=True)
od = Leadership('a', '', [a, b, c])
b.impl_add_consistency('network_netmask', a)
c.impl_add_consistency('broadcast', a, b)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
#first, test network_netmask
api.option('a.a').value.set(['192.168.1.128'])
raises(ValueError, "api.option('a.a').value.set(['255.255.255.0'])")
#
api.option('a.a').value.set(['192.168.1.0'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.c', 0).value.set('192.168.1.255')
raises(ValueError, "api.option('a.a').value.set(['192.168.1.1'])")
#
api.option('a.a').value.set(['192.168.1.0', '192.168.2.128'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.b', 1).value.set('255.255.255.128')
api.option('a.c', 0).value.set('192.168.1.255')
api.option('a.c', 1).value.set('192.168.2.255')
raises(ValueError, "api.option('a.c', 1).value.set('192.168.2.128')")
api.option('a.c', 1).value.set('192.168.2.255')
def test_consistency_broadcast_error():
a = NetworkOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = BroadcastOption('c', '', multi=True)
od = Leadership('a', '', [a, b, c])
od2 = OptionDescription('od2', '', [od])
b.impl_add_consistency('network_netmask', a)
c.impl_add_consistency('broadcast', a)
api = Config(od2)
raises(ConfigError, "api.option('a.a').value.set(['192.168.1.0'])")
def test_consistency_broadcast_warnings():
warnings.simplefilter("always", ValueWarning)
a = NetworkOption('a', '', properties=('mandatory', 'disabled'))
b = NetmaskOption('b', '', properties=('mandatory', 'disabled'))
c = NetmaskOption('c', '', properties=('mandatory', 'disabled'))
od = OptionDescription('a', '', [a, b, c])
b.impl_add_consistency('network_netmask', a, warnings_only=True)
api = Config(od)
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.1.4')
api.option('b').value.set('255.255.255.0')
assert len(w) == 1
api.property.read_write()
with warnings.catch_warnings(record=True) as w:
list(api.value.mandatory())
assert len(w) == 0
def test_consistency_broadcast_default_1():
a = NetworkOption('a', '', '192.168.1.0')
b = NetmaskOption('b', '', '255.255.255.128')
c = BroadcastOption('c', '', '192.168.2.127')
od = OptionDescription('a', '', [a, b, c])
od
raises(ValueError, "c.impl_add_consistency('broadcast', a, b)")
def test_consistency_broadcast_default_2():
a = NetworkOption('a', '', '192.168.1.0')
b = NetmaskOption('b', '', '255.255.255.128')
d = BroadcastOption('d', '', '192.168.1.127')
od2 = OptionDescription('a', '', [a, b, d])
od2
d.impl_add_consistency('broadcast', a, b)
def test_consistency_not_all():
#_cache_consistencies is not None by not options has consistencies
a = NetworkOption('a', '', multi=True)
b = NetmaskOption('b', '', multi=True)
c = BroadcastOption('c', '', multi=True)
od = Leadership('a', '', [a, b, c])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.option('a.a').value.set(['192.168.1.0'])
api.option('a.b', 0).value.set('255.255.255.0')
api.option('a.c', 0).value.set('192.168.1.255')
def test_consistency_permissive():
a = IntOption('a', '', 1)
b = IntOption('b', '', 2, properties=('hidden',))
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
api.property.read_write()
api.permissive.set(frozenset(['hidden']))
api.option('a').value.set(1)
def test_consistency_disabled():
a = IntOption('a', '')
b = IntOption('b', '', properties=('disabled',))
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
api.property.read_write()
raises(PropertiesOptionError, "api.option('a').value.set(1)")
def test_consistency_disabled_transitive():
a = IntOption('a', '')
b = IntOption('b', '', properties=('disabled',))
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b, transitive=False)
api = Config(od)
api.property.read_write()
api.option('a').value.set(1)
def test_consistency_disabled_transitive_2():
a = IPOption('a', '')
b = IPOption('b', '')
c = NetworkOption('c', '', default='192.168.1.0')
d = NetmaskOption('d', '', default='255.255.255.0', properties=('disabled',))
od = OptionDescription('od', '', [a, b, c, d])
a.impl_add_consistency('not_equal', b)
a.impl_add_consistency('in_network', c, d, transitive=False)
api = Config(od)
api.property.read_write()
api.option('a').value.set('192.168.1.1')
raises(ValueError, "api.option('b').value.set('192.168.1.1')")
api.option('a').value.set('192.168.2.1')
#
api.option('a').value.set('192.168.1.1')
api.property.pop('disabled')
raises(ValueError, "api.option('a').value.set('192.168.2.1')")
#
api.property.add('demoting_error_warning')
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.2.1')
assert len(w) == 1
def return_val(*args, **kwargs):
return '192.168.1.1'
def test_consistency_with_callback():
a = NetworkOption('a', '', default='192.168.1.0')
b = NetmaskOption('b', '', default='255.255.255.0')
c = IPOption('c', '', callback=return_val, callback_params=Params(ParamOption(a)))
od = OptionDescription('od', '', [a, b, c])
c.impl_add_consistency('in_network', a, b)
api = Config(od)
api.option('c').value.get()
def test_consistency_warnings_only_options():
a = IPOption('a', '', warnings_only=True)
b = IPOption('b', '')
c = NetworkOption('c', '', default='192.168.1.0')
d = NetmaskOption('d', '', default='255.255.255.0', properties=('disabled',))
od = OptionDescription('od', '', [a, b, c, d])
a.impl_add_consistency('not_equal', b)
a.impl_add_consistency('in_network', c, d, transitive=False)
api = Config(od)
api.property.read_write()
api.option('a').value.set('192.168.1.1')
raises(ValueError, "api.option('b').value.set('192.168.1.1')")
api.option('a').value.set('192.168.2.1')
#
api.option('a').value.set('192.168.1.1')
api.property.pop('disabled')
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.2.1')
assert len(w) == 1
def test_consistency_warnings_only_options_callback():
a = IPOption('a', '', warnings_only=True)
b = IPOption('b', '')
c = NetworkOption('c', '', default='192.168.1.0')
d = NetmaskOption('d', '', callback=return_netmask2, callback_params=Params(ParamOption(c)))
od = OptionDescription('od', '', [a, b, c, d])
a.impl_add_consistency('not_equal', b)
a.impl_add_consistency('in_network', c, d, transitive=False)
api = Config(od)
api.property.read_write()
api.option('a').value.set('192.168.1.1')
raises(ValueError, "api.option('b').value.set('192.168.1.1')")
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.2.1')
assert len(w) == 1
#
api.option('a').value.set('192.168.1.1')
api.property.pop('disabled')
with warnings.catch_warnings(record=True) as w:
api.option('a').value.set('192.168.2.1')
assert len(w) == 1
def test_consistency_double_warnings():
a = IntOption('a', '')
b = IntOption('b', '', 1)
c = IntOption('c', '', 1)
od = OptionDescription('od', '', [a, b, c])
warnings.simplefilter("always", ValueWarning)
a.impl_add_consistency('not_equal', b, warnings_only=True)
a.impl_add_consistency('not_equal', c, warnings_only=True)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
with warnings.catch_warnings(record=True) as w:
api.option('od.a').value.set(1)
assert w != []
assert len(w) == 2
with warnings.catch_warnings(record=True) as w:
api.option('od.c').value.set(2)
assert len(w) == 0
with warnings.catch_warnings(record=True) as w:
api.option('od.a').value.set(2)
assert w != []
assert len(w) == 1
api.property.pop('warnings')
with warnings.catch_warnings(record=True) as w:
api.option('od.a').value.set(1)
assert w == []
def test_consistency_warnings_error():
a = IntOption('a', '')
b = IntOption('b', '', 1)
c = IntOption('c', '', 1)
od = OptionDescription('od', '', [a, b, c])
warnings.simplefilter("always", ValueWarning)
a.impl_add_consistency('not_equal', b, warnings_only=True)
a.impl_add_consistency('not_equal', c)
api = Config(od)
with warnings.catch_warnings(record=True) as w:
raises(ValueError, "api.option('a').value.set(1)")
assert w == []
def test_consistency_network_netmask_mandatory():
a = NetworkOption('a', '', multi=True, properties=('mandatory',), default=[u'0.0.0.0'])
b = NetmaskOption('b', '', multi=True, properties=('mandatory',), default_multi=u'0.0.0.0')
od = Leadership('a', '', [a, b])
b.impl_add_consistency('network_netmask', a)
od2 = OptionDescription('od2', '', [od])
api = Config(od2)
api.property.read_only()
api.property.pop('mandatory')
api.value.dict()
def test_consistency_has_dependency():
a = IPOption('a', '')
b = NetmaskOption('b', '')
od = OptionDescription('od', '', [a, b])
b.impl_add_consistency('ip_netmask', a)
api = Config(od)
assert api.option('a').option.has_dependency() is True
assert api.option('b').option.has_dependency() is True
assert api.option('a').option.has_dependency(False) is True
assert api.option('b').option.has_dependency(False) is True
def test_consistency_not_equal_has_dependency():
a = IntOption('a', '')
b = IntOption('b', '')
od = OptionDescription('od', '', [a, b])
a.impl_add_consistency('not_equal', b)
api = Config(od)
assert api.option('a').option.has_dependency() is False
assert api.option('b').option.has_dependency() is False
assert api.option('a').option.has_dependency(False) is True
assert api.option('b').option.has_dependency(False) is True

View File

@ -1,216 +0,0 @@
"test all types of option default values for options, add new option in a descr"
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import owners
from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu import IntOption, FloatOption, StrOption, ChoiceOption, \
BoolOption, OptionDescription, Leadership, Config, undefined
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)
objspaceoption = ChoiceOption('objspace', 'Object space',
['std', 'thunk'], 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=['boolop'])
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False,
requires=['boolop'])
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiramisu', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop])
return descr
#____________________________________________________________
# default values
def test_default_is_none():
"""
Most constructors take a ``default`` argument that specifies the default
value of the option. If this argument is not supplied the default value is
assumed to be ``None``.
"""
dummy1 = BoolOption('dummy1', 'doc dummy')
dummy2 = BoolOption('dummy2', 'doc dummy')
group = OptionDescription('group', '', [dummy1, dummy2])
api = Config(group)
# so when the default value is not set, there is actually a default value
assert api.option('dummy1').value.get() is None
assert api.option('dummy2').value.get() is None
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
def test_force_default_on_freeze():
"a frozen option wich is forced returns his default"
dummy1 = BoolOption('dummy1', 'doc dummy', default=False, properties=('force_default_on_freeze',))
dummy2 = BoolOption('dummy2', 'doc dummy', default=True)
group = OptionDescription('group', '', [dummy1, dummy2])
api = Config(group)
api.property.read_write()
owner = api.owner.get()
api.option('dummy1').value.set(True)
api.option('dummy2').value.set(False)
assert api.option('dummy1').owner.get() == owner
assert api.option('dummy2').owner.get() == owner
api.option('dummy1').property.add('frozen')
api.option('dummy2').property.add('frozen')
assert api.option('dummy1').value.get() is False
assert api.option('dummy2').value.get() is False
assert api.option('dummy1').owner.isdefault()
assert api.option('dummy2').owner.get() == owner
raises(PropertiesOptionError, "api.option('dummy2').owner.set('frozen')")
raises(PropertiesOptionError, "api.option('dummy1').value.reset()")
api.option('dummy1').property.pop('frozen')
api.option('dummy1').value.reset()
api.option('dummy1').property.add('frozen')
raises(PropertiesOptionError, "api.option('dummy2').owner.set('frozen')")
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])
api = Config(group)
api.property.read_write()
api.option('dummy1').value.set([undefined, True])
api.option('dummy2').value.set([undefined, False])
owner = api.owner.get()
assert api.option('dummy1').owner.get() == owner
assert api.option('dummy2').owner.get() == owner
api.option('dummy1').property.add('frozen')
api.option('dummy2').property.add('frozen')
assert api.option('dummy1').value.get() == [False]
assert api.option('dummy2').value.get() == [True, False]
assert api.option('dummy1').owner.isdefault()
assert api.option('dummy2').owner.get() == owner
raises(PropertiesOptionError, "api.option('dummy2').owner.set('owner')")
raises(PropertiesOptionError, "api.option('dummy2').value.reset()")
api.option('dummy1').property.pop('frozen')
api.option('dummy1').value.reset()
api.option('dummy1').property.add('frozen')
def test_force_default_on_freeze_leader():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze',))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr])
raises(ConfigError, "Config(descr)")
def test_force_metaconfig_on_freeze_leader():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze',))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr])
raises(ConfigError, "Config(descr)")
def test_force_default_on_freeze_leader_frozen():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_default_on_freeze', 'frozen'))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr])
api = Config(descr)
raises(ConfigError, "api.option('dummy1.dummy1').property.pop('frozen')")
def test_force_metaconfig_on_freeze_leader_frozen():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True, properties=('force_metaconfig_on_freeze', 'frozen'))
dummy2 = BoolOption('dummy2', 'Test string option', multi=True)
descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr])
api = Config(descr)
raises(ConfigError, "api.option('dummy1.dummy1').property.pop('frozen')")
def test_force_default_on_freeze_follower():
dummy1 = BoolOption('dummy1', 'Test int option', multi=True)
dummy2 = BoolOption('dummy2', 'Test string option', multi=True, properties=('force_default_on_freeze',))
descr = Leadership("dummy1", "", [dummy1, dummy2])
descr = OptionDescription("root", "", [descr])
api = Config(descr)
api.property.read_write()
owners.addowner("frozenmultifollower2")
api.option('dummy1.dummy1').value.set([True])
api.option('dummy1.dummy2', 0).value.set(False)
assert api.option('dummy1.dummy1').value.get() == [True]
assert api.option('dummy1.dummy2', 0).value.get() == False
assert api.option('dummy1.dummy1').owner.get() == 'user'
assert api.option('dummy1.dummy2', 0).owner.get() == 'user'
#
api.option('dummy1.dummy2').property.add('frozen')
assert api.option('dummy1.dummy1').value.get() == [True]
assert api.option('dummy1.dummy2', 0).value.get() == None
assert api.option('dummy1.dummy1').owner.get() == 'user'
assert api.option('dummy1.dummy2', 0).owner.isdefault()
raises(PropertiesOptionError, "api.option('dummy1.dummy2', 0).owner.set('frozenmultifollower2')")
#
api.option('dummy1.dummy2').property.pop('frozen')
api.option('dummy1.dummy1').value.set([True, True])
api.option('dummy1.dummy2', 1).value.set(False)
assert api.option('dummy1.dummy1').value.get() == [True, True]
assert api.option('dummy1.dummy2', 0).value.get() == False
assert api.option('dummy1.dummy2', 1).value.get() == False
#
api.option('dummy1.dummy2').property.add('frozen')
assert api.option('dummy1.dummy1').value.get() == [True, True]
assert api.option('dummy1.dummy2', 0).value.get() == None
assert api.option('dummy1.dummy2', 1).value.get() == None
#
api.option('dummy1.dummy1').value.pop(1)
assert api.option('dummy1.dummy1').value.get() == [True]
assert api.option('dummy1.dummy2', 0).value.get() == None
#
api.option('dummy1.dummy2').property.pop('frozen')
assert api.option('dummy1.dummy1').value.get() == [True]
assert api.option('dummy1.dummy2', 0).value.get() == False
#
api.option('dummy1.dummy1').value.set([True, True])
assert api.option('dummy1.dummy2', 0).value.get() == False
assert api.option('dummy1.dummy2', 1).value.get() == None
def test_overrides_changes_option_value():
"with config.override(), the default is changed and the value is changed"
descr = OptionDescription("test", "", [
BoolOption("b", "", default=False)])
api = Config(descr)
api.option('b').value.set(True)
def test_choice_with_no_default():
descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"))])
api = Config(descr)
assert api.option('backend').value.get() is None
api.option('backend').value.set('c')
def test_choice_with_default():
descr = OptionDescription("test", "", [
ChoiceOption("backend", "", ("c", "cli"), default="cli")])
api = Config(descr)
assert api.option('backend').value.get() == 'cli'

View File

@ -1,184 +0,0 @@
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.setting import owners, groups
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
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)
objspaceoption = ChoiceOption('objspace', 'Object space',
['std', 'thunk'], 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False)
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False)
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiram', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop])
return descr
def test_default_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
api.option('dummy').value.set(True)
owner = api.owner.get()
assert api.option('dummy').owner.get() == owner
def test_hidden_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('hidden',))
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
api.property.read_write()
#raises(PropertiesOptionError, "api.forcepermissive.option('dummy').owner.get()")
#raises(PropertiesOptionError, "api.option('dummy').owner.isdefault()")
#raises(PropertiesOptionError, "api.forcepermissive.option('dummy').owner.isdefault()")
api.permissive.set(frozenset(['hidden']))
api.forcepermissive.option('dummy').value.get()
api.forcepermissive.option('dummy').owner.isdefault()
def test_addowner():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
assert api.option('dummy').owner.isdefault()
api.owner.set('gen_config')
api.option('dummy').value.set(True)
assert api.option('dummy').owner.get() == owners.gen_config
assert not api.option('dummy').owner.isdefault()
def test_addowner_multiple_time():
owners.addowner("testowner2")
raises(ConstError, 'owners.addowner("testowner2")')
def test_delete_owner():
owners.addowner('deleted2')
raises(ConstError, 'del(owners.deleted2)')
def test_owner_is_not_a_string():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == owners.default
assert api.option('dummy').owner.get() == 'default'
assert isinstance(api.option('dummy').owner.get(), owners.Owner)
api.option('dummy').value.set(True)
assert api.option('dummy').owner.get() == 'user'
def test_setowner_without_valid_owner():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
def test_setowner_for_value():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
owners.addowner("new2")
raises(ConfigError, "api.option('dummy').owner.set('new2')")
api.option('dummy').value.set(False)
assert api.option('dummy').owner.get() == owners.user
api.option('dummy').owner.set('new2')
assert api.option('dummy').owner.get() == owners.new2
def test_setowner_forbidden():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
raises(ValueError, "api.owner.set('default')")
api.option('dummy').value.set(False)
raises(ValueError, "api.option('dummy').owner.set('default')")
def test_setowner_read_only():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr = OptionDescription('tiramisu', '', [gcdummy])
api = Config(descr)
api.property.read_write()
assert api.option('dummy').value.get() is False
assert api.option('dummy').owner.get() == 'default'
owners.addowner("readonly2")
api.option('dummy').value.set(False)
assert api.option('dummy').owner.get() == owners.user
api.property.read_only()
raises(PropertiesOptionError,
"api.option('dummy').owner.set('readonly2')")
assert api.option('dummy').owner.get() == owners.user
def test_setowner_optiondescription():
gcdummy = BoolOption('dummy', 'dummy', default=False)
descr1 = OptionDescription('tiramisu', '', [gcdummy])
descr = OptionDescription('tiramisu', '', [descr1])
api = Config(descr)
raises(APIError, "api.option('tiramisu').owner.get()")
raises(APIError, "api.option('tiramisu').owner.set('user')")
def test_setowner_symlinkoption():
gcdummy = BoolOption('dummy', 'dummy', default=False)
s = SymLinkOption('symdummy', gcdummy)
descr1 = OptionDescription('tiramisu', '', [gcdummy, s])
descr = OptionDescription('tiramisu', '', [descr1])
api = Config(descr)
assert api.option('tiramisu.symdummy').owner.isdefault()
api.option('tiramisu.dummy').value.set(True)
assert not api.option('tiramisu.symdummy').owner.isdefault()
raises(ConfigError, "api.option('tiramisu.symdummy').owner.set('user')")
def test_owner_leadership():
b = IntOption('int', 'Test int option', default=[0], multi=True)
c = StrOption('str', 'Test string option', multi=True)
descr = Leadership("int", "", [b, c])
od = OptionDescription('od', '', [descr])
api = Config(od)
raises(ConfigError, "api.option('int.str', 0).owner.set('user')")
api.option('int.int').value.set([0, 1])
api.option('int.str', 0).value.set('yes')
assert not api.option('int.str', 0).owner.isdefault()
assert api.option('int.str', 1).owner.isdefault()
api.option('int.str', 0).owner.set('user')
assert api.option('int.str', 0).owner.get() == owners.user
assert api.option('int.str', 1).owner.isdefault()
assert api.option('int.str', 0).value.get() == 'yes'
assert api.option('int.str', 1).value.get() == None

View File

@ -1,666 +0,0 @@
"config.set() or config.setoption() or option.setoption()"
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.i18n import _
from tiramisu.error import display_list, ConfigError
from tiramisu.setting import owners, groups
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
StrOption, OptionDescription, Leadership, Config, undefined
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__)
def make_description():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False)
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), 'std')
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
boolop = BoolOption('boolop', 'Test boolean option op', default=True)
wantref_option = BoolOption('wantref', 'Test requires', default=False)
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False)
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('tiramisu', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption, boolop])
return descr
#____________________________________________________________
# change with __setattr__
def test_attribute_access():
"Once set, option values can't be changed again by attribute access"
s = StrOption("string", "", default="string")
descr = OptionDescription("options", "", [s])
api = Config(descr)
# let's try to change it again
api.option('string').value.set('foo')
assert api.option('string').value.get() == 'foo'
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 = Config(descr)
config2 = Config(descr)
assert config.property.getdefault() == {'cache', 'validator', 'warnings'}
assert config.property.getdefault('read_only', 'append') == {'frozen',
'disabled',
'validator',
'everything_frozen',
'mandatory',
'empty',
'force_store_value'}
assert config.property.getdefault('read_only', 'remove') == {'permissive',
'hidden'}
assert config.property.getdefault('read_write', 'append') == {'frozen',
'disabled',
'validator',
'hidden',
'force_store_value'}
assert config.property.getdefault('read_write', 'remove') == {'permissive',
'everything_frozen',
'mandatory',
'empty'}
#
config.property.setdefault({'cache'})
config.property.setdefault(type='read_only', when='append', properties={'disabled'})
config.property.setdefault(type='read_only', when='remove', properties={'hidden'})
config.property.setdefault(type='read_write', when='append', properties={'disabled',
'hidden'})
config.property.setdefault(type='read_write', when='remove', properties=set([]))
raises(ValueError, "config.property.setdefault(type='unknown', when='append', properties={'disabled'})")
raises(ValueError, "config.property.setdefault(type='read_only', when='unknown', properties={'disabled'})")
raises(TypeError, "config.property.setdefault(type='read_only', when='append', properties=['disabled'])")
assert config.property.getdefault() == {'cache'}
assert config.property.getdefault('read_only', 'append') == {'disabled'}
assert config.property.getdefault('read_only', 'remove') == {'hidden'}
assert config.property.getdefault('read_write', 'append') == {'disabled',
'hidden'}
assert config.property.getdefault('read_write', 'remove') == set([])
#
config.property.read_only()
assert config.property.get() == {'cache', 'disabled'}
config.property.read_write()
assert config.property.get() == {'cache', 'disabled', 'hidden'}
config.property.read_only()
assert config.property.get() == {'cache', 'disabled'}
#
assert config2.property.getdefault() == {'cache', 'validator', 'warnings'}
assert config2.property.getdefault('read_only', 'append') == {'frozen',
'disabled',
'validator',
'everything_frozen',
'mandatory',
'empty',
'force_store_value'}
assert config2.property.getdefault('read_only', 'remove') == {'permissive',
'hidden'}
assert config2.property.getdefault('read_write', 'append') == {'frozen',
'disabled',
'validator',
'hidden',
'force_store_value'}
assert config2.property.getdefault('read_write', 'remove') == {'permissive',
'everything_frozen',
'mandatory',
'empty'}
raises(ValueError, "config2.property.getdefault('unknown', 'remove')")
raises(ValueError, "config2.property.getdefault('read_write', 'unknown')")
def test_setitem():
s = StrOption("string", "", default=["string", "sdfsdf"], default_multi="prout", multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('string').value.set([undefined, 'foo'])
assert api.option('string').value.get() == ['string', 'foo']
def test_reset():
"if value is None, resets to default owner"
s = StrOption("string", "", default="string")
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('string').value.set('foo')
assert api.option('string').value.get() == "foo"
assert api.option('string').owner.get() ==owners.user
api.option('string').value.reset()
assert api.option('string').value.get() == 'string'
assert api.option('string').owner.get() ==owners.default
def test_reset_with_multi():
s = StrOption("string", "", default=["string"], default_multi="string", multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
# api.option('string').value.set([])
api.option('string').value.reset()
assert api.option('string').value.get() == ["string"]
assert api.option('string').owner.get() =='default'
api.option('string').value.set(["eggs", "spam", "foo"])
assert api.option('string').owner.get() =='user'
api.option('string').value.set([])
api.option('string').value.reset()
# assert api.option('string').value.get() == ["string"]
assert api.option('string').owner.get() =='default'
raises(ValueError, "api.option('string').value.set(None)")
def test_property_only_raises():
s = StrOption("string", "", default=["string"], default_multi="string", multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc",
requires=[{'option': intoption, 'expected': 1, 'action': 'hidden'}], multi=True)
descr = OptionDescription("options", "", [s, intoption, stroption])
api = Config(descr)
api.property.read_write()
assert api.option('str').property.get() == {'empty'}
assert api.option('str').property.get(only_raises=True) == set()
def test_default_with_multi():
"default with multi is a list"
s = StrOption("string", "", default=[], default_multi="string", multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
assert api.option('string').value.get() == []
s = StrOption("string", "", default=None, default_multi="string", multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
assert api.option('string').value.get() == []
def test_idontexist():
descr = make_description()
api = Config(descr)
api.value.dict()
raises(AttributeError, "api.option('idontexist').value.get()")
# ____________________________________________________________
def test_attribute_access_with_multi():
s = StrOption("string", "", default=["string"], default_multi="string", multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('string').value.set(["foo", "bar"])
assert api.option('string').value.get() == ["foo", "bar"]
def test_item_access_with_multi():
s = StrOption("string", "", default=["string"], multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('string').value.set(["foo", "bar"])
assert api.option('string').value.get() == ["foo", "bar"]
api.option('string').value.set(["changetest", "bar"])
assert api.option('string').value.get() == ["changetest", "bar"]
def test_access_with_multi_default():
s = StrOption("string", "", default=["string"], multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
assert api.option('string').owner.get() =='default'
api.option('string').value.set(["foo", "bar"])
assert api.option('string').value.get() == ["foo", "bar"]
assert api.option('string').owner.get() =='user'
def test_multi_with_requires():
s = StrOption("string", "", default=["string"], default_multi="string", multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc",
requires=[{'option': intoption, 'expected': 1, 'action': 'hidden'}], multi=True)
descr = OptionDescription("options", "", [s, intoption, stroption])
api = Config(descr)
api.property.read_write()
assert not 'hidden' in api.option('str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('str').value.set(['a', 'b'])")
assert 'hidden' in api.forcepermissive.option('str').property.get()
def test__requires_with_inverted():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"], default_multi="abc",
requires=[{'option': intoption, 'expected': 1, 'action': 'hide', 'inverse': True}], multi=True)
descr = OptionDescription("options", "", [s, intoption, stroption])
api = Config(descr)
assert not 'hidden' in api.option('str').property.get()
api.option('int').value.set(1)
assert not 'hidden' in api.option('str').property.get()
def test_multi_with_requires_in_another_group():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"],
requires=[{'option': intoption, 'expected': 1, 'action': 'hidden'}], multi=True)
descr = OptionDescription("opt", "", [stroption])
descr2 = OptionDescription("opt2", "", [intoption, s, descr])
api = Config(descr2)
api.property.read_write()
assert not 'hidden' in api.option('opt.str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.set(['a', 'b'])")
assert 'hidden' in api.forcepermissive.option('opt.str').property.get()
def test_multi_with_requires_in_another_group_inverse():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"],
requires=[{'option': intoption, 'expected': 0, 'action': 'hidden', 'inverse': True}], multi=True)
descr = OptionDescription("opt", "", [stroption])
descr2 = OptionDescription("opt2", "", [intoption, s, descr])
api = Config(descr2)
api.property.read_write()
assert not 'hidden' in api.option('opt.str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.set(['a', 'b'])")
assert 'hidden' in api.forcepermissive.option('opt.str').property.get()
def test_apply_requires_from_config():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"],
requires=[{'option': intoption, 'expected': 1, 'action': 'hidden'}], multi=True)
descr = OptionDescription("opt", "", [stroption])
descr2 = OptionDescription("opt2", "", [intoption, s, descr])
api = Config(descr2)
api.property.read_write()
assert not 'hidden' in api.option('opt.str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.get()")
assert 'hidden' in api.forcepermissive.option('opt.str').property.get()
assert 'hidden' not in api.forcepermissive.option('opt.str').option.properties()
assert 'hidden' not in api.forcepermissive.option('opt.str').option.properties(only_raises=True)
def test_apply_requires_with_disabled():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"],
requires=[{'option': intoption, 'expected': 1, 'action': 'disabled'}], multi=True)
descr = OptionDescription("opt", "", [stroption])
descr2 = OptionDescription("opt2", "", [intoption, s, descr])
api = Config(descr2)
api.property.read_write()
assert not 'disabled' in api.option('opt.str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.get()")
assert 'disabled' not in api.unrestraint.option('opt.str').option.properties()
assert 'disabled' not in api.unrestraint.option('opt.str').option.properties(only_raises=True)
assert 'disabled' in api.unrestraint.option('opt.str').property.get()
def test_multi_with_requires_with_disabled_in_another_group():
s = StrOption("string", "", default=["string"], multi=True)
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default=["abc"],
requires=[{'option': intoption, 'expected': 1, 'action': 'disabled'}], multi=True)
descr = OptionDescription("opt", "", [stroption])
descr2 = OptionDescription("opt2", "", [intoption, s, descr])
api = Config(descr2)
api.property.read_write()
assert not 'disabled' in api.option('opt.str').property.get()
api.option('int').value.set(1)
raises(PropertiesOptionError, "api.option('opt.str').value.set(['a', 'b'])")
assert 'disabled' in api.unrestraint.option('opt.str').property.get()
def test_multi_with_requires_that_is_multi():
b = IntOption('int', 'Test int option', default=[0], multi=True)
c = StrOption('str', 'Test string option', default=['abc'], requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True)
descr = OptionDescription("opt", "", [b, c])
descr
raises(ValueError, "Config(descr)")
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
raises(ValueError, "Config(descr)")
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)
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)
raises(ValueError, "Leadership('str', '', [c, b])")
def test_multi_with_requires_that_is_leadership_follower():
b = IntOption('int', 'Test int option', default=[0], multi=True)
c = StrOption('str', 'Test string option', multi=True)
d = StrOption('str1', 'Test string option', requires=[{'option': c, 'expected': '1', 'action': 'hidden'}], multi=True)
descr = Leadership("int", "", [b, c, d])
descr2 = OptionDescription('od', '', [descr])
api = Config(descr2)
api.property.read_write()
assert api.option('int.int').value.get() == [0]
assert api.option('int.str', 0).value.get() == None
assert api.option('int.str1', 0).value.get() == None
api.option('int.int').value.set([0, 1])
assert api.option('int.int').value.get() == [0, 1]
assert api.option('int.str', 0).value.get() == None
assert api.option('int.str', 1).value.get() == None
assert api.option('int.str1', 0).value.get() == None
assert api.option('int.str1', 1).value.get() == None
api.option('int.str', 1).value.set('1')
api.property.read_only()
assert api.option('int.str1', 0).value.get() == None
assert api.option('int.str1', 1).value.get() == None
api.property.read_write()
assert api.option('int.str1', 0).value.get() == None
raises(PropertiesOptionError, "api.option('int.str1', 1).value.get()")
def test_multi_with_requires_that_is_leadership_follower_inverse():
b = IntOption('int', 'Test int option', default=[0], multi=True)
c = StrOption('str', 'Test string option', multi=True)
d = StrOption('str1', 'Test string option', requires=[{'option': c, 'expected': None, 'action': 'hidden', 'inverse': True}], multi=True)
descr = Leadership("int", "", [b, c, d])
descr2 = OptionDescription('od', '', [descr])
api = Config(descr2)
api.property.read_write()
assert api.option('int.int').value.get() == [0]
assert api.option('int.str', 0).value.get() is None
assert api.option('int.str1', 0).value.get() is None
api.option('int.int').value.set([0, 1])
assert api.option('int.int').value.get() == [0, 1]
assert api.option('int.str', 0).value.get() is None
assert api.option('int.str', 1).value.get() is None
assert api.option('int.str1', 0).value.get() is None
assert api.option('int.str1', 1).value.get() is None
api.option('int.str', 1).value.set('1')
api.property.read_only()
assert api.option('int.str1', 0).value.get() is None
assert api.option('int.str1', 1).value.get() is None
api.property.read_write()
assert api.option('int.str1', 0).value.get() is None
raises(PropertiesOptionError, "api.option('int.str1', 1).value.get()")
def test_multi_with_requires_that_is_not_same_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)
descr1 = Leadership("int", "", [b, c])
d = IntOption('int1', 'Test int option', default=[0], multi=True)
e = StrOption('str', 'Test string option', requires=[{'option': b, 'expected': 1, 'action': 'hidden'}], multi=True)
descr2 = Leadership("int1", "", [d, e])
descr3 = OptionDescription('val', '', [descr1, descr2])
descr3
raises(ValueError, "Config(descr3)")
def test_multi_with_bool():
s = BoolOption("bool", "", default=[False], multi=True)
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('bool').value.set([True, False])
assert api.option('bool').value.get() == [True, False]
def test_choice_access_with_multi():
ch = ChoiceOption("t1", "", ("a", "b"), default=["a"], multi=True)
descr = OptionDescription("options", "", [ch])
api = Config(descr)
api.option('t1').value.set(["a", "b", "a", "b"])
assert api.option('t1').value.get() == ["a", "b", "a", "b"]
#____________________________________________________________
def test_accepts_multiple_changes_from_option():
s = StrOption("string", "", default="string")
descr = OptionDescription("options", "", [s])
api = Config(descr)
api.option('string').value.set("egg")
assert api.option('string').option.default() == "string"
assert api.option('string').value.get() == "egg"
api.option('string').value.set('blah')
assert api.option('string').option.default() == "string"
assert api.option('string').value.get() == "blah"
api.option('string').value.set('bol')
assert api.option('string').value.get() == 'bol'
def test_allow_multiple_changes_from_config():
"""
a `setoption` from the config object is much like the attribute access,
except the fact that value owner can bet set
"""
s = StrOption("string", "", default="string")
s2 = StrOption("string2", "", default="string")
suboption = OptionDescription("bip", "", [s2])
descr = OptionDescription("options", "", [s, suboption])
api = Config(descr)
api.option('string').value.set("oh")
assert api.option('string').value.get() == "oh"
api.option('string').value.set("blah")
assert api.option('string').value.get() == "blah"
# ____________________________________________________________
# accessing a value by the get method
def test_access_by_get():
descr = make_description()
api = Config(descr)
raises(AttributeError, "list(api.option.find('idontexist'))")
assert api.option.find('wantref', first=True).value.get() is False
assert api.option.find('dummy', first=True).value.get() is False
def test_access_by_get_whith_hide():
b1 = BoolOption("b1", "", properties=(('hidden'),))
descr = OptionDescription("opt", "",
[OptionDescription("sub", "",
[b1, ChoiceOption("c1", "", ('a', 'b', 'c'), 'a'),
BoolOption("d1", "")]),
BoolOption("b2", ""),
BoolOption("d1", "")])
api = Config(descr)
api.property.read_write()
raises(AttributeError, "api.option.find('b1').value.get()")
def test_append_properties():
descr = make_description()
api = Config(descr)
assert api.option('gc.dummy').property.get() == set()
api.option('gc.dummy').property.add('test')
assert api.option('gc.dummy').property.get() == {'test'}
raises(ConfigError, "api.option('gc.dummy').property.add('force_store_value')")
assert api.option('gc.dummy').property.get() == {'test'}
def test_reset_properties():
descr = make_description()
api = Config(descr)
assert api.option('gc.dummy').property.get() == set()
api.option('gc.dummy').property.add('frozen')
assert api.option('gc.dummy').property.get() == {'frozen'}
api.option('gc.dummy').property.reset()
assert api.option('gc.dummy').property.get() == set()
def test_properties_cached():
b1 = BoolOption("b1", "", properties=('test',))
descr = OptionDescription("opt", "", [OptionDescription("sub", "", [b1])])
api = Config(descr)
api.property.read_write()
assert api.option('sub.b1').property.get() == {'test'}
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])
api = Config(descr)
assert api.option('gc.dummy').property.get() == {'force_store_value'}
api.option('gc.dummy').property.add('test')
assert api.option('gc.dummy').property.get() == {'force_store_value', 'test'}
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])
api = Config(descr)
assert api.property.exportation() == {}
api.property.add('frozen')
assert api.property.exportation() == \
{None: set(('frozen', 'cache', 'validator', 'warnings'))}
api.property.reset()
assert api.property.exportation() == {}
api.option('gc.dummy').property.add('test')
assert api.property.exportation() == {'gc.dummy': set(('test', 'force_store_value'))}
api.property.reset()
assert api.property.exportation() == {'gc.dummy': set(('test', 'force_store_value'))}
api.property.add('frozen')
assert api.property.exportation() == \
{None: set(('frozen', 'validator', 'cache', 'warnings')),
'gc.dummy': set(('test', 'force_store_value'))}
api.property.add('frozen')
assert api.property.exportation() == \
{None: set(('frozen', 'validator', 'cache', 'warnings')),
'gc.dummy': set(('test', 'force_store_value'))}
api.option('gc.dummy').property.add('test')
assert api.property.exportation() == \
{None: set(('frozen', 'validator', 'cache', 'warnings')),
'gc.dummy': set(('test', 'force_store_value'))}
def test_importation_force_store_value():
gcdummy = BoolOption('dummy', 'dummy', default=False,
properties=('force_store_value',))
gcgroup = OptionDescription('gc', '', [gcdummy])
descr = OptionDescription('tiramisu', '', [gcgroup])
config1 = Config(descr)
assert config1.value.exportation() == [[], [], [], []]
config1.property.add('frozen')
assert config1.value.exportation() == [[], [], [], []]
config1.property.add('force_store_value')
assert config1.value.exportation() == [['gc.dummy'], [None], [False], ['forced']]
exportation = config1.property.exportation()
config2 = Config(descr)
assert config2.value.exportation() == [[], [], [], []]
config2.property.importation(exportation)
assert config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']]
config2.property.importation(exportation)
assert config2.value.exportation() == [['gc.dummy'], [None], [False], ['forced']]
def test_set_modified_value():
gcdummy = BoolOption('dummy', 'dummy', default=False, properties=('force_store_value',))
gcgroup = OptionDescription('gc', '', [gcdummy])
descr = OptionDescription('tiramisu', '', [gcgroup])
api = Config(descr)
assert api.property.exportation() == {}
api.property.importation({None: set(('frozen', 'cache', 'validator', 'warnings'))})
assert api.property.exportation() == \
{None: set(('frozen', 'cache', 'validator', 'warnings'))}
def test_pprint():
msg_error = _("cannot access to {0} \"{1}\" because has {2} {3}")
msg_is_not = _('the value of "{0}" is not {1}')
msg_is = _('the value of "{0}" is "{1}"')
properties = _('properties')
prop = _('property')
s = StrOption("string", "", default=["string"], default_multi="string", multi=True, properties=('hidden', 'disabled'))
s2 = StrOption("string2", "", default="string")
s3 = StrOption("string3", "", default=["string"], default_multi="string", multi=True, properties=('hidden',))
intoption = IntOption('int', 'Test int option', default=0)
stroption = StrOption('str', 'Test string option', default="abc",
requires=[{'option': intoption, 'expected': 2, 'action': 'hidden', 'inverse': True},
{'option': intoption, 'expected': 3, 'action': 'hidden', 'inverse': True},
{'option': intoption, 'expected': 4, 'action': 'hidden', 'inverse': True},
{'option': intoption, 'expected': 1, 'action': 'disabled'},
{'option': s2, 'expected': 'string', 'action': 'disabled'}])
val2 = StrOption('val2', "")
descr2 = OptionDescription("options", "", [val2], requires=[{'option': intoption, 'expected': 1, 'action': 'hidden'}])
val3 = StrOption('val3', "", requires=[{'option': stroption, 'expected': '2', 'action': 'hidden', 'inverse': True}])
descr = OptionDescription("options", "", [s, s2, s3, intoption, stroption, descr2, val3])
api = Config(descr)
api.property.read_write()
api.option('int').value.set(1)
err = None
try:
api.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')]) + ')'
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])))
del err
err = None
try:
api.option('options.val2').value.get()
except PropertiesOptionError as error:
err = error
assert str(err) == msg_error.format('optiondescription', 'options', prop, '"hidden" (' + msg_is.format('Test int option', 1) + ')')
#err = None
#try:
# api.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]) + ')'
#assert str(err) == msg_error.format('option', 'val3', prop, list_hidden)
err = None
try:
api.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
err = None
try:
api.option('string3').value.get()
except Exception as error:
err = error
assert str(err) == msg_error.format('option', 'string3', prop, '"hidden"')
del err

View File

@ -1,139 +0,0 @@
# coding: utf-8
"frozen and hidden values"
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu import ChoiceOption, BoolOption, IntOption, FloatOption, \
PasswordOption, StrOption, DateOption, OptionDescription, Config
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__)
def make_description():
gcoption = ChoiceOption('name', 'GC name', ('ref', 'framework'), 'ref')
gcdummy = BoolOption('dummy', 'dummy', default=False, properties=(('hidden'),))
objspaceoption = ChoiceOption('objspace', 'Object space',
('std', 'thunk'), ['std'], multi=True)
booloption = BoolOption('bool', 'Test boolean option', default=True)
intoption = IntOption('int', 'Test int option', default=0)
floatoption = FloatOption('float', 'Test float option', default=2.3)
stroption = StrOption('str', 'Test string option', default="abc")
wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=({'option': gcoption, 'expected': 'ref', 'action': 'hidden'},))
wantframework_option = BoolOption('wantframework', 'Test requires',
default=False,
requires=({'option': gcoption, 'expected': 'framework', 'action': 'hidden'},))
# ____________________________________________________________
booloptiontwo = BoolOption('booltwo', 'Test boolean option two', default=False)
subgroup = OptionDescription('subgroup', '', [booloptiontwo])
# ____________________________________________________________
gcgroup = OptionDescription('gc', '', [subgroup, gcoption, gcdummy, floatoption])
descr = OptionDescription('trs', '', [gcgroup, booloption, objspaceoption,
wantref_option, stroption,
wantframework_option,
intoption])
return descr
# ____________________________________________________________
def test_is_hidden():
descr = make_description()
api = Config(descr)
api.property.read_write()
assert not 'frozen' in api.forcepermissive.option('gc.dummy').property.get()
# setattr
raises(PropertiesOptionError, "api.option('gc.dummy').value.get() == False")
# getattr
raises(PropertiesOptionError, "api.option('gc.dummy').value.get()")
def test_group_is_hidden():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.option('gc').property.add('hidden')
raises(PropertiesOptionError, "api.option('gc.dummy').value.get()")
assert 'hidden' in api.forcepermissive.option('gc').property.get()
raises(PropertiesOptionError, "api.option('gc.float').value.get()")
# manually set the subconfigs to "show"
api.forcepermissive.option('gc').property.pop('hidden')
assert not 'hidden' in api.option('gc').property.get()
assert api.option('gc.float').value.get() == 2.3
#dummy est en hide
prop = []
try:
api.option('gc.dummy').value.set(False)
except PropertiesOptionError as err:
prop = err.proptype
assert 'hidden' in prop
def test_group_is_hidden_multi():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.option('objspace').property.add('hidden')
raises(PropertiesOptionError, "api.option('objspace').value.get()")
assert 'hidden' in api.forcepermissive.option('objspace').property.get()
prop = []
try:
api.option('objspace').value.set(['std'])
except PropertiesOptionError as err:
prop = err.proptype
assert 'hidden' in prop
api.forcepermissive.option('objspace').property.pop('hidden')
assert not 'hidden' in api.option('objspace').property.get()
api.option('objspace').value.set(['std', 'std'])
def test_global_show():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.forcepermissive.option('gc.dummy').property.add('hidden')
assert 'hidden' in api.forcepermissive.option('gc.dummy').property.get()
raises(PropertiesOptionError, "api.option('gc.dummy').value.get() == False")
def test_with_many_subgroups():
descr = make_description()
api = Config(descr)
#booltwo = config.unwrap_from_path('gc.subgroup.booltwo')
#setting = config.cfgimpl_get_settings()
assert not 'hidden' in api.option('gc.subgroup.booltwo').property.get()
assert api.option('gc.subgroup.booltwo').value.get() is False
api.option('gc.subgroup.booltwo').property.add('hidden')
def test_password_option():
o = PasswordOption('o', '')
d = OptionDescription('d', '', [o])
api = Config(d)
api.option('o').value.set('a_valid_password')
raises(ValueError, "api.option('o').value.set(1)")
def test_date_option():
o = DateOption('o', '')
d = OptionDescription('d', '', [o])
api = Config(d)
api.option('o').value.set('2017-02-04')
api.option('o').value.set('2017-2-4')
raises(ValueError, "api.option('o').value.set(1)")
raises(ValueError, "api.option('o').value.set('2017-13-20')")
raises(ValueError, "api.option('o').value.set('2017-11-31')")
raises(ValueError, "api.option('o').value.set('2017-12-32')")
raises(ValueError, "api.option('o').value.set('2017-2-29')")
raises(ValueError, "api.option('o').value.set('2-2-2017')")
raises(ValueError, "api.option('o').value.set('2017/2/2')")

View File

@ -1,32 +0,0 @@
"configuration objects global API"
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.option import UsernameOption
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_username():
UsernameOption('a', '', 'string')
UsernameOption('a', '', '_string')
UsernameOption('a', '', 's_tring')
UsernameOption('a', '', 'string_')
UsernameOption('a', '', 'string$')
UsernameOption('a', '', '_string$')
raises(ValueError, "UsernameOption('a', '', 'strin$g')")
UsernameOption('a', '', 's-tring')
raises(ValueError, "UsernameOption('a', '', '-string')")
UsernameOption('a', '', 's9tring')
raises(ValueError, "UsernameOption('a', '', '9string')")
raises(ValueError, "UsernameOption('a', '', '')")
UsernameOption('a', '', 's')
UsernameOption('a', '', 's2345678901234567890123456789012')
raises(ValueError, "UsernameOption('a', '', 's23456789012345678901234567890123')")
UsernameOption('a', '', 's234567890123456789012345678901$')
raises(ValueError, "UsernameOption('a', '', 's2345678901234567890123456789012$')")

View File

@ -1,514 +0,0 @@
from .autopath import do_autopath
do_autopath()
import warnings
from py.test import raises
from tiramisu import BoolOption, StrOption, OptionDescription, Leadership, Config, Params, ParamValue, ParamOption, ParamContext
from tiramisu.setting import groups
from tiramisu.error import ValueWarning, ConfigError
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__)
msg_err = _('attention, "{0}" could be an invalid {1} for "{2}", {3}')
def return_true(value, param=None):
if value == 'val' and param in [None, 'yes']:
return True
raise ValueError('test error')
def return_false(value, param=None):
if value == 'val' and param in [None, 'yes']:
raise ValueError('test error return_false')
def return_val(value, param=None):
return 'val'
def return_if_val(value):
if value != 'val':
raise ValueError('test error')
def is_context(value, context):
api = Config(context)
api.property.pop('validator')
if not isinstance(api, Config):
raise ValueError('not context')
def value_values(value, values):
if not (value == 'val' and values == ['val'] or
value == 'val1' and values == ['val'] or
value == 'val2' and values == ['val'] or
value == 'val1' and values == ['val1'] or
value == 'val1' and values == ['val1', 'val2'] or
value == 'val2' and values == ['val1', 'val2'] or
value == 'val1' and values == ['val1', None]):
raise ValueError('error')
def value_values_index(value, values, index):
value_values(value, values)
if not (index == 0 or (value == 'val2' and index == 1)):
raise ValueError('error 2')
def value_values_auto(value, values, auto=False):
if auto != False:
raise ValueError('auto should be False')
if not (value == 'val' and values == ['val'] or
value == 'val1' and values == ['val1'] or
value == 'val2' and values == ['val1', 'val2'] or
value == 'val1' and values == ['val1', None]):
raise ValueError('error')
def value_values_auto2(value, values, auto=False):
if auto != False:
raise ValueError('auto should be False')
if not (value == 'val1' and values == 'val' or
value == 'val2' and values == 'val'):
raise ValueError('error')
def value_values_index2(value, values, index, auto=False):
if auto != False:
raise ValueError('auto should be False')
if not (value == 'val1' and values == ['val1'] and index == 'val' or
value == 'val1' and values == ['val1', None] and index == 'val' or
value == 'val2' and values == ['val1', 'val2'] and index == 'val'):
raise ValueError('error')
def value_empty(value, empty, values):
if not value == 'val' or empty is not False and not values == ['val']:
raise ValueError('error')
def valid_from_config(value, config):
api = Config(config)
if api.option('opt1').value.get() != u'yes':
raise ValueError("c'est une erreur")
def test_validator():
opt1 = StrOption('opt1', '', validator=return_true, default='val')
raises(ValueError, "StrOption('opt2', '', validator=return_false, default='val')")
opt2 = StrOption('opt2', '', validator=return_false)
root = OptionDescription('root', '', [opt1, opt2])
api = Config(root)
assert api.option('opt1').value.get() == 'val'
raises(ValueError, "api.option('opt2').value.set('val')")
try:
api.option('opt2').value.set('val')
except ValueError as err:
msg = _('"{0}" is an invalid {1} for "{2}", {3}').format('val', _('string'), 'opt2', 'test error return_false')
assert str(err) == msg
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
assert len(w) == 1
assert str(w[0].message) == msg
def test_validator_params():
opt1 = StrOption('opt1', '', validator=return_true, validator_params=Params(ParamValue('yes')), default='val')
raises(ValueError, "StrOption('opt2', '', validator=return_false, validator_params=Params(ParamValue('yes')), default='val')")
opt2 = StrOption('opt2', '', validator=return_false, validator_params=Params(ParamValue('yes')))
root = OptionDescription('root', '', [opt1, opt2])
api = Config(root)
assert api.option('opt1').value.get() == 'val'
raises(ValueError, "api.option('opt2').value.set('val')")
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
assert len(w) == 1
def test_validator_params_value_values():
opt1 = StrOption('opt1', '', validator=value_values, default=['val'], multi=True)
root = OptionDescription('root', '', [opt1])
api = Config(root)
assert api.option('opt1').value.get() == ['val']
api.option('opt1').value.set(['val1', 'val2'])
def test_validator_params_value_values_index():
opt1 = StrOption('opt1', '', validator=value_values_index, default=['val'], multi=True)
root = OptionDescription('root', '', [opt1])
api = Config(root)
assert api.option('opt1').value.get() == ['val']
api.option('opt1').value.set(['val1', 'val2'])
def test_validator_params_value_values_leader():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True, validator=value_values)
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])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
def test_validator_params_value_values_index_leader():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True, validator=value_values_index)
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])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
def test_validator_params_value_values_follower():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True, validator=value_values)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2')
def test_validator_params_value_values_index_follower():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-reseau", multi=True, validator=value_values_index)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2')
def test_validator_params_value_values_notmulti():
raises(ConfigError, "opt1 = StrOption('opt1', '', validator=value_values, default='val')")
def test_validator_params_value_values_kwargs_empty():
v = BoolOption('v', '', default=False)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True, default=["ip"])
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=value_empty,
validator_params=Params(ParamOption(v)))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [v, interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val'])
#cfg.ip_admin_eth0.ip_admin_eth0.append('val')
#cfg.ip_admin_eth0.netmask_admin_eth0[1] = 'val2'
def test_validator_params_value_values_kwargs():
v = BoolOption('v', '', default=False)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True, default=["ip"])
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=value_values_auto,
validator_params=Params(kwargs={'auto': ParamOption(v)}))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [v, interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['ip']
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['ip', 'val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2')
def test_validator_params_value_values_kwargs_values():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=value_values_auto2,
validator_params=Params(kwargs={'values': ParamOption(ip_admin_eth0)}))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2')
def test_validator_params_value_values_kwargs2():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=value_values_index2,
validator_params=Params(ParamValue(['val1']), {'index': ParamOption(ip_admin_eth0)}))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val'])
def test_validator_params_value_values_kwargs_index():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=value_values_index2,
validator_params=Params(kwargs={'index': ParamOption(ip_admin_eth0)}))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val2')
def test_validator_params_context():
opt1 = StrOption('opt1', '', validator=is_context, validator_params=Params(ParamContext()), default='val')
root = OptionDescription('root', '', [opt1])
api = Config(root)
assert 'validator' in api.property.get()
assert api.option('opt1').value.get() == 'val'
assert 'validator' in api.property.get()
def test_validator_params_context_value():
opt1 = StrOption('opt1', '', 'yes')
opt2 = StrOption('opt2', '', validator=valid_from_config, validator_params=Params(ParamContext()), default='val')
root = OptionDescription('root', '', [opt1, opt2])
api = Config(root)
assert api.option('opt1').value.get() == 'yes'
assert api.option('opt2').value.get() == 'val'
api.option('opt1').value.set('no')
raises(ValueError, "assert api.option('opt2').value.get()")
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.get()
assert len(w) == 1
def test_validator_params_key():
opt1 = StrOption('opt1', '', validator=return_true, validator_params=Params(kwargs={'param': ParamValue('yes')}), default='val')
raises(ConfigError, "StrOption('opt2', '', validator=return_true, validator_params=Params(kwargs={'param_unknown': ParamValue('yes')}), default='val')")
root = OptionDescription('root', '', [opt1])
api = Config(root)
assert api.option('opt1').value.get() == 'val'
def test_validator_params_option():
opt0 = StrOption('opt0', '', default='yes')
opt1 = StrOption('opt1', '', validator=return_true, validator_params=Params(ParamOption(opt0)), default='val')
r = OptionDescription('root', '', [opt0, opt1])
api = Config(r)
assert api.option('opt1').value.get() == 'val'
api.option('opt0').value.set('val')
raises(ValueError, "api.option('opt1').value.get()")
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt1').value.get()
assert len(w) == 1
def test_validator_multi():
opt1 = StrOption('opt1', '', validator=return_if_val, multi=True)
root = OptionDescription('root', '', [opt1])
api = Config(root)
assert api.option('opt1').value.get() == []
api.option('opt1').value.set(['val'])
assert api.option('opt1').value.get() == ['val']
raises(ValueError, "api.option('opt1').value.set(['val', 'val1'])")
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt1').value.set(['val', 'val1'])
assert len(w) == 1
def test_validator_warning():
opt1 = StrOption('opt1', '', validator=return_true, default='val', warnings_only=True)
opt2 = StrOption('opt2', '', validator=return_false, warnings_only=True)
opt3 = StrOption('opt3', '', validator=return_if_val, multi=True, warnings_only=True)
root = OptionDescription('root', '', [opt1, opt2, opt3])
api = Config(root)
assert api.option('opt1').value.get() == 'val'
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt1').value.set('val')
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
assert len(w) == 1
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:
api.option('opt3').value.set(['val'])
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('opt3').value.set(['val', 'val1'])
assert len(w) == 1
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:
raises(ValueError, "api.option('opt2').value.set(1)")
assert len(w) == 0
#
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
api.option('opt3').value.set(['val', 'val1', 'val'])
assert len(w) == 2
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')
def test_validator_warning_disabled():
opt1 = StrOption('opt1', '', validator=return_true, default='val', warnings_only=True)
opt2 = StrOption('opt2', '', validator=return_false, warnings_only=True)
opt3 = StrOption('opt3', '', validator=return_if_val, multi=True, warnings_only=True)
root = OptionDescription('root', '', [opt1, opt2, opt3])
api = Config(root)
api.property.pop('warnings')
assert api.option('opt1').value.get() == 'val'
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt1').value.set('val')
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('opt3').value.set(['val'])
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('opt3').value.set(['val', 'val1'])
assert w == []
raises(ValueError, "api.option('opt2').value.set(1)")
#
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set('val')
api.option('opt3').value.set(['val', 'val1', 'val'])
assert w == []
#
api.property.add('demoting_error_warning')
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('opt2').value.set(1)
assert len(w) == 1
def test_validator_warning_leadership():
display_name_ip = "ip reseau autorise"
display_name_netmask = "masque du sous-reseau"
ip_admin_eth0 = StrOption('ip_admin_eth0', display_name_ip, multi=True, validator=return_false, warnings_only=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', display_name_netmask, multi=True, validator=return_if_val, warnings_only=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
assert interface1.impl_get_group_type() == groups.leadership
root = OptionDescription('root', '', [interface1])
api = Config(root)
warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w:
api.option('ip_admin_eth0.ip_admin_eth0').value.set([None])
assert w == []
#
with warnings.catch_warnings(record=True) as w:
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val1')
assert len(w) == 1
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:
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val'])
assert len(w) == 1
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')
#
with warnings.catch_warnings(record=True) as w:
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val', 'val1', 'val1'])
#FIXME
#assert len(w) == 1
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')
#
with warnings.catch_warnings(record=True) as w:
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val', 'val1'])
#FIXME
#assert len(w) == 1
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')
#
warnings.resetwarnings()
with warnings.catch_warnings(record=True) as w:
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val1', 'val'])
#FIXME
#assert len(w) == 1
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')
def test_validator_follower_param():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
multi=True,
validator=return_true,
validator_params=Params(kwargs={'param': ParamOption(ip_admin_eth0)}))
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
root = OptionDescription('root', '', [interface1])
api = Config(root)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('val')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['yes', 'yes'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val')
def test_validator_dependencies():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip reseau autorise")
netmask_admin_eth0 = StrOption('netmask_admin_eth0',
"masque du sous-reseau",
validator=return_true,
validator_params=Params(kwargs={'param': ParamOption(ip_admin_eth0)}))
opt2 = StrOption('opt2', '', validator=return_false)
root = OptionDescription('root', '', [ip_admin_eth0, netmask_admin_eth0, opt2])
api = Config(root)
assert api.option('ip_admin_eth0').option.has_dependency() is False
assert api.option('netmask_admin_eth0').option.has_dependency() is True
assert api.option('opt2').option.has_dependency() is False
#
assert api.option('ip_admin_eth0').option.has_dependency(False) is True
assert api.option('netmask_admin_eth0').option.has_dependency(False) is False
assert api.option('opt2').option.has_dependency(False) is False

View File

@ -1,379 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu import IntOption, UnicodeOption, OptionDescription, Config
from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.api import TIRAMISU_VERSION
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__)
def make_description():
u1 = IntOption('u1', '', properties=('frozen', 'mandatory', 'disabled', ))
u2 = IntOption('u2', '', properties=('frozen', 'mandatory', 'disabled', ))
return OptionDescription('od1', '', [u1, u2])
def test_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.property.read_write()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.unrestraint.permissive.set(frozenset(['disabled']))
assert api.unrestraint.permissive.get() == frozenset(['disabled'])
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.add('permissive')
api.option('u1').value.get()
api.property.pop('permissive')
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
def test_permissive_add():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.property.read_write()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.unrestraint.permissive.add('disabled')
assert api.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.add('permissive')
api.option('u1').value.get()
api.property.pop('permissive')
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
def test_permissive_pop():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.property.read_write()
props = frozenset()
try:
api.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.unrestraint.permissive.add('disabled')
assert api.unrestraint.permissive.get() == frozenset(['hidden', 'disabled'])
api.forcepermissive.option('u1').value.get()
api.unrestraint.permissive.pop('disabled')
props = frozenset()
try:
api.forcepermissive.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
def test_permissive_reset():
descr = make_description()
api = Config(descr)
api.property.read_write()
assert api.unrestraint.permissive.get() == frozenset(['hidden'])
#
api.unrestraint.permissive.set(frozenset(['disabled']))
assert api.unrestraint.permissive.get() == frozenset(['disabled'])
#
api.unrestraint.permissive.reset()
assert api.unrestraint.permissive.get() == frozenset()
def test_permissive_mandatory():
descr = make_description()
api = Config(descr)
api.property.read_only()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'mandatory'])
else:
assert frozenset(props) == frozenset(['disabled'])
api.unrestraint.permissive.set(frozenset(['mandatory', 'disabled']))
assert api.unrestraint.permissive.get() == frozenset(['mandatory', 'disabled'])
api.property.add('permissive')
api.option('u1').value.get()
api.property.pop('permissive')
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'mandatory'])
else:
assert frozenset(props) == frozenset(['disabled'])
def test_permissive_frozen():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.unrestraint.permissive.set(frozenset(['frozen', 'disabled']))
assert api.unrestraint.permissive.get() == frozenset(['frozen', 'disabled'])
assert api.permissive.get() == frozenset(['frozen', 'disabled'])
try:
api.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'frozen'])
else:
assert frozenset(props) == frozenset(['disabled'])
api.property.add('permissive')
api.option('u1').value.set(1)
assert api.option('u1').value.get() == 1
api.property.pop('permissive')
try:
api.option('u1').value.set(1)
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'frozen'])
else:
assert frozenset(props) == frozenset(['disabled'])
def test_invalid_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
raises(TypeError, "api.unrestraint.permissive.set(['frozen', 'disabled'])")
def test_forbidden_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
raises(ConfigError, "api.permissive.set(frozenset(['force_default_on_freeze']))")
raises(ConfigError, "api.permissive.set(frozenset(['force_metaconfig_on_freeze']))")
def test_permissive_option():
descr = make_description()
api = Config(descr)
api.property.read_write()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.add('permissive')
api.option('u1').value.get()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.pop('permissive')
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
def test_permissive_option_cache():
descr = make_description()
api = Config(descr)
api.property.read_write()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.unrestraint.option('u1').permissive.set(frozenset(['disabled']))
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.add('permissive')
api.option('u1').value.get()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
api.property.pop('permissive')
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset()
props = frozenset()
try:
api.option('u2').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled'}
def test_permissive_option_mandatory():
descr = make_description()
api = Config(descr)
api.property.read_only()
props = frozenset()
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'mandatory'])
else:
assert frozenset(props) == frozenset(['disabled'])
api.unrestraint.option('u1').permissive.set(frozenset(['mandatory', 'disabled']))
assert api.unrestraint.option('u1').permissive.get() == frozenset(['mandatory', 'disabled'])
api.property.add('permissive')
api.option('u1').value.get()
api.property.pop('permissive')
try:
api.option('u1').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert frozenset(props) == frozenset(['disabled', 'mandatory'])
else:
assert frozenset(props) == frozenset(['disabled'])
def test_permissive_option_frozen():
descr = make_description()
api = Config(descr)
api.property.read_write()
api.unrestraint.option('u1').permissive.set(frozenset(['frozen', 'disabled']))
api.option('u1').value.set(1)
assert api.option('u1').value.get() == 1
api.property.add('permissive')
assert api.option('u1').value.get() == 1
api.property.pop('permissive')
assert api.option('u1').value.get() == 1
if TIRAMISU_VERSION == 3:
def test_invalid_option_permissive():
descr = make_description()
api = Config(descr)
api.property.read_write()
raises(TypeError, "api.unrestraint.option('u1').permissive.set(['frozen', 'disabled'])")
def test_remove_option_permissive():
var1 = UnicodeOption('var1', '', u'value', properties=('hidden',))
od1 = OptionDescription('od1', '', [var1])
rootod = OptionDescription('rootod', '', [od1])
api = Config(rootod)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od1.var1').value.get()")
api.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert api.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
assert api.option('od1.var1').value.get() == 'value'
api.forcepermissive.option('od1.var1').permissive.set(frozenset())
assert api.forcepermissive.option('od1.var1').permissive.get() == frozenset()
raises(PropertiesOptionError, "api.option('od1.var1').value.get()")
def test_reset_option_permissive():
var1 = UnicodeOption('var1', '', u'value', properties=('hidden',))
od1 = OptionDescription('od1', '', [var1])
rootod = OptionDescription('rootod', '', [od1])
api = Config(rootod)
api.property.read_write()
raises(PropertiesOptionError, "api.option('od1.var1').value.get()")
api.forcepermissive.option('od1.var1').permissive.set(frozenset(['hidden']))
assert api.forcepermissive.option('od1.var1').permissive.get() == frozenset(['hidden'])
assert api.option('od1.var1').value.get() == 'value'
api.forcepermissive.option('od1.var1').permissive.reset()
assert api.forcepermissive.option('od1.var1').permissive.get() == frozenset()
raises(PropertiesOptionError, "api.option('od1.var1').value.get()")

View File

@ -1,1125 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from copy import copy
from tiramisu.i18n import _
from tiramisu.setting import groups
from tiramisu import setting
setting.expires_time = 1
from tiramisu import IPOption, OptionDescription, BoolOption, IntOption, StrOption, \
Leadership, Config
from tiramisu.error import PropertiesOptionError, RequirementError
from py.test import raises
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__)
def test_properties():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '', properties=('disabled',))
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.unrestraint.option('ip_address_service').property.pop('disabled')
api.option('ip_address_service').value.get()
api.unrestraint.option('ip_address_service').property.add('disabled')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
# pop twice
api.unrestraint.option('ip_address_service').property.pop('disabled')
api.unrestraint.option('ip_address_service').property.pop('disabled')
def test_requires():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
assert not api.option('activate_service').option.requires()
assert api.option('ip_address_service').option.requires()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(False)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
api.option('ip_address_service').value.get()
def test_requires_inverse():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled', 'inverse': True}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_self():
a = StrOption('ip_address_service', '',
requires=[{'option': 'self', 'expected': 'b', 'action': 'disabled'}])
od = OptionDescription('service', '', [a])
api = Config(od)
api.property.read_write()
assert api.option('ip_address_service').value.get() == None
api.option('ip_address_service').value.set('a')
assert api.option('ip_address_service').value.get() == 'a'
api.option('ip_address_service').value.set('b')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_with_requires():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').property.add('test')
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(False)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
api.option('ip_address_service').value.get()
def test_requires_invalid():
a = BoolOption('activate_service', '', True)
a
raises(ValueError, "IPOption('ip_address_service', '', requires='string')")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': False, 'action': 'disabled', 'unknown': True}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': False}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'action': 'disabled'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'expected': False, 'action': 'disabled'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': False, 'action': 'disabled', 'inverse': 'string'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': False, 'action': 'disabled', 'transitive': 'string'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': False, 'action': 'disabled', 'same_action': 'string'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': 'string', 'expected': False, 'action': 'disabled'}])")
raises(ValueError, "IPOption('ip_address_service', '', requires=[{'option': a, 'expected': 'string', 'action': 'disabled'}])")
def test_requires_same_action():
activate_service = BoolOption('activate_service', '', True)
activate_service_web = BoolOption('activate_service_web', '', True,
requires=[{'option': activate_service, 'expected': False,
'action': 'new'}])
ip_address_service_web = IPOption('ip_address_service_web', '',
requires=[{'option': activate_service_web, 'expected': False,
'action': 'disabled', 'inverse': False,
'transitive': True, 'same_action': False}])
od1 = OptionDescription('service', '', [activate_service, activate_service_web, ip_address_service_web])
api = Config(od1)
api.property.read_write()
api.property.add('new')
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['new'])
#
props = []
try:
api.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"') + ')'
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))
assert frozenset(props) == frozenset(['disabled'])
def test_multiple_requires():
a = StrOption('activate_service', '')
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': 'yes', 'action': 'disabled'},
{'option': a, 'expected': 'ok', 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('yes')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set('ok')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set('no')
api.option('ip_address_service').value.get()
def test_multiple_requires_cumulative():
a = StrOption('activate_service', '')
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': 'yes', 'action': 'disabled'},
{'option': a, 'expected': 'yes', 'action': 'hidden'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('yes')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == set(['hidden', 'disabled'])
api.option('activate_service').value.set('ok')
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('no')
api.option('ip_address_service').value.get()
def test_multiple_requires_cumulative_inverse():
a = StrOption('activate_service', '')
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': 'yes', 'action': 'disabled', 'inverse': True},
{'option': a, 'expected': 'yes', 'action': 'hidden', 'inverse': True}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == set(['hidden', 'disabled'])
api.option('activate_service').value.set('yes')
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('ok')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == set(['hidden', 'disabled'])
api.option('activate_service').value.set('no')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == set(['hidden', 'disabled'])
def test_multiple_requires_inverse():
a = StrOption('activate_service', '')
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': 'yes', 'action': 'disabled', 'inverse': True},
{'option': a, 'expected': 'ok', 'action': 'disabled', 'inverse': True}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set('yes')
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('ok')
api.option('ip_address_service').value.get()
api.option('activate_service').value.set('no')
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
props = []
try:
api.option('ip_address_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive_unrestraint():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
assert api.unrestraint.option('activate_service_web').property.get() == {'disabled'}
assert api.unrestraint.option('ip_address_service_web').property.get() == {'disabled'}
def test_requires_transitive_owner():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
#no more default value
api.option('ip_address_service_web').value.set('1.1.1.1')
api.option('activate_service').value.set(False)
props = []
try:
api.option('ip_address_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive_bis():
a = BoolOption('activate_service', '', True)
abis = BoolOption('activate_service_bis', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': True, 'action': 'disabled', 'inverse': True}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': True, 'action': 'disabled', 'inverse': True}])
od = OptionDescription('service', '', [a, abis, b, d])
api = Config(od)
api.property.read_write()
#
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
props = []
try:
api.option('ip_address_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive_hidden_permissive():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'hidden'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('ip_address_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
api.option('ip_address_service_web').value.get()
def test_requires_transitive_hidden_disabled():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'hidden'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['hidden'])
api.option('ip_address_service_web').value.get()
def test_requires_transitive_hidden_disabled_multiple():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'hidden'},
{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False, 'action': 'mandatory'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert set(props) == {'disabled', 'hidden'}
del props
#
req = None
try:
api.option('ip_address_service_web').value.get()
except RequirementError as err:
req = err
assert req, "ip_address_service_web should raise RequirementError"
assert str(req) == str(_('cannot access to option "{}" because required option "{}" has {} {}').format('ip_address_service_web', 'activate_service_web', 'property', '"disabled"'))
del req
#
api.permissive.set(frozenset())
try:
api.option('ip_address_service_web').value.get()
except RequirementError as err:
req = err
assert req, "ip_address_service_web should raise RequirementError"
assert str(req) == str(_('cannot access to option "{}" because required option "{}" has {} {}').format('ip_address_service_web', 'activate_service_web', 'properties', '"disabled" and "hidden"'))
del req
def test_requires_not_transitive():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False,
'action': 'disabled', 'transitive': False}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
api.option('ip_address_service_web').value.get()
def test_requires_not_transitive_not_same_action():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'option': b, 'expected': False,
'action': 'hidden', 'transitive': False}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
raises(RequirementError, "api.option('ip_address_service_web').value.get()")
def test_requires_None():
a = BoolOption('activate_service', '')
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': None, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
def test_requires_multi_disabled():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': True, 'action': 'disabled'},
{'option': b, 'expected': 1, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_multi_disabled_new_format():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value': True}, {'option': b, 'value': 1}], 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_unknown_operator():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
raises(ValueError, """IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value': True}, {'option': b, 'value': 1}],
'action': 'disabled', 'operator': 'unknown'}])""")
def test_requires_keys():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
raises(ValueError, """IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value2': True}, {'option': b, 'value': 1}],
'action': 'disabled', 'operator': 'and'}])""")
def test_requires_unvalid():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
raises(ValueError, """IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value': 'unvalid'}, {'option': b, 'value': 1}],
'action': 'disabled', 'operator': 'and'}])""")
def test_requires_multi_disabled_new_format_and():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value': True}, {'option': b, 'value': 1}], 'action': 'disabled', 'operator': 'and'}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert props == []
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert props == []
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_multi_disabled_new_format_and_2():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'expected': [{'option': a, 'value': True}, {'option': b, 'value': 1}], 'action': 'disabled', 'operator': 'and'},
{'expected': [{'option': a, 'value': False}, {'option': b, 'value': 1}], 'action': 'expert'}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.add('expert')
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert props == []
api.option('activate_service').value.set(False)
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['expert'])
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled', 'expert'])
def test_requires_multi_disabled_inverse():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': True,
'action': 'disabled', 'inverse': True},
{'option': b, 'expected': 1,
'action': 'disabled', 'inverse': True}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.read_write()
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
api.option('ip_address_service').value.get()
def test_requires_multi_disabled_2():
a = BoolOption('a', '')
b = BoolOption('b', '')
c = BoolOption('c', '')
d = BoolOption('d', '')
e = BoolOption('e', '')
f = BoolOption('f', '')
g = BoolOption('g', '')
h = BoolOption('h', '')
i = BoolOption('i', '')
j = BoolOption('j', '')
k = BoolOption('k', '')
l = BoolOption('l', '')
m = BoolOption('m', '')
list_bools = [a, b, c, d, e, f, g, h, i, j, k, l, m]
requires = []
for boo in list_bools:
requires.append({'option': boo, 'expected': True, 'action': 'disabled'})
z = IPOption('z', '', requires=requires)
y = copy(list_bools)
y.append(z)
od = OptionDescription('service', '', y)
api = Config(od)
api.property.read_write()
api.option('z').value.get()
for boo in list_bools:
api.option(boo.impl_getname()).value.set(True)
props = []
try:
api.option('z').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
for boo in list_bools:
api.option(boo.impl_getname()).value.set(False)
if boo == m:
api.option('z').value.get()
else:
props = []
try:
api.option('z').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_multi_disabled_inverse_2():
a = BoolOption('a', '')
b = BoolOption('b', '')
c = BoolOption('c', '')
d = BoolOption('d', '')
e = BoolOption('e', '')
f = BoolOption('f', '')
g = BoolOption('g', '')
h = BoolOption('h', '')
i = BoolOption('i', '')
j = BoolOption('j', '')
k = BoolOption('k', '')
l = BoolOption('l', '')
m = BoolOption('m', '')
list_bools = [a, b, c, d, e, f, g, h, i, j, k, l, m]
requires = []
for boo in list_bools:
requires.append({'option': boo, 'expected': True, 'action': 'disabled',
'inverse': True})
z = IPOption('z', '', requires=requires)
y = copy(list_bools)
y.append(z)
od = OptionDescription('service', '', y)
api = Config(od)
api.property.read_write()
props = []
try:
api.option('z').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
for boo in list_bools:
api.option(boo.impl_getname()).value.set(True)
if boo == m:
api.option('z').value.get()
else:
props = []
try:
api.option('z').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
for boo in list_bools:
api.option(boo.impl_getname()).value.set(False)
props = []
try:
api.option('z').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_requirement_append():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
api.property.get()
api.option('ip_address_service').property.get()
raises(ValueError, "api.option('ip_address_service').property.add('disabled')")
api.option('activate_service').value.set(False)
# disabled is now set, test to remove disabled before store in storage
api.unrestraint.option('ip_address_service').property.add("test")
def test_requires_different_inverse():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '', requires=[
{'option': a, 'expected': True, 'action': 'disabled', 'inverse': True},
{'option': a, 'expected': True, 'action': 'disabled', 'inverse': False}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
raises(PropertiesOptionError, "api.option('ip_address_service').value.get()")
api.option('activate_service').value.set(False)
raises(PropertiesOptionError, "api.option('ip_address_service').value.get()")
def test_requires_different_inverse_unicode():
a = BoolOption('activate_service', '', True)
d = StrOption('activate_other_service', '', 'val2')
b = IPOption('ip_address_service', '', requires=[
{'option': a, 'expected': True, 'action': 'disabled', 'inverse': True},
{'option': d, 'expected': 'val1', 'action': 'disabled', 'inverse': False}])
od = OptionDescription('service', '', [a, d, b])
api = Config(od)
api.property.read_write()
assert api.option('ip_address_service').value.get() == None
api.option('activate_service').value.set(False)
raises(PropertiesOptionError, "api.option('ip_address_service').value.get()")
api.option('activate_service').value.set(True)
assert api.option('ip_address_service').value.get() == None
api.option('activate_other_service').value.set('val1')
raises(PropertiesOptionError, "api.option('ip_address_service').value.get()")
api.option('activate_service').value.set(False)
raises(PropertiesOptionError, "api.option('ip_address_service').value.get()")
def test_requires_recursive_path():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od1 = OptionDescription('service', '', [a, b], requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
od = OptionDescription('base', '', [od1])
api = Config(od)
api.property.read_write()
raises(RequirementError, "api.option('service.a').value.get()")
def test_optiondescription_requires():
a = BoolOption('activate_service', '', True)
b = BoolOption('ip_address_service', '', multi=True)
a, b
OptionDescription('service', '', [b], requires=[{'option': a, 'expected': False, 'action': 'disabled'}])
def test_optiondescription_requires_multi():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '', multi=True)
a, b
raises(ValueError, "OptionDescription('service', '', [a], requires=[{'option': b, 'expected': False, 'action': 'disabled'}])")
def test_properties_conflict():
a = BoolOption('activate_service', '', True)
a
raises(ValueError, "IPOption('ip_address_service', '', properties=('disabled',), requires=[{'option': a, 'expected': False, 'action': 'disabled'}])")
raises(ValueError, "od1 = OptionDescription('service', '', [a], properties=('disabled',), requires=[{'option': a, 'expected': False, 'action': 'disabled'}])")
def test_leadership_requires():
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,
requires=[{'option': ip_admin_eth0, 'expected': '192.168.1.1', 'action': 'disabled'}])
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255')
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255'
assert api.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']}
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
ret = api.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']
#
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255')
ret = api.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']
def test_leadership_requires_both():
ip_admin = StrOption('ip_admin_eth0', "ip réseau autorisé")
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
raises(RequirementError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])")
def test_leadership_requires_properties_invalid():
ip_admin = StrOption('ip_admin', "ip réseau autorisé")
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,
requires=[{'option': ip_admin_eth0, 'expected': '192.168.1.1', 'action': 'disabled'}])
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('disabled',), requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])")
def test_leadership_requires_properties_invalid_2():
ip_admin = StrOption('ip_admin', "ip réseau autorisé")
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True,
requires=[{'option': ip_admin_eth0, 'expected': '192.168.1.1', 'action': 'disabled'}])
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('disabled',))")
def test_leadership_requires_properties():
ip_admin = StrOption('ip_admin', "ip réseau autorisé")
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,
requires=[{'option': ip_admin_eth0, 'expected': '192.168.1.1', 'action': 'disabled'}])
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('hidden',),
requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])
def test_leadership_requires_leader():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
requires=[{'option': activate, 'expected': False, 'action': 'disabled'}])
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', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
#
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
assert api.value.dict() == {'activate': False}
def test_leadership_requires_leadership():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0],
requires=[{'option': activate, 'expected': False, 'action': 'disabled'}])
maconfig = OptionDescription('toto', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
#
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
assert api.value.dict() == {'activate': False}
def test_leadership_requires_no_leader():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True,
requires=[{'option': activate, 'expected': False, 'action': 'disabled'}])
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
api.option('activate').value.set(False)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2', '192.168.1.1']
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255')
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255'
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.1'], 'activate': False}

View File

@ -1,165 +0,0 @@
## coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
try:
from tiramisu.setting import OptionBag, ConfigBag
tiramisu_version = 3
except:
tiramisu_version = 2
from tiramisu import Config
from tiramisu.config import SubConfig
from tiramisu.option import ChoiceOption, BoolOption, IntOption, FloatOption,\
StrOption, SymLinkOption, UnicodeOption, IPOption, OptionDescription, \
PortOption, NetworkOption, NetmaskOption, DomainnameOption, EmailOption, \
URLOption, FilenameOption
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__)
def test_slots_option():
c = ChoiceOption('a', '', ('a',))
raises(AttributeError, "c.x = 1")
del c
c = BoolOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = IntOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = FloatOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = StrOption('a', '')
raises(AttributeError, "c.x = 1")
c = SymLinkOption('b', c)
raises(AttributeError, "c.x = 1")
del c
c = UnicodeOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = IPOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = OptionDescription('a', '', [])
raises(AttributeError, "c.x = 1")
del c
c = PortOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = NetworkOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = NetmaskOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = DomainnameOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = EmailOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = URLOption('a', '')
raises(AttributeError, "c.x = 1")
del c
c = FilenameOption('a', '')
raises(AttributeError, "c.x = 1")
del c
def test_slots_option_readonly():
a = ChoiceOption('a', '', ('a',))
b = BoolOption('b', '')
c = IntOption('c', '')
d = FloatOption('d', '')
e = StrOption('e', '')
g = UnicodeOption('g', '')
h = IPOption('h', '')
i = PortOption('i', '')
j = NetworkOption('j', '')
k = NetmaskOption('k', '')
l = DomainnameOption('l', '')
o = EmailOption('o', '')
p = URLOption('p', '')
q = FilenameOption('q', '')
m = OptionDescription('m', '', [a, b, c, d, e, g, h, i, j, k, l, o, p, q])
a._requires = (((a,),),)
b._requires = (((a,),),)
c._requires = (((a,),),)
d._requires = (((a,),),)
e._requires = (((a,),),)
g._requires = (((a,),),)
h._requires = (((a,),),)
i._requires = (((a,),),)
j._requires = (((a,),),)
k._requires = (((a,),),)
l._requires = (((a,),),)
m._requires = (((a,),),)
o._requires = (((a,),),)
p._requires = (((a,),),)
q._requires = (((a,),),)
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'")
#def test_slots_description():
# # __slots__ for OptionDescription should be complete for __getattr__
# slots = set()
# for subclass in OptionDescription.__mro__:
# if subclass is not object:
# slots.update(subclass.__slots__)
# assert slots == set(OptionDescription.__slots__)
def test_slots_config():
od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1])
c = 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',
None,
ConfigBag(c._config_bag.context))
sc = c._config_bag.context.get_subconfig(option_bag)
assert isinstance(sc, SubConfig)
raises(AttributeError, "sc.x = 1")
raises(AttributeError, "sc.cfgimpl_x = 1")
def test_slots_setting():
od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1])
c = Config(od2)
s = c._config_bag.context.cfgimpl_get_settings()
s
raises(AttributeError, "s.x = 1")
def test_slots_value():
od1 = OptionDescription('a', '', [])
od2 = OptionDescription('a', '', [od1])
c = Config(od2)
v = c._config_bag.context.cfgimpl_get_values()
v
raises(AttributeError, "v.x = 1")

View File

@ -1,238 +0,0 @@
#from autopath import do_autopath
#do_autopath()
#
from tiramisu.option import BoolOption, UnicodeOption, SymLinkOption, \
OptionDescription, DynOptionDescription
from tiramisu import Config
from pickle import dumps
from py.test import raises
import sys
from tiramisu.storage import list_sessions
def teardown_function(function):
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
def test_diff_opt():
b = BoolOption('b', '')
u = UnicodeOption('u', '', requires=[{'option': b, 'expected': True, 'action': 'disabled', 'inverse': True}])
s = SymLinkOption('s', u)
o = OptionDescription('o', '', [b, u, s])
o1 = OptionDescription('o1', '', [o])
raises(NotImplementedError, "dumps(o1)")
def test_diff_information_config():
b = BoolOption('b', '')
b.impl_set_information('info', 'oh')
b.impl_set_information('info1', 'oh')
b.impl_set_information('info2', 'oh')
o = OptionDescription('o', '', [b])
o1 = OptionDescription('o1', '', [o])
c = Config(o1)._config_bag.context
raises(NotImplementedError, "dumps(c)")
def test_only_optiondescription():
b = BoolOption('b', '')
b
raises(NotImplementedError, "a = dumps(b)")

View File

@ -1,309 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.error import ConfigError
from tiramisu import Config, BoolOption, OptionDescription, Leadership, \
list_sessions, delete_session, default_storage
from tiramisu.setting import groups, owners
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def test_non_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
Config(o, session_id='test_non_persistent')
def test_list():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
c = Config(o, session_id='test_non_persistent')
c.option('b').value.set(True)
assert 'test_non_persistent' in list_sessions()
del(c)
assert 'test_non_persistent' not in list_sessions()
def test_delete_not_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if not default_storage.is_persistent():
c = Config(o, session_id='not_test_persistent')
assert 'not_test_persistent' in list_sessions()
del c
assert 'not_test_persistent' not in list_sessions()
#
c = Config(o, session_id='not_test_persistent')
raises(ValueError, "delete_session('not_test_persistent')")
def test_create_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
Config(o, session_id='test_persistent', persistent=True)
delete_session('test_persistent')
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')")
def test_list_sessions_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.option('b').value.set(True)
assert 'test_persistent' in list_sessions()
delete_session('test_persistent')
def test_delete_session_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
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()
def test_create_persistent_retrieve():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None
c.option('b').value.set(True)
assert c.option('b').value.get() is True
del c
c = Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is True
assert 'test_persistent' in list_sessions()
delete_session(c.config.name())
del c
c = Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None
delete_session(c.config.name())
del c
def test_two_persistent():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c2 = Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache')
assert c.option('b').value.get() is None
assert c2.option('b').value.get() is None
#
c.option('b').value.set(False)
assert c.option('b').value.get() is False
assert c2.option('b').value.get() is False
#
c.option('b').value.set(True)
assert c.option('b').value.get() is True
assert c2.option('b').value.get() is True
delete_session('test_persistent')
def test_create_persistent_retrieve_owner():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').owner.isdefault()
c.option('b').value.set(True)
assert c.option('b').value.get()
assert c.option('b').owner.get() == 'user'
##owners.addowner('persistentowner')
c.option('b').owner.set('persistentowner')
assert c.option('b').owner.get() == 'persistentowner'
del c
#
c = Config(o, session_id='test_persistent', persistent=True)
c.option('b').owner.set('persistentowner')
delete_session(c.config.name())
del c
#
c = Config(o, session_id='test_persistent', persistent=True)
assert c.option('b').value.get() is None
assert c.option('b').owner.isdefault()
delete_session(c.config.name())
del c
def test_create_persistent_retrieve_owner_leadership():
a = BoolOption('a', '', multi=True)
b = BoolOption('b', '', multi=True)
o = Leadership('a', '', [a, b])
o1 = OptionDescription('a', '', [o])
if default_storage.is_persistent():
c = Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').owner.isdefault()
c.option('a.a').value.set([True, False])
c.option('a.b', 1).value.set(True)
assert c.option('a.a').owner.get() == 'user'
assert c.option('a.b', 0).owner.isdefault()
assert c.option('a.b', 1).owner.get() == 'user'
#owners.addowner('persistentowner2')
c.option('a.b', 1).owner.set('persistentowner2')
c.option('a.b', 0).value.set(True)
assert c.option('a.b', 0).owner.get() == 'user'
assert c.option('a.b', 1).owner.get() == 'persistentowner2'
assert c.option('a.a').value.get() == [True, False]
del c
#
c = Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').value.get() == [True, False]
assert c.option('a.b', 0).owner.get() == 'user'
assert c.option('a.b', 1).owner.get() == 'persistentowner2'
delete_session(c.config.name())
del c
#
c = Config(o1, session_id='test_persistent', persistent=True)
assert c.option('a.a').value.get() == []
delete_session(c.config.name())
del c
def test_two_persistent_owner():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache')
c2 = Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache')
assert c.option('b').owner.isdefault()
assert c2.option('b').owner.isdefault()
c.option('b').value.set(False)
assert c.option('b').owner.get() == 'user'
assert c2.option('b').owner.get() == 'user'
c.option('b').owner.set('persistent')
assert c.option('b').owner.get() == 'persistent'
assert c2.option('b').owner.get() == 'persistent'
delete_session('test_persistent')
def test_create_persistent_retrieve_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.information.set('info', 'string')
assert c.information.get('info') == 'string'
del c
#
c = Config(o, session_id='test_persistent', persistent=True)
assert c.information.get('info') == 'string'
delete_session(c.config.name())
del c
#
c = Config(o, session_id='test_persistent', persistent=True)
assert c.information.get('info', None) is None
delete_session(c.config.name())
del c
def test_two_persistent_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache')
c.information.set('info', 'string')
assert c.information.get('info') == 'string'
c2 = Config(o, session_id='test_persistent', persistent=True)
c2.property.pop('cache')
assert c2.information.get('info') == 'string'
delete_session('test_persistent')
def test_two_different_persistents():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.property.pop('cache')
d = Config(o, session_id='test_persistent2', persistent=True)
d.property.pop('cache')
c.option('b').property.add('test')
assert c.option('b').property.get() == {'test'}
assert d.option('b').property.get() == set()
assert c.option('b').value.get() is None
assert d.option('b').value.get() is None
c.option('b').value.set(True)
assert c.option('b').value.get() == True
assert d.option('b').value.get() is None
delete_session('test_persistent')
delete_session('test_persistent2')
def test_two_different_information():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
c.information.set('a', 'a')
d = Config(o, session_id='test_persistent2', persistent=True)
d.information.set('a', 'b')
assert c.information.get('a') == 'a'
assert d.information.get('a') == 'b'
delete_session('test_persistent')
delete_session('test_persistent2')
def test_exportation_importation():
b = BoolOption('b', '')
o = OptionDescription('od', '', [b])
if default_storage.is_persistent():
c = Config(o, session_id='test_persistent', persistent=True)
d = Config(o, session_id='test_persistent2', persistent=True)
e = Config(o, session_id='test_persistent3', persistent=True)
c.owner.set('export')
assert c.option('b').value.get() is None
c.option('b').value.set(True)
assert c.option('b').value.get() is True
assert c.owner.get() == 'export'
del c
#
c = Config(o, session_id='test_persistent', persistent=True)
assert c.owner.get() == 'export'
assert c.value.exportation() == [['b'], [None], [True], ['export']]
d.value.importation(c.value.exportation())
assert c.value.exportation() == [['b'], [None], [True], ['export']]
assert c.owner.get() == 'export'
assert d.value.exportation() == [['b'], [None], [True], ['export']]
assert d.owner.get() == 'user'
del d
#
d = Config(o, session_id='test_persistent2', persistent=True)
assert d.value.exportation() == [['b'], [None], [True], ['export']]
assert d.owner.get() == 'user'
#
e.value.importation(c.value.exportation(with_default_owner=True))
assert e.value.exportation() == [['b'], [None], [True], ['export']]
assert e.owner.get() == 'export'
del e
#
e = Config(o, session_id='test_persistent3', persistent=True)
assert e.value.exportation() == [['b'], [None], [True], ['export']]
assert e.owner.get() == 'export'
#
delete_session('test_persistent')
delete_session('test_persistent2')
delete_session('test_persistent3')

View File

@ -1,443 +0,0 @@
# coding: utf-8
from .autopath import do_autopath
do_autopath()
from py.test import raises
from tiramisu.api import TIRAMISU_VERSION
from tiramisu.setting import groups, owners
from tiramisu import StrOption, IntOption, OptionDescription, submulti, Leadership, Config, \
MetaConfig, undefined, Params, ParamOption
from tiramisu.error import LeadershipError
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def return_val(val=None):
if val is None:
return 'val'
else:
return val
def return_list(value=None):
return ['val', 'val']
def return_list2(value=None):
return [['val', 'val']]
def test_unknown_multi():
raises(ValueError, "StrOption('multi', '', multi='unknown')")
def test_submulti():
multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2:
default_multi = 'yes'
else:
default_multi = ['yes']
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od)
assert api.option('multi').option.ismulti()
assert api.option('multi').option.issubmulti()
assert api.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default
assert api.option('multi').owner.get() == owners.default
assert api.option('multi3').value.get() == [['yes']]
assert api.option('multi').owner.get() == owners.default
def test_submulti_default_multi_not_list():
raises(ValueError, "StrOption('multi2', '', default_multi='yes', multi=submulti)")
def test_append_submulti():
multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2:
default_multi = 'yes'
else:
default_multi = ['yes']
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od)
owner = api.owner.get()
assert api.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default
api.option('multi').value.set([undefined])
assert api.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [[]]
api.option('multi').value.set([undefined, ['no']])
assert api.option('multi').value.get() == [[], ['no']]
#
assert api.option('multi2').value.get() == []
assert api.option('multi2').owner.get() == owners.default
api.option('multi2').value.set([undefined])
assert api.option('multi2').owner.get() == owner
assert api.option('multi2').value.get() == [['yes']]
api.option('multi2').value.set([undefined, ['no']])
assert api.option('multi2').value.get() == [['yes'], ['no']]
#
assert api.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([undefined, undefined])
assert api.option('multi3').owner.get() == owner
assert api.option('multi3').value.get() == [['yes'], []]
api.option('multi3').value.set([undefined, undefined, ['no']])
assert api.option('multi3').value.get() == [['yes'], [], ['no']]
def test_append_unvalide_submulti():
multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2:
default_multi = 'yes'
else:
default_multi = ['yes']
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od)
assert api.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default
raises(ValueError, "api.option('multi').value.set([[1]])")
assert api.option('multi').value.get() == []
assert api.option('multi').owner.get() == owners.default
#
assert api.option('multi2').value.get() == []
raises(ValueError, "api.option('multi2').value.set(['no'])")
assert api.option('multi').owner.get() == owners.default
assert api.option('multi2').value.get() == []
#
assert api.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default
raises(ValueError, "api.option('multi3').value.set([[1]])")
assert api.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default
def test_pop_submulti():
multi = StrOption('multi', '', multi=submulti)
if TIRAMISU_VERSION == 2:
default_multi = 'yes'
else:
default_multi = ['yes']
multi2 = StrOption('multi2', '', default_multi=default_multi, multi=submulti)
multi3 = StrOption('multi3', '', default=[['yes']], multi=submulti)
od = OptionDescription('od', '', [multi, multi2, multi3])
api = Config(od)
owner = api.owner.get()
assert api.option('multi').value.get() == []
assert api.option('multi3').owner.get() == owners.default
api.option('multi').value.set([['no', 'yes'], ['peharps']])
assert api.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['no', 'yes'], ['peharps']]
#
assert api.option('multi3').value.get() == [['yes']]
assert api.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([])
assert api.option('multi').owner.get() == owner
assert api.option('multi3').value.get() == []
api.option('multi3').value.reset()
assert api.option('multi3').owner.get() == owners.default
api.option('multi3').value.set([[]])
assert api.option('multi3').owner.get() == owner
assert api.option('multi3').value.get() == [[]]
def test_callback_submulti_str():
multi = StrOption('multi', '', multi=submulti, callback=return_val)
od = OptionDescription('od', '', [multi])
api = Config(od)
api.property.read_write()
owner = api.owner.get()
assert api.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == [['val']]
api.option('multi').value.set([['val'], undefined])
assert api.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['val'], ['val']]
api.option('multi').value.reset()
assert api.option('multi').owner.get() == owners.default
def test_callback_submulti_list():
multi = StrOption('multi', '', multi=submulti, callback=return_list)
od = OptionDescription('od', '', [multi])
api = Config(od)
api.property.read_write()
owner = api.owner.get()
assert api.option('multi').value.get() == [['val', 'val']]
assert api.option('multi').owner.get() == owners.default
api.option('multi').value.set([['val', 'val'], undefined])
assert api.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['val', 'val'], ['val', 'val']]
api.option('multi').value.set([['val', 'val'], undefined, undefined])
assert api.option('multi').value.get() == [['val', 'val'], ['val', 'val'], ['val', 'val']]
api.option('multi').value.reset()
assert api.option('multi').owner.get() == owners.default
def test_callback_submulti_list_list():
multi = StrOption('multi', '', multi=submulti, callback=return_list2)
od = OptionDescription('od', '', [multi])
api = Config(od)
api.property.read_write()
owner = api.owner.get()
assert api.option('multi').value.get() == [['val', 'val']]
assert api.option('multi').owner.get() == owners.default
api.option('multi').value.set([['val', 'val'], undefined])
assert api.option('multi').owner.get() == owner
assert api.option('multi').value.get() == [['val', 'val'], []]
api.option('multi').value.reset()
assert api.option('multi').owner.get() == owners.default
def test_groups_with_leader_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
assert interface1.impl_get_group_type() == groups.leadership
def test_groups_with_leader_in_config_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
od = OptionDescription('root', '', [interface1])
Config(od)
assert interface1.impl_get_group_type() == groups.leadership
def test_values_with_leader_and_followers_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.147"])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == []
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
raises(ValueError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.0')")
raises(ValueError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set([['255.255.255.0']])")
def test_reset_values_with_leader_and_followers_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owner
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_and_followers_follower_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
raises(LeadershipError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])")
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0', '255.255.255.0'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == []
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
def test_values_with_leader_and_leadership_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145"])
api.option('ip_admin_eth0.ip_admin_eth0').value.set(["192.168.230.145", "192.168.230.145"])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['255.255.255.0'])
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set(['255.255.255.0'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == ['255.255.255.0']
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ["192.168.230.145"]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == ['255.255.255.0']
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
def test_values_with_leader_owner_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.get() == owners.default
api.option('ip_admin_eth0.ip_admin_eth0').value.reset()
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owners.default
def test_values_with_leader_disabled_submulti():
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=submulti)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.reset()
api.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145', '192.168.230.145'])
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(1)
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
#delete with value in disabled var
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.pop('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.230.145'])
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set(['192.168.230.145'])
api.unrestraint.option('ip_admin_eth0.netmask_admin_eth0').property.add('disabled')
api.option('ip_admin_eth0.ip_admin_eth0').value.pop(0)
def test_leader_is_submulti():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=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])
api = Config(maconfig)
api.property.read_write()
owner = api.owner.get()
assert interface1.impl_get_group_type() == groups.leadership
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"]])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145"]]
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.ip_admin_eth0').owner.get() == owner
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).owner.isdefault()
api.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145"], ["192.168.230.147"]])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
api.option('ip_admin_eth0.ip_admin_eth0').value.set([["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == [["192.168.230.145", '192.168.1.1'], ["192.168.230.147"]]
raises(ValueError, "api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.1', '192.168.1.1'])")
def test_callback_submulti():
multi = StrOption('multi', '', multi=submulti)
multi2 = StrOption('multi2', '', multi=submulti, callback=return_val, callback_params=Params(ParamOption(multi)))
od = OptionDescription('multi', '', [multi, multi2])
api = Config(od)
api.property.read_write()
owner = api.owner.get()
assert api.option('multi').owner.get() == owners.default
assert api.option('multi').value.get() == []
assert api.option('multi2').value.get() == []
api.option('multi').value.set([['val']])
assert api.option('multi').owner.get() == owner
assert api.option('multi2').owner.get() == owners.default
assert api.option('multi').value.get() == [['val']]
assert api.option('multi2').value.get() == [['val']]
def test_submulti_unique():
i = IntOption('int', '', multi=submulti, unique=True)
o = OptionDescription('od', '', [i])
api = Config(o)
assert api.option('int').value.get() == []
api.option('int').value.set([[0]])
assert api.option('int').value.get() == [[0]]
raises(ValueError, "api.option('int').value.set([[0, 0]])")
api.option('int').value.set([[0], [0]])
raises(ValueError, "api.option('int').value.set([[1, 0, 2, 3, 4, 5, 6, 0, 7], [0]])")
api.option('int').value.set([[0, 4, 5, 6], [0]])
def test_submulti_unknown_unique():
raises(ValueError, "IntOption('int', '', multi=submulti, unique='str')")
def test_unique_not_multi():
raises(ValueError, "IntOption('int', '', unique=True)")
def test_multi_submulti_meta():
multi = StrOption('multi', '', multi=submulti)
od = OptionDescription('od', '', [multi])
conf1 = Config(od, session_id='conf1')
conf1.property.read_write()
conf2 = Config(od, session_id='conf2')
conf2.property.read_write()
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.option('multi').value.set([['val']])
assert meta.option('multi').value.get() == [['val']]
meta.config('conf1').option('multi').value.set([['val', None]])
assert conf1.option('multi').value.get() == [['val', None]]
assert meta.config('conf1').option('multi').value.get() == [['val', None]]
assert meta.option('multi').value.get() == [['val']]
def test_multi_submulti_meta_no_cache():
multi = StrOption('multi', '', multi=submulti)
multi = StrOption('multi', '', multi=submulti)
od = OptionDescription('od', '', [multi])
conf1 = Config(od, session_id='conf1')
conf1.property.read_write()
conf2 = Config(od, session_id='conf2')
conf1.property.read_write()
meta = MetaConfig([conf1, conf2])
meta.property.read_write()
meta.property.pop('cache')
meta.option('multi').value.set([['val']])
assert meta.option('multi').value.get() == [['val']]
meta.config('conf1').option('multi').value.set([['val', None]])
assert conf1.option('multi').value.get() == [['val', None]]
assert meta.config('conf1').option('multi').value.get() == [['val', None]]
assert meta.option('multi').value.get() == [['val']]

View File

@ -1,302 +0,0 @@
# coding: utf-8
from py.test import raises
from .autopath import do_autopath
do_autopath()
from tiramisu import BoolOption, StrOption, SymLinkOption, \
OptionDescription, Leadership, Config
from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.setting import groups, owners
from tiramisu.api import TIRAMISU_VERSION
from tiramisu.storage import list_sessions
def teardown_function(function):
assert list_sessions() == [], 'session list is not empty when leaving "{}"'.format(function.__name__)
def return_value():
pass
#____________________________________________________________
def test_symlink_option():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
assert api.option('s1.b').value.get() is False
api.option("s1.b").value.set(True)
api.option("s1.b").value.set(False)
assert api.option('s1.b').value.get() is False
assert api.option('c').value.get() is False
api.option('s1.b').value.set(True)
assert api.option('s1.b').value.get() is True
assert api.option('c').value.get() is True
api.option('s1.b').value.set(False)
assert api.option('s1.b').value.get() is False
assert api.option('c').value.get() is False
def test_symlink_assign_option():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
raises(ConfigError, "api.option('c').value.set(True)")
def test_symlink_del_option():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
raises(TypeError, "api.option('c').value.reset()")
def test_symlink_addproperties():
boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt])
api = Config(descr)
api.property.read_write()
raises(TypeError, "api.option('c').property.add('new')")
try:
api.option('c').property.reset()
except AssertionError:
pass
else:
raise Exception('must raise')
def test_symlink_getpermissive():
boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt])
api = Config(descr)
api.property.read_write()
api.option('b').permissive.set(frozenset(['perm']))
api.option('c').permissive.get() == frozenset(['perm'])
def test_symlink_addpermissives():
boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt])
api = Config(descr)
api.property.read_write()
raises(TypeError, "api.option('c').permissive.set(frozenset(['new']))")
try:
api.option('c').permissive.reset()
except AssertionError:
pass
else:
raise Exception('must raise')
def test_symlink_getproperties():
boolopt = BoolOption('b', '', default=True, properties=('test',))
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt])
api = Config(descr)
api.property.read_write()
if TIRAMISU_VERSION == 2:
assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == ('test',)
else:
assert boolopt.impl_getproperties() == linkopt.impl_getproperties() == {'test'}
assert boolopt.impl_has_callback() == linkopt.impl_has_callback() == False
def test_symlink_getcallback():
boolopt = BoolOption('b', '', callback=return_value)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription('opt', '', [boolopt, linkopt])
api = Config(descr)
api.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)
def test_symlink_requires():
boolopt = BoolOption('b', '', default=True)
stropt = StrOption('s', '', requires=[{'option': boolopt,
'expected': False,
'action': 'disabled'}])
linkopt = SymLinkOption("c", stropt)
descr = OptionDescription('opt', '', [boolopt, stropt, linkopt])
api = Config(descr)
api.property.read_write()
assert api.option('b').value.get() is True
assert api.option('s').value.get() is None
assert api.option('c').value.get() is None
api.option('b').value.set(False)
#
props = []
try:
api.option('s').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert props == ['disabled']
else:
assert props == {'disabled'}
#
props = []
try:
api.option('c').value.get()
except PropertiesOptionError as err:
props = err.proptype
if TIRAMISU_VERSION == 2:
assert props == ['disabled']
else:
assert props == {'disabled'}
def test_symlink_multi():
boolopt = BoolOption("b", "", default=[False], multi=True)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
assert api.option('s1.b').value.get() == [False]
assert api.option('c').value.get() == [False]
api.option('s1.b').value.set([True])
assert api.option('s1.b').value.get() == [True]
assert api.option('c').value.get() == [True]
api.option('s1.b').value.set([False])
assert api.option('s1.b').value.get() == [False]
assert api.option('c').value.get() == [False]
api.option('s1.b').value.set([False, True])
assert api.option('s1.b').value.get() == [False, True]
assert api.option('c').value.get() == [False, True]
assert boolopt.impl_is_multi() is True
assert linkopt.impl_is_multi() is True
def test_symlink_assign():
if TIRAMISU_VERSION != 2:
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
raises(ConfigError, "api.option('c').value.set(True)")
def test_symlink_owner():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
assert api.option('s1.b').owner.isdefault()
assert api.option('c').owner.isdefault()
api.option('s1.b').value.set(True)
assert not api.option('s1.b').owner.isdefault()
assert not api.option('c').owner.isdefault()
def test_symlink_get_information():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
boolopt.impl_set_information('test', 'test')
assert boolopt.impl_get_information('test') == 'test'
assert linkopt.impl_get_information('test') == 'test'
boolopt.impl_set_information('test', 'test2')
assert boolopt.impl_get_information('test') == 'test2'
assert linkopt.impl_get_information('test') == 'test2'
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)
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
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)
raises(ValueError, "Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])")
def test_symlink_with_leader():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
leader = SymLinkOption('leader', ip_admin_eth0)
od = OptionDescription('root', '', [interface1, leader])
api = Config(od)
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'leader': []}
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'leader': ['val1', 'val2']}
def test_symlink_with_follower():
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)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
follower = SymLinkOption('follower', netmask_admin_eth0)
od = OptionDescription('root', '', [interface1, follower])
api = Config(od)
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': [], 'ip_admin_eth0.netmask_admin_eth0': [], 'follower': []}
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['val1', 'val2'])
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, None], 'follower': [None, None]}
#
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == None
assert api.option('follower', 0).value.get() == None
assert api.option('follower', 1).value.get() == None
#
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('val3')
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['val1', 'val2'], 'ip_admin_eth0.netmask_admin_eth0': [None, 'val3'], 'follower': [None, 'val3']}
#
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() == None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == 'val3'
assert api.option('follower', 0).value.get() == None
assert api.option('follower', 1).value.get() == 'val3'
#____________________________________________________________
def test_symlink_dependency():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
assert api.option('s1.b').option.has_dependency() is False
assert api.option('c').option.has_dependency() is True
assert api.option('s1.b').option.has_dependency(False) is True
assert api.option('c').option.has_dependency(False) is False
def test_symlink_makedict():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
assert api.value.dict() == {'c': False, 's1.b': False}
api.option('s1.b').value.set(True)
assert api.value.dict() == {'c': True, 's1.b': True}
def test_symlink_list():
boolopt = BoolOption("b", "", default=False)
linkopt = SymLinkOption("c", boolopt)
descr = OptionDescription("opt", "",
[linkopt, OptionDescription("s1", "", [boolopt])])
api = Config(descr)
list_opt = []
for opt in api.option.list():
list_opt.append(opt.option.path())
assert list_opt == ['c']
#
list_opt = []
for opt in api.option.list(recursive=True):
list_opt.append(opt.option.path())
assert list_opt == ['c', 's1.b']

View File

@ -10,7 +10,7 @@ from .autopath import do_autopath
do_autopath()
from tiramisu import Config, MetaConfig, \
StrOption, SymLinkOption, OptionDescription, Leadership, DynOptionDescription, \
submulti, undefined, owners, Params, ParamOption
submulti, undefined, owners, Params, ParamOption, Calculation
from tiramisu.error import PropertiesOptionError, APIError, ConfigError, LeadershipError
ICON = u'\u2937'
@ -83,30 +83,34 @@ def _autocheck_default_value(cfg, path, conf, **kwargs):
# test default value (should be empty)
# cannot test for follower (we cannot get all values for a follower)
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
with warnings.catch_warnings(record=True) as w:
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(path).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(path).value.get() == empty_value
assert cfg_.option(path).value.get() == empty_value
assert cfg_.forcepermissive.option(path).value.get() == empty_value
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(path).value.get()")
assert cfg.config(conf).forcepermissive.option(path).value.get() == empty_value
raises(PropertiesOptionError, "cfg_.option(path).value.get()")
assert cfg_.forcepermissive.option(path).value.get() == empty_value
else:
raises(PropertiesOptionError, "cfg.config(conf).option(path).value.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(path).value.get()")
raises(PropertiesOptionError, "cfg_.option(path).value.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(path).value.get()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(path, 0).value.get() == empty_value
assert cfg.config(conf).option(path, 1).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(path, 0).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(path, 1).value.get() == empty_value
assert cfg_.option(path, 0).value.get() == empty_value
assert cfg_.option(path, 1).value.get() == empty_value
assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(path, 0).value.get()")
assert cfg.config(conf).forcepermissive.option(path, 0).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(path, 1).value.get() == empty_value
raises(PropertiesOptionError, "cfg_.option(path, 0).value.get()")
assert cfg_.forcepermissive.option(path, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(path, 1).value.get() == empty_value
else:
raises(PropertiesOptionError, "cfg.config(conf).option(path, 0).value.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(path, 0).value.get()")
raises(PropertiesOptionError, "cfg_.option(path, 0).value.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(path, 0).value.get()")
def _set_value(cfg, pathwrite, conf, **kwargs):
@ -131,60 +135,65 @@ def _set_value(cfg, pathwrite, conf, **kwargs):
# for follower should have an index and good length
# for leader must append, not set
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
with warnings.catch_warnings(record=True) as w:
if isleader:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
raises(APIError, "cfg.config(conf).option(pathwrite, 0).value.set(first_value[0])")
raises(APIError, "cfg_.option(pathwrite, 0).value.set(first_value[0])")
if not set_permissive:
cfg.config(conf).option(pathwrite).value.set([first_value[0]])
cfg_.option(pathwrite).value.set([first_value[0]])
else:
cfg.config(conf).forcepermissive.option(pathwrite).value.set([first_value[0]])
cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite).value.set([first_value[0]])")
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set([first_value[0]])")
if set_permissive:
cfg.config(conf).forcepermissive.option(pathwrite).value.set([first_value[0]])
cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite).value.set([first_value[0]])")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathwrite).value.set([first_value[0]])")
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set([first_value[0]])")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite).value.set([first_value[0]])")
if len(first_value) > 1:
raises(APIError, "cfg.config(conf).unrestraint.option(pathwrite).value.set(first_value[1])")
raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set(first_value[1])")
elif isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not set_permissive:
cfg.config(conf).option(pathwrite, 1).value.set(second_value)
cfg_.option(pathwrite, 1).value.set(second_value)
else:
cfg.config(conf).forcepermissive.option(pathwrite, 1).value.set(second_value)
cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite, 1).value.set(second_value)")
raises(PropertiesOptionError, "cfg_.option(pathwrite, 1).value.set(second_value)")
if set_permissive:
cfg.config(conf).forcepermissive.option(pathwrite, 1).value.set(second_value)
cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite, 1).value.set(second_value)")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathwrite, 1).value.set(second_value)")
raises(APIError, "cfg.config(conf).unrestraint.option(pathwrite).value.set([second_value, second_value])")
raises(PropertiesOptionError, "cfg_.option(pathwrite, 1).value.set(second_value)")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite, 1).value.set(second_value)")
raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set([second_value, second_value])")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not set_permissive:
cfg.config(conf).option(pathwrite).value.set(first_value)
cfg_.option(pathwrite).value.set(first_value)
else:
cfg.config(conf).forcepermissive.option(pathwrite).value.set(first_value)
cfg_.forcepermissive.option(pathwrite).value.set(first_value)
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite).value.set(first_value)")
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set(first_value)")
if set_permissive:
cfg.config(conf).forcepermissive.option(pathwrite).value.set(first_value)
cfg_.forcepermissive.option(pathwrite).value.set(first_value)
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathwrite).value.set(first_value)")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathwrite).value.set(first_value)")
#FIXME raises(APIError, "cfg.config(conf).unrestraint.option(pathwrite).value.set(first_value)")
raises(PropertiesOptionError, "cfg_.option(pathwrite).value.set(first_value)")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathwrite).value.set(first_value)")
#FIXME raises(APIError, "cfg_.unrestraint.option(pathwrite).value.set(first_value)")
def _getproperties(multi, isfollower, kwargs):
# define properties
properties = copy(PROPERTIES_LIST)
if multi and not isfollower:
default_props = ['empty']
default_props = ['empty', 'unique']
properties.append('empty')
properties.append('unique')
else:
default_props = []
extra_properties = kwargs.get('extra_properties')
@ -195,37 +204,41 @@ def _getproperties(multi, isfollower, kwargs):
def _check_properties(cfg, mcfg, pathread, conf, kwargs, props_permissive, props):
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if not cfg.unrestraint.option(pathread).option.isfollower():
if not kwargs.get('permissive_od', False):
assert set(cfg.config(conf).option(pathread).property.get()) == set(props_permissive)
assert set(cfg.config(conf).option(pathread).property.get()) == set(props)
assert set(cfg_.option(pathread).property.get()) == set(props_permissive)
assert set(cfg_.option(pathread).property.get()) == set(props)
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).property.get()")
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).property.get()")
assert set(cfg.config(conf).forcepermissive.option(pathread).property.get()) == set(props_permissive)
assert set(cfg.config(conf).forcepermissive.option(pathread).property.get()) == set(props)
assert set(cfg.config(conf).unrestraint.option(pathread).property.get()) == set(props_permissive)
assert set(cfg.config(conf).unrestraint.option(pathread).property.get()) == set(props)
raises(PropertiesOptionError, "cfg_.option(pathread).property.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).property.get()")
assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props_permissive)
assert set(cfg_.forcepermissive.option(pathread).property.get()) == set(props)
assert set(cfg_.unrestraint.option(pathread).property.get()) == set(props_permissive)
assert set(cfg_.unrestraint.option(pathread).property.get()) == set(props)
else:
if not kwargs.get('permissive_od', False):
assert set(cfg.config(conf).option(pathread, 0).property.get()) == set(props_permissive)
assert set(cfg.config(conf).option(pathread, 0).property.get()) == set(props)
assert set(cfg_.option(pathread, 0).property.get()) == set(props_permissive)
assert set(cfg_.option(pathread, 0).property.get()) == set(props)
#
assert set(cfg.config(conf).option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg.config(conf).option(pathread, 1).property.get()) == set(props)
assert set(cfg_.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg_.option(pathread, 1).property.get()) == set(props)
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).property.get()")
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).property.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 0).property.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 0).property.get()")
#
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 1).property.get()")
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 1).property.get()")
assert set(cfg.config(conf).forcepermissive.option(pathread, 0).property.get()) == set(props_permissive)
assert set(cfg.config(conf).forcepermissive.option(pathread, 0).property.get()) == set(props)
raises(PropertiesOptionError, "cfg_.option(pathread, 1).property.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 1).property.get()")
assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props_permissive)
assert set(cfg_.forcepermissive.option(pathread, 0).property.get()) == set(props)
#
assert set(cfg.config(conf).forcepermissive.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg.config(conf).forcepermissive.option(pathread, 1).property.get()) == set(props)
assert set(cfg.config(conf).unrestraint.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg.config(conf).unrestraint.option(pathread, 1).property.get()) == set(props)
assert set(cfg_.forcepermissive.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg_.forcepermissive.option(pathread, 1).property.get()) == set(props)
assert set(cfg_.unrestraint.option(pathread, 1).property.get()) == set(props_permissive)
assert set(cfg_.unrestraint.option(pathread, 1).property.get()) == set(props)
def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
@ -236,8 +249,9 @@ def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
# define properties
properties = copy(PROPERTIES_LIST)
if multi and not isfollower:
default_props = ['empty']
default_props = ['empty', 'unique']
properties.append('empty')
properties.append('unique')
else:
default_props = []
extra_properties = kwargs.get('extra_properties')
@ -253,12 +267,16 @@ def _property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
# set properties with permissive
for prop in properties:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg.config(confread).option(pathwrite).property.add(prop)
elif not kwargs.get('propertyerror', False):
cfg.config(confread).forcepermissive.option(pathwrite).property.add(prop)
if confread is not None:
cfg_ = cfg.config(confread)
else:
cfg.config(confread).unrestraint.option(pathwrite).property.add(prop)
cfg_ = cfg
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg_.option(pathwrite).property.add(prop)
elif not kwargs.get('propertyerror', False):
cfg_.forcepermissive.option(pathwrite).property.add(prop)
else:
cfg_.unrestraint.option(pathwrite).property.add(prop)
if confwrite == confread:
_check_properties(cfg, mcfg, pathread, confwrite, kwargs, properties, properties)
else:
@ -286,64 +304,72 @@ def _autocheck_get_value(cfg, pathread, conf, **kwargs):
second_value = SUBLIST_SECOND_VALUE[1]
# get value after set value without permissive
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
with warnings.catch_warnings(record=True) as w:
if isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread, 0).value.get() == empty_value
assert cfg.config(conf).option(pathread, 1).value.get() == second_value
assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == second_value
assert cfg_.option(pathread, 0).value.get() == empty_value
assert cfg_.option(pathread, 1).value.get() == second_value
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).value.get()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get() == empty_value
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()")
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
if set_permissive:
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == second_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value
else:
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == empty_value
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).value.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).value.get()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread).value.get() == first_value
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == first_value
assert cfg_.option(pathread).value.get() == first_value
assert cfg_.forcepermissive.option(pathread).value.get() == first_value
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).value.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()")
if set_permissive:
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == first_value
assert cfg_.forcepermissive.option(pathread).value.get() == first_value
else:
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread).value.get() == empty_value
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).value.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).value.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).value.get()")
def _check_owner(cfg, pathread, conf, kwargs, owner, permissive_owner):
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread).owner.get() == owner
assert cfg.config(conf).forcepermissive.option(pathread).owner.get() == owner
assert cfg_.option(pathread).owner.get() == owner
assert cfg_.forcepermissive.option(pathread).owner.get() == owner
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.get()")
assert cfg.config(conf).forcepermissive.option(pathread).owner.get() == permissive_owner
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()")
assert cfg_.forcepermissive.option(pathread).owner.get() == permissive_owner
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.get()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread, 0).owner.get() == 'default'
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg.config(conf).option(pathread, 1).owner.get() == owner
assert cfg.config(conf).forcepermissive.option(pathread, 1).owner.get() == owner
assert cfg_.option(pathread, 0).owner.get() == 'default'
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg_.option(pathread, 1).owner.get() == owner
assert cfg_.forcepermissive.option(pathread, 1).owner.get() == owner
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 1).owner.get()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg.config(conf).forcepermissive.option(pathread, 1).owner.get() == permissive_owner
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 1).owner.get()")
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg_.forcepermissive.option(pathread, 1).owner.get() == permissive_owner
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.get()")
@autocheck
@ -373,49 +399,53 @@ def autocheck_default_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite,
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
# check if owner is a string "default" and 'isdefault'
def do(conf):
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread).owner.get() == 'default'
assert cfg.config(conf).forcepermissive.option(pathread).owner.get() == 'default'
assert cfg_.option(pathread).owner.get() == 'default'
assert cfg_.forcepermissive.option(pathread).owner.get() == 'default'
#
assert cfg.config(conf).option(pathread).owner.isdefault()
assert cfg.config(conf).forcepermissive.option(pathread).owner.isdefault()
assert cfg_.option(pathread).owner.isdefault()
assert cfg_.forcepermissive.option(pathread).owner.isdefault()
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.get()")
assert cfg.config(conf).forcepermissive.option(pathread).owner.get() == 'default'
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()")
assert cfg_.forcepermissive.option(pathread).owner.get() == 'default'
#
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.isdefault()")
assert cfg.config(conf).forcepermissive.option(pathread).owner.isdefault()
raises(PropertiesOptionError, "cfg_.option(pathread).owner.isdefault()")
assert cfg_.forcepermissive.option(pathread).owner.isdefault()
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).owner.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.get()")
#
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).owner.isdefault()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).owner.isdefault()")
raises(PropertiesOptionError, "cfg_.option(pathread).owner.isdefault()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).owner.isdefault()")
#
assert cfg.config(conf).unrestraint.option(pathread).owner.get() == 'default'
assert cfg.config(conf).unrestraint.option(pathread).owner.isdefault()
assert cfg_.unrestraint.option(pathread).owner.get() == 'default'
assert cfg_.unrestraint.option(pathread).owner.isdefault()
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread, 0).owner.get() == 'default'
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.get() == 'default'
assert cfg_.option(pathread, 0).owner.get() == 'default'
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
#
assert cfg.config(conf).option(pathread, 0).owner.isdefault()
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.isdefault()
assert cfg_.option(pathread, 0).owner.isdefault()
assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault()
elif not kwargs.get('propertyerror', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.get()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.get() == 'default'
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()")
assert cfg_.forcepermissive.option(pathread, 0).owner.get() == 'default'
#
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.isdefault()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.isdefault()
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.isdefault()")
assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault()
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.get()")
#
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).owner.isdefault()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread, 0).owner.isdefault()")
assert cfg.config(conf).unrestraint.option(pathread, 0).owner.get() == 'default'
assert cfg.config(conf).unrestraint.option(pathread, 0).owner.isdefault()
raises(PropertiesOptionError, "cfg_.option(pathread, 0).owner.isdefault()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread, 0).owner.isdefault()")
assert cfg_.unrestraint.option(pathread, 0).owner.get() == 'default'
assert cfg_.unrestraint.option(pathread, 0).owner.isdefault()
do(confread)
if confread != confwrite:
do(confwrite)
@ -450,40 +480,44 @@ def autocheck_get_value_permissive(cfg, mcfg, pathread, pathwrite, confread, con
def do(conf):
# get value after set value without permissive
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread, 0).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg_.option(pathread, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
if submulti_:
assert cfg.config(conf).option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
assert cfg_.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
assert cfg_.forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
else:
assert cfg.config(conf).option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
assert cfg_.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "assert cfg.config(conf).option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg.config(conf).option(pathread, 1).value.get()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get() == empty_value
raises(PropertiesOptionError, "assert cfg_.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg_.option(pathread, 1).value.get()")
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
if submulti_:
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
assert cfg_.forcepermissive.option(pathread, 1).value.get() == SUBLIST_SECOND_VALUE[1]
else:
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
assert cfg_.forcepermissive.option(pathread, 1).value.get() == LIST_SECOND_VALUE[1]
else:
raises(PropertiesOptionError, "assert cfg.config(conf).option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg.config(conf).option(pathread, 1).value.get()")
raises(PropertiesOptionError, "assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get()")
raises(PropertiesOptionError, "assert cfg_.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg_.option(pathread, 1).value.get()")
raises(PropertiesOptionError, "assert cfg_.forcepermissive.option(pathread, 0).value.get()")
raises(PropertiesOptionError, "assert cfg_.forcepermissive.option(pathread, 1).value.get()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
with warnings.catch_warnings(record=True) as w:
assert cfg.config(conf).option(pathread).value.get() == first_value
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == first_value
assert cfg_.option(pathread).value.get() == first_value
assert cfg_.forcepermissive.option(pathread).value.get() == first_value
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).value.get()")
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == first_value
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()")
assert cfg_.forcepermissive.option(pathread).value.get() == first_value
else:
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).value.get()")
raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).value.get()")
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()")
raises(PropertiesOptionError, "cfg_.forcepermissive.option(pathread).value.get()")
with warnings.catch_warnings(record=True) as w:
do(confread)
if confread != confwrite:
@ -515,8 +549,12 @@ def autocheck_value_follower(cfg, mcfg, pathread, pathwrite, confread, confwrite
empty_value = kwargs['default']
def do(conf):
length = cfg.config(conf).option(pathread).value.len()
assert cfg.config(conf).forcepermissive.option(pathread).value.len() == length
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
length = cfg_.option(pathread).value.len()
assert cfg_.forcepermissive.option(pathread).value.len() == length
assert length == 2
do(confread)
if confread != confwrite:
@ -567,33 +605,41 @@ def autocheck_reset_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, *
# reset value without permissive
with warnings.catch_warnings(record=True) as w:
if confwrite is not None:
cfg_ = cfg.config(confwrite)
else:
cfg_ = cfg
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg.config(confwrite).option(pathwrite).value.reset()
cfg_.option(pathwrite).value.reset()
#else:
#FIXME raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite).value.reset()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg.config(confwrite).option(pathwrite, 0).value.reset()
cfg_.option(pathwrite, 0).value.reset()
#else:
#FIXME raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite, 0).value.reset()")
# get value after reset value without permissive
def do(conf):
if confwrite is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread, 0).value.get() == empty_value
assert cfg.config(conf).option(pathread, 1).value.get() == second_value[1]
assert cfg_.option(pathread, 0).value.get() == empty_value
assert cfg_.option(pathread, 1).value.get() == second_value[1]
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread, 0).value.get()")
assert cfg.config(conf).forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg.config(conf).forcepermissive.option(pathread, 1).value.get() == second_value[1]
raises(PropertiesOptionError, "cfg_.option(pathread, 0).value.get()")
assert cfg_.forcepermissive.option(pathread, 0).value.get() == empty_value
assert cfg_.forcepermissive.option(pathread, 1).value.get() == second_value[1]
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(conf).option(pathread).value.get() == empty_value
assert cfg_.option(pathread).value.get() == empty_value
elif kwargs.get('permissive', False):
raises(PropertiesOptionError, "cfg.config(conf).option(pathread).value.get()")
assert cfg.config(conf).forcepermissive.option(pathread).value.get() == first_value
raises(PropertiesOptionError, "cfg_.option(pathread).value.get()")
assert cfg_.forcepermissive.option(pathread).value.get() == first_value
with warnings.catch_warnings(record=True) as w:
do(confread)
if confread != confwrite:
@ -606,16 +652,27 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
submulti_ = cfg.unrestraint.option(pathread).option.issubmulti()
if not isleader:
return
if confread is not None:
cfg_ = cfg.config(confread)
else:
cfg_ = cfg
if confwrite is not None:
cfg2_ = cfg.config(confwrite)
else:
cfg2_ = cfg
with warnings.catch_warnings(record=True) as w:
if not kwargs.get('propertyerror', False):
leader_value = cfg.config(confread).forcepermissive.option(pathread).value.get()
leader_value = cfg_.forcepermissive.option(pathread).value.get()
v3 = cfg_.forcepermissive.option(pathread).value.get()
len_value = len(leader_value)
leader_value.append(undefined)
assert len(cfg.config(confread).forcepermissive.option(pathread).value.get()) == len_value
print('debut', leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
assert len(cfg_.forcepermissive.option(pathread).value.get()) == len_value
with warnings.catch_warnings(record=True) as w:
cfg.forcepermissive.config(confwrite).option(pathread).value.set(leader_value)
new_leader_value = cfg.config(confread).forcepermissive.option(pathread).value.get()
cfg2_.forcepermissive.option(pathread).value.set(leader_value)
new_leader_value = cfg_.forcepermissive.option(pathread).value.get()
len_new = len(new_leader_value)
assert len_value + 1 == len_new
assert new_leader_value[-1] == kwargs['default_multi']
@ -625,16 +682,21 @@ def autocheck_append_value(cfg, mcfg, pathread, pathwrite, confread, confwrite,
else:
follower_path += '.third'
for idx in range(len_new):
assert cfg.config(confread).forcepermissive.option(follower_path, idx).value.get() == kwargs['default_multi']
assert cfg_.forcepermissive.option(follower_path, idx).value.get() == kwargs['default_multi']
#
if not submulti_:
value = 'value'
else:
value = ['value']
print('==>>>')
print(leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
leader_value.append(value)
assert len(cfg.config(confread).forcepermissive.option(pathread).value.get()) == len(new_leader_value)
cfg.forcepermissive.config(confwrite).option(pathread).value.set(leader_value)
assert cfg.config(confread).forcepermissive.option(pathread).value.get()[-1] == value
print(leader_value, cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0])
print(id(leader_value), id(cfg_._config_bag.context._impl_values_cache._cache['odleader.first'][None][0]))
assert len(cfg_.forcepermissive.option(pathread).value.get()) == len(new_leader_value)
cfg2_.forcepermissive.option(pathread).value.set(leader_value)
assert cfg_.forcepermissive.option(pathread).value.get()[-1] == value
@autocheck
@ -644,6 +706,14 @@ def autocheck_pop_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
if not isleader:
return
if confwrite is not None:
cfg_ = cfg.config(confwrite)
else:
cfg_ = cfg
if confread is not None:
cfg2_ = cfg.config(confread)
else:
cfg2_ = cfg
if not kwargs.get('propertyerror', False):
if not submulti_:
values = ['value1', 'value2', 'value3', 'value4']
@ -658,34 +728,34 @@ def autocheck_pop_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
else:
a_follower += '.third'
with warnings.catch_warnings(record=True) as w:
cfg.forcepermissive.config(confwrite).option(pathread).value.set(values)
cfg.forcepermissive.config(confwrite).option(a_follower, 1).value.set(follower_value)
cfg.config(confread).forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 0).owner.isdefault() is True
cfg.config(confread).forcepermissive.option(a_follower, 1).value.get() == follower_value
assert cfg.config(confread).forcepermissive.option(a_follower, 1).owner.isdefault() is False
cfg.config(confread).forcepermissive.option(a_follower, 2).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 2).owner.isdefault() is True
cfg.config(confread).forcepermissive.option(a_follower, 3).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 3).owner.isdefault() is True
cfg_.forcepermissive.option(pathread).value.set(values)
cfg_.forcepermissive.option(a_follower, 1).value.set(follower_value)
cfg2_.forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 0).owner.isdefault() is True
cfg2_.forcepermissive.option(a_follower, 1).value.get() == follower_value
assert cfg2_.forcepermissive.option(a_follower, 1).owner.isdefault() is False
cfg2_.forcepermissive.option(a_follower, 2).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 2).owner.isdefault() is True
cfg2_.forcepermissive.option(a_follower, 3).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 3).owner.isdefault() is True
#
cfg.forcepermissive.config(confwrite).option(pathread).value.pop(3)
cfg.config(confread).forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 0).owner.isdefault() is True
cfg.config(confread).forcepermissive.option(a_follower, 1).value.get() == follower_value
assert cfg.config(confread).forcepermissive.option(a_follower, 1).owner.isdefault() is False
cfg.config(confread).forcepermissive.option(a_follower, 2).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 2).owner.isdefault() is True
cfg_.forcepermissive.option(pathread).value.pop(3)
cfg2_.forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 0).owner.isdefault() is True
cfg2_.forcepermissive.option(a_follower, 1).value.get() == follower_value
assert cfg2_.forcepermissive.option(a_follower, 1).owner.isdefault() is False
cfg2_.forcepermissive.option(a_follower, 2).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 2).owner.isdefault() is True
#
cfg.forcepermissive.config(confwrite).option(pathread).value.pop(0)
cfg.config(confread).forcepermissive.option(a_follower, 0).value.get() == follower_value
assert cfg.config(confread).forcepermissive.option(a_follower, 0).owner.isdefault() is False
cfg.config(confread).forcepermissive.option(a_follower, 1).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 1).owner.isdefault() is True
cfg_.forcepermissive.option(pathread).value.pop(0)
cfg2_.forcepermissive.option(a_follower, 0).value.get() == follower_value
assert cfg2_.forcepermissive.option(a_follower, 0).owner.isdefault() is False
cfg2_.forcepermissive.option(a_follower, 1).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 1).owner.isdefault() is True
#
cfg.forcepermissive.config(confwrite).option(pathread).value.pop(0)
cfg.config(confread).forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg.config(confread).forcepermissive.option(a_follower, 0).owner.isdefault() is True
cfg_.forcepermissive.option(pathread).value.pop(0)
cfg2_.forcepermissive.option(a_follower, 0).value.get() == kwargs['default_multi']
assert cfg2_.forcepermissive.option(a_follower, 0).owner.isdefault() is True
@autocheck
@ -697,12 +767,20 @@ def autocheck_reset_value_permissive(cfg, mcfg, pathread, pathwrite, confread, c
with warnings.catch_warnings(record=True) as w:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
if not isfollower:
cfg.forcepermissive.config(confwrite).option(pathwrite).value.reset()
if confwrite is not None:
cfg_ = cfg.forcepermissive.config(confwrite)
else:
cfg_ = cfg.forcepermissive
cfg_.option(pathwrite).value.reset()
else:
cfg.forcepermissive.option(pathwrite, 1).value.reset()
elif kwargs.get('permissive', False):
if not isfollower:
cfg.forcepermissive.config(confwrite).option(pathwrite).value.reset()
if confwrite is not None:
cfg_ = cfg.forcepermissive.config(confwrite)
else:
cfg_ = cfg.forcepermissive
cfg_.option(pathwrite).value.reset()
else:
cfg.forcepermissive.option(pathwrite, 1).value.reset()
#FIXME else:
@ -723,13 +801,21 @@ def autocheck_display(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwa
return
make_dict = kwargs['make_dict']
make_dict_value = kwargs['make_dict_value']
assert cfg.config(confread).value.dict() == make_dict
if confread is not None:
cfg_ = cfg.config(confread)
else:
cfg_ = cfg
if confwrite is not None:
cfg2_ = cfg.config(confwrite)
else:
cfg2_ = cfg
assert cfg_.value.dict() == make_dict
if confread != confwrite:
assert(cfg.config(confwrite).value.dict()) == make_dict
assert(cfg2_.value.dict()) == make_dict
_set_value(cfg, pathwrite, confwrite, **kwargs)
assert cfg.config(confread).value.dict() == make_dict_value
assert cfg_.value.dict() == make_dict_value
if confread != confwrite:
assert(cfg.config(confwrite).value.dict()) == make_dict_value
assert(cfg2_.value.dict()) == make_dict_value
@autocheck
@ -749,7 +835,11 @@ def autocheck_property(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kw
# set properties without permissive
for prop in properties:
cfg.unrestraint.config(confwrite).option(pathwrite).property.add(prop)
if confwrite is not None:
cfg_ = cfg.unrestraint.config(confwrite)
else:
cfg_ = cfg.unrestraint
cfg_.option(pathwrite).property.add(prop)
if confread == confwrite:
_check_properties(cfg, mcfg, pathread, confread, kwargs, properties, properties)
else:
@ -774,7 +864,11 @@ def autocheck_reset_property(cfg, mcfg, pathread, pathwrite, confread, confwrite
_property_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs)
# reset properties without permissive
cfg.unrestraint.config(confwrite).option(pathwrite).property.reset()
if confwrite is not None:
cfg_ = cfg.unrestraint.config(confwrite)
else:
cfg_ = cfg.unrestraint
cfg_.option(pathwrite).property.reset()
if confread == confwrite:
_check_properties(cfg, mcfg, pathread, confread, kwargs, default_props, default_props)
@ -819,22 +913,28 @@ def autocheck_default_owner_with_value(cfg, mcfg, pathread, pathwrite, confread,
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None:
cfg_ = cfg.config(confread)
cfg2_ = cfg.config(confwrite)
else:
cfg_ = cfg
cfg2_ = cfg
# test if is default owner without permissive
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(confwrite).option(pathread).owner.isdefault() is False
assert cfg_.option(pathread).owner.isdefault() is False
if confwrite != confread:
assert cfg.config(confread).option(pathread).owner.isdefault() is False
assert cfg2_.option(pathread).owner.isdefault() is False
#FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathread).owner.isdefault()")
# raises(PropertiesOptionError, "cfg.config(confread).option(pathread).owner.isdefault()")
else:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert cfg.config(confwrite).option(pathread, 0).owner.isdefault() is True
assert cfg.config(confwrite).option(pathread, 1).owner.isdefault() is False
assert cfg2_.option(pathread, 0).owner.isdefault() is True
assert cfg2_.option(pathread, 1).owner.isdefault() is False
if confwrite != confread:
assert cfg.config(confread).option(pathread, 0).owner.isdefault() is True
assert cfg.config(confread).option(pathread, 1).owner.isdefault() is False
assert cfg_.option(pathread, 0).owner.isdefault() is True
assert cfg_.option(pathread, 1).owner.isdefault() is False
#FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathread, 0).owner.isdefault()")
# raises(PropertiesOptionError, "cfg.config(confread).option(pathread, 0).owner.isdefault()")
@ -849,14 +949,16 @@ def autocheck_default_owner_with_value_permissive(cfg, mcfg, pathread, pathwrite
def do(conf):
# test if is default owner with permissive
if conf is not None:
cfg_ = cfg.config(conf)
else:
cfg_ = cfg
if not kwargs.get('propertyerror', False):
if not isfollower:
assert cfg.config(conf).forcepermissive.option(pathread).owner.isdefault() is False
assert cfg_.forcepermissive.option(pathread).owner.isdefault() is False
else:
assert cfg.config(conf).forcepermissive.option(pathread, 0).owner.isdefault() is True
assert cfg.config(conf).forcepermissive.option(pathread, 1).owner.isdefault() is False
#FIXME else:
# raises(PropertiesOptionError, "cfg.config(conf).forcepermissive.option(pathread).owner.isdefault()")
assert cfg_.forcepermissive.option(pathread, 0).owner.isdefault() is True
assert cfg_.forcepermissive.option(pathread, 1).owner.isdefault() is False
do(confwrite)
if confwrite != confread:
do(confread)
@ -865,11 +967,15 @@ def autocheck_default_owner_with_value_permissive(cfg, mcfg, pathread, pathwrite
@autocheck
def autocheck_set_owner_no_value(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs):
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
if confwrite is not None:
cfg_ = cfg.forcepermissive.config(confwrite)
else:
cfg_ = cfg.forcepermissive
if not kwargs.get('propertyerror', False):
if not isfollower:
raises(ConfigError, "cfg.forcepermissive.config(confwrite).option(pathwrite).owner.set('new_user')")
raises(ConfigError, "cfg_.option(pathwrite).owner.set('new_user')")
else:
raises(ConfigError, "cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user')")
raises(ConfigError, "cfg_.option(pathwrite, 1).owner.set('new_user')")
@autocheck
@ -878,13 +984,17 @@ def autocheck_set_owner(cfg, mcfg, pathread, pathwrite, confread, confwrite, **k
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None:
cfg_ = cfg.config(confwrite)
else:
cfg_ = cfg
# set owner without permissive
if not isfollower:
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
cfg.config(confwrite).option(pathwrite).owner.set('new_user')
raises(ValueError, "cfg.config(confwrite).option(pathwrite).owner.set('default')")
raises(ValueError, "cfg.config(confwrite).option(pathwrite).owner.set('forced')")
cfg_.option(pathwrite).owner.set('new_user')
raises(ValueError, "cfg_.option(pathwrite).owner.set('default')")
raises(ValueError, "cfg_.option(pathwrite).owner.set('forced')")
#FIXME else:
# raises(PropertiesOptionError, "cfg.config(confwrite).option(pathwrite).owner.set('new_user')")
else:
@ -903,11 +1013,15 @@ def autocheck_set_owner_permissive(cfg, mcfg, pathread, pathwrite, confread, con
isfollower = cfg.unrestraint.option(pathread).option.isfollower()
_set_value(cfg, pathwrite, confwrite, **kwargs)
if confwrite is not None:
cfg_ = cfg.forcepermissive.config(confwrite)
else:
cfg_ = cfg.forcepermissive
# set owner with permissive
if not kwargs.get('propertyerror', False):
if not isfollower:
cfg.forcepermissive.config(confwrite).option(pathwrite).owner.set('new_user1')
cfg_.option(pathwrite).owner.set('new_user1')
else:
cfg.forcepermissive.option(pathwrite, 1).owner.set('new_user1')
#FIXME else:
@ -961,9 +1075,17 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
"""test permissive for hidden and disabled value
"""
# no permissive before
assert cfg.unrestraint.config(confwrite).option(pathread).permissive.get() == frozenset()
if confwrite is not None:
cfg_ = cfg.unrestraint.config(confwrite)
else:
cfg_ = cfg.unrestraint
if confread is not None:
cfg2_ = cfg.config(confread).unrestraint
else:
cfg2_ = cfg.unrestraint
assert cfg_.option(pathread).permissive.get() == frozenset()
if kwargs.get('permissive_od', False):
assert cfg.unrestraint.config(confwrite).option(pathread.rsplit('.', 1)[0]).permissive.get() == frozenset()
assert cfg_.option(pathread.rsplit('.', 1)[0]).permissive.get() == frozenset()
# cannot access to hidden value without forcepermissive
# and to disabled value (with forcepermissive too)
@ -972,17 +1094,17 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
_autocheck_default_value(cfg, pathread, confread, **kwargs)
# set permissive
cfg.unrestraint.config(confwrite).option(pathwrite).permissive.set(frozenset(['disabled']))
cfg_.option(pathwrite).permissive.set(frozenset(['disabled']))
callback = kwargs['callback']
if callback:
if pathread.endswith('val1') or pathread.endswith('val2'):
call_path = pathread[:-4] + 'call' + pathread[-4:]
else:
call_path = pathread + 'call'
cfg.unrestraint.config(confwrite).option(call_path).permissive.set(frozenset(['disabled']))
cfg_.option(call_path).permissive.set(frozenset(['disabled']))
# have permissive?
assert cfg.unrestraint.config(confwrite).option(pathread).permissive.get() == frozenset(['disabled'])
assert cfg_.option(pathread).permissive.get() == frozenset(['disabled'])
#if confwrite != confread:
# assert cfg.config(confread).unrestraint.option(pathread).permissive.get() == frozenset(['disabled'])
@ -991,9 +1113,9 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
ckwargs['propertyerror'] = False
_autocheck_default_value(cfg, pathread, confwrite, **ckwargs)
cfg.config(confread).unrestraint.option(pathwrite).permissive.set(frozenset(['disabled', 'hidden']))
cfg2_.option(pathwrite).permissive.set(frozenset(['disabled', 'hidden']))
if kwargs['callback']:
cfg.config(confread).unrestraint.option(call_path).permissive.set(frozenset(['disabled', 'hidden']))
cfg2_.option(call_path).permissive.set(frozenset(['disabled', 'hidden']))
# can access to all value except when optiondescript have hidden
if not ckwargs.get('permissive_od', False):
@ -1002,7 +1124,7 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
if ckwargs.get('permissive_od', False):
# set permissive to OptionDescription
cfg.config(confread).unrestraint.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset(['disabled',
cfg2_.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset(['disabled',
'hidden']))
ckwargs['permissive'] = False
_autocheck_default_value(cfg, pathread, confread, **ckwargs)
@ -1010,23 +1132,23 @@ def autocheck_permissive(cfg, mcfg, pathread, pathwrite, confread, confwrite, **
# _autocheck_default_value(cfg, pathread, confwrite, **ckwargs)
# only hidden
cfg.config(confread).unrestraint.option(pathwrite).permissive.set(frozenset(['hidden']))
cfg2_.option(pathwrite).permissive.set(frozenset(['hidden']))
if callback:
cfg.config(confread).unrestraint.option(call_path).permissive.set(frozenset(['hidden']))
cfg2_.option(call_path).permissive.set(frozenset(['hidden']))
if ckwargs.get('permissive_od', False):
_autocheck_default_value(cfg, pathread, confread, **ckwargs)
cfg.config(confread).unrestraint.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset(['hidden']))
cfg2_.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset(['hidden']))
ckwargs = copy(kwargs)
ckwargs['permissive'] = False
_autocheck_default_value(cfg, pathread, confread, **ckwargs)
# no permissive
cfg.config(confread).unrestraint.option(pathwrite).permissive.set(frozenset())
cfg2_.option(pathwrite).permissive.set(frozenset())
if callback:
cfg.config(confread).unrestraint.option(call_path).permissive.set(frozenset())
cfg2_.option(call_path).permissive.set(frozenset())
if ckwargs.get('permissive_od', False):
_autocheck_default_value(cfg, pathread, confread, **ckwargs)
cfg.config(confread).unrestraint.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset())
cfg2_.option(pathwrite.rsplit('.', 1)[0]).permissive.set(frozenset())
_autocheck_default_value(cfg, pathread, confread, **kwargs)
@ -1060,23 +1182,27 @@ def autocheck_find(cfg, mcfg, pathread, pathwrite, confread, confwrite, **kwargs
option = _getoption(cfg.unrestraint.option(pathread))
def do(conf):
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert option == _getoption(cfg.config(conf).option.find(name, first=True))
assert option == _getoption(cfg.config(conf).forcepermissive.option.find(name, first=True))
elif kwargs.get('permissive', False):
raises(AttributeError, "cfg.config(conf).option.find(name, first=True)")
assert option == _getoption(cfg.config(conf).forcepermissive.option.find(name, first=True))
if conf is not None:
cfg_ = cfg.config(conf)
else:
raises(AttributeError, "cfg.config(conf).option.find(name, first=True)")
raises(AttributeError, "cfg.config(conf).forcepermissive.option.find(name, first=True)")
assert option == _getoption(cfg.config(conf).unrestraint.option.find(name, first=True))
assert [option] == _getoptions(cfg.config(conf).unrestraint.option.find(name))
cfg_ = cfg
if not kwargs.get('permissive', False) and not kwargs.get('propertyerror', False):
assert option == _getoption(cfg_.option.find(name, first=True))
assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True))
elif kwargs.get('permissive', False):
raises(AttributeError, "cfg_.option.find(name, first=True)")
assert option == _getoption(cfg_.forcepermissive.option.find(name, first=True))
else:
raises(AttributeError, "cfg_.option.find(name, first=True)")
raises(AttributeError, "cfg_.forcepermissive.option.find(name, first=True)")
assert option == _getoption(cfg_.unrestraint.option.find(name, first=True))
assert [option] == _getoptions(cfg_.unrestraint.option.find(name))
do(confread)
if confread != confwrite:
do(confwrite)
def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, consistency, callback, symlink, weakrefs, **kwargs):
def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, callback, symlink, weakrefs, **kwargs):
def _build_make_dict():
dico = {}
dico_value = {}
@ -1168,31 +1294,6 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
if symlink:
dico['extraoptrequirelink'] = 'value'
dico_value['extraoptrequirelink'] = 'value'
if consistency and has_value:
cpath = list(dico.keys())[0]
if "." in cpath:
cpath = cpath.rsplit('.', 1)[0] + '.'
else:
cpath = ''
if multi:
value = []
else:
value = None
if is_dyn:
dico[cpath + 'extraoptconsistencyval1'] = value
dico_value[cpath + 'extraoptconsistencyval1'] = value
if is_leader:
spath = cpath.split('.')
spath[-2] = spath[-2][:-1] + '2'
spath[-3] = spath[-3][:-1] + '2'
npath = '.'.join(spath) + 'extraoptconsistencyval2'
else:
npath = cpath[:-2] + '2.' + 'extraoptconsistencyval2'
dico[npath] = value
dico_value[npath] = value
else:
dico[cpath + 'extraoptconsistency'] = value
dico_value[cpath + 'extraoptconsistency'] = value
if is_leader:
for cpath in list(paths_.keys())[len(dyns):]:
if cpath.endswith('.first') or cpath.endswith('.firstval1') or cpath.endswith('.firstval2'):
@ -1256,8 +1357,6 @@ def check_all(cfg, paths_, path, meta, multi, default, default_multi, require, c
text += u' with default multi'
if require:
text += u' with requirement'
if consistency:
text += u' with consistency'
text += u', kwargs: {}'.format(kwargs)
print(text)
if not require:
@ -1412,7 +1511,7 @@ def check_deref(weakrefs):
assert wrf() is None
def make_conf(options, multi, default, default_multi, require, consistency, callback, symlink):
def make_conf(options, multi, default, default_multi, require, callback, symlink):
weakrefs = []
dyn = []
goptions = []
@ -1475,7 +1574,8 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
if callback:
largs = [path + 'call', "{}'s callback option".format(path)]
objcall = tiramisu_option(*largs, **call_kwargs)
kwargs['callback_params'] = Params(ParamOption(objcall))
kwargs['default'] = Calculation(kwargs['callback'], Params(ParamOption(objcall)))
del kwargs['callback']
else:
objcall = None
if symlink and not path.endswith('extraoptconsistency'):
@ -1485,16 +1585,8 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
tiramisu_option = SymLinkOption
else:
sobj = None
print(args, kwargs)
obj = tiramisu_option(*args, **kwargs)
if not 'extraopt' in path and consistency:
if require:
if symlink:
gopt = goptions[2]
else:
gopt = goptions[1]
else:
gopt = goptions[0]
obj.impl_add_consistency('not_equal', gopt, warnings_only=True, transitive=False)
return obj, objcall, sobj
def make_optiondescriptions(path, collected):
@ -1514,7 +1606,7 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
if symlink:
return
optiondescription = DynOptionDescription
kwargs['callback'] = return_list
kwargs['suffixes'] = Calculation(return_list)
dyn.append(path)
options = []
if 'options' in collected:
@ -1533,17 +1625,10 @@ def make_conf(options, multi, default, default_multi, require, consistency, call
return obj
collect_options = {}
if require or consistency:
if require:
noptions = OrderedDict()
if require:
noptions['extraoptrequire'] = {}
if consistency:
subpath = list(options.keys())[0]
if '.' in subpath:
subpath = subpath.rsplit('.', 1)[0] + '.'
else:
subpath = ''
noptions[subpath + 'extraoptconsistency'] = {}
noptions.update(options)
else:
noptions = options
@ -1694,34 +1779,29 @@ def test_options(paths):
lpaths = list(paths.keys())
for meta in (False, True):
for callback in (False, True):
for consistency in (False, True):
for require in (False, True):
for default_multi in (False, True):
for symlink in (False, True):
if callback and default_multi:
continue
for default in (False, True):
for multi in (False, True, submulti):
pass
# for meta in (True,):
# for callback in (False,):
# for consistency in (True,):
# for require in (True,):
# for default_multi in (True,):
# for symlink in (False,):
# for meta in (False, True):
# for callback in (False, True):
# for require in (False, True):
# for default_multi in (False, True):
# for symlink in (False, True):
# if callback and default_multi:
# continue
# for default in (True,):
# for multi in (submulti,):
if multi is submulti and default:
# for default in (False, True):
# for multi in (False, True, submulti):
for meta in (False,):
for callback in (False,):
for require in (False,):
for default_multi in (False,):
for symlink in (False,):
if callback and default_multi:
continue
if multi is submulti and consistency:
for default in (False,):
for multi in (True,):
if multi is submulti and default:
continue
if multi is False and default_multi:
continue
cfg, weakrefs, dyn = make_conf(paths, multi, default, default_multi, require, consistency, callback, symlink)
cfg, weakrefs, dyn = make_conf(paths, multi, default, default_multi, require, callback, symlink)
if cfg is None:
continue
if dyn:
@ -1732,7 +1812,7 @@ def test_options(paths):
cnt += 1
else:
check_all(cfg, paths, lpaths[index], meta, multi, default,
default_multi, require, consistency, callback, symlink,
default_multi, require, callback, symlink,
weakrefs, **get_kwargs(lpaths[idx]))
idx += 1
if idx == cnt:
@ -1740,7 +1820,7 @@ def test_options(paths):
else:
for lpath in lpaths:
check_all(cfg, paths, lpath, meta, multi, default,
default_multi, require, consistency, callback, symlink,
default_multi, require, callback, symlink,
weakrefs, **get_kwargs(lpath))
del cfg
check_deref(weakrefs)

85
tests/config.py Normal file
View File

@ -0,0 +1,85 @@
# from json import dumps, loads
import asyncio
from os import environ
try:
from tiramisu_api import Config
class TestConfig(Config):
def __init__(self,
config):
self.test_option = config.option
json = self.test_option.dict()
# assert json == loads(dumps(json))
super().__init__(json)
def send_data(self,
updates):
return self.updates_data(self.test_option.updates(updates))
PARAMS = ['tiramisu', 'tiramisu-api']
except:
PARAMS = ['tiramisu']
import pytest
async def get_config(config, type, error=False):
if type == 'tiramisu':
return config
if error:
await config.property.add('demoting_error_warning')
return TestConfig(config)
def value_list(values):
if values[0] == '':
del values[0]
return tuple(values)
async def global_owner(config, config_type):
return await config.owner.get()
@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()

0
tests/dict/__init__.py Normal file
View File

View File

View File

@ -0,0 +1,43 @@
{
"schema": {
"options": {
"properties": {
"options.boolean": {
"type": "boolean",
"title": "Boolean 1"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.boolean": {
"clearable": true
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,12 @@
"""just an boolean option
"""
from tiramisu.option import BoolOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = BoolOption('boolean', "Boolean 1")
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("boolean1", "Simple boolean", [descr1])
return descr

View File

@ -0,0 +1,47 @@
{
"schema": {
"options": {
"properties": {
"options.boolean": {
"type": "boolean",
"title": "Boolean 1 frozen"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {
"options.boolean": {
"readOnly": true
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.boolean": {
"clearable": true
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,12 @@
"""just an boolean option
"""
from tiramisu.option import BoolOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = BoolOption('boolean', "Boolean 1 frozen", properties=('frozen',))
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("boolean1_frozen", "Simple boolean", [descr1])
return descr

View File

@ -0,0 +1,49 @@
{
"schema": {
"options": {
"properties": {
"options.choice": {
"type": "choice",
"enum": [
"",
"choice 1",
"choice 2"
],
"title": "Choice description"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,10 @@
from tiramisu.option import ChoiceOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice', "Choice description", ("choice 1", "choice 2"))
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("choice1", "Simple choice", [descr1])
return descr

View File

@ -0,0 +1,53 @@
{
"schema": {
"options": {
"properties": {
"options.choice": {
"type": "choice",
"enum": [
"",
"choice 1",
"choice 2"
],
"title": "Choice description frozen"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {
"options.choice": {
"readOnly": true
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,10 @@
from tiramisu.option import ChoiceOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice', "Choice description frozen", ("choice 1", "choice 2"), properties=('frozen',))
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("choice1_frozen", "Simple choice", [descr1])
return descr

View File

@ -0,0 +1,104 @@
{
"schema": {
"options": {
"properties": {
"options.choice1": {
"properties": {
"options.choice1.choice1": {
"type": "choice",
"isMulti": true,
"enum": [
"choice 1",
"choice 2"
],
"title": "Choice description leader"
},
"options.choice1.choice2": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 3",
"choice 4"
],
"title": "Choice description follower 1"
},
"options.choice1.choice3": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 5",
"choice 6"
],
"title": "Choice description follower 2"
},
"options.choice1.choice4": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 7",
"choice 8"
],
"title": "Choice description follower 3"
}
},
"type": "array",
"title": "Common configuration 1"
}
},
"type": "object",
"title": "Common configuration 2"
}
},
"model": {
"options.choice1.choice1": {
"required": true,
"properties": [
"unique"
]
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice1.choice1": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice2": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice3": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice4": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,16 @@
from tiramisu.option import ChoiceOption, OptionDescription
from tiramisu import Leadership
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice1', "Choice description leader", ("choice 1", "choice 2"), multi=True)
option1 = ChoiceOption('choice2', "Choice description follower 1", ("choice 3", "choice 4"), multi=True)
option2 = ChoiceOption('choice3', "Choice description follower 2", ("choice 5", "choice 6"), multi=True)
option3 = ChoiceOption('choice4', "Choice description follower 3", ("choice 7", "choice 8"), multi=True)
descr1 = Leadership("choice1", "Common configuration 1",
[option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1])
descr = OptionDescription("choice1_leadership", "Leader followers with choice", [descr])
return descr

View File

@ -0,0 +1,109 @@
{
"schema": {
"options": {
"properties": {
"options.choice1": {
"properties": {
"options.choice1.choice1": {
"type": "choice",
"isMulti": true,
"enum": [
"choice 1",
"choice 2"
],
"title": "Choice description leader"
},
"options.choice1.choice2": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 3",
"choice 4"
],
"title": "Choice description follower 1"
},
"options.choice1.choice3": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 5",
"choice 6"
],
"title": "Choice description follower 2 hidden"
},
"options.choice1.choice4": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 7",
"choice 8"
],
"title": "Choice description follower 3"
}
},
"type": "array",
"title": "Slave 2 is hidden"
}
},
"type": "object",
"title": "Common configuration 2"
}
},
"model": {
"options.choice1.choice1": {
"required": true,
"properties": [
"unique"
]
},
"options.choice1.choice3": {
"null": {
"display": false
}
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice1.choice1": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice2": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice3": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice4": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,16 @@
from tiramisu.option import ChoiceOption, OptionDescription
from tiramisu import Leadership
from tiramisu.setting import groups
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice1', "Choice description leader", ("choice 1", "choice 2"), multi=True)
option1 = ChoiceOption('choice2', "Choice description follower 1", ("choice 3", "choice 4"), multi=True)
option2 = ChoiceOption('choice3', "Choice description follower 2 hidden", ("choice 5", "choice 6"), multi=True, properties=('hidden',))
option3 = ChoiceOption('choice4', "Choice description follower 3", ("choice 7", "choice 8"), multi=True)
descr1 = Leadership("choice1", "Slave 2 is hidden",
[option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1])
descr = OptionDescription("choice1_leadership_hidden", "Leader follower with choice, one is hidden", [descr])
return descr

View File

@ -0,0 +1,114 @@
{
"schema": {
"options": {
"properties": {
"options.choice1": {
"properties": {
"options.choice1.choice1": {
"type": "choice",
"isMulti": true,
"enum": [
"choice 1",
"choice 2"
],
"title": "Choice leader"
},
"options.choice1.choice2": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 3",
"choice 4"
],
"title": "Choice follower 1"
},
"options.choice1.choice3": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 5",
"choice 6"
],
"title": "Choice follower 2"
},
"options.choice1.choice4": {
"type": "choice",
"isMulti": true,
"enum": [
"",
"choice 7",
"choice 8"
],
"title": "Choice follower 3"
}
},
"type": "array",
"title": "Common configuration 1"
}
},
"type": "object",
"title": "Common configuration 2"
}
},
"model": {
"options.choice1.choice1": {
"required": true,
"properties": [
"unique"
],
"value": [
"choice 2"
],
"owner": "user"
},
"options.choice1.choice2": {
"0": {
"value": "choice 4",
"owner": "user"
}
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice1.choice1": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice2": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice3": {
"clearable": true,
"type": "choice"
},
"options.choice1.choice4": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,25 @@
from tiramisu.option import ChoiceOption, OptionDescription
from tiramisu import Leadership
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice1', "Choice leader", ("choice 1", "choice 2"), multi=True)
option1 = ChoiceOption('choice2', "Choice follower 1", ("choice 3", "choice 4"), multi=True)
option2 = ChoiceOption('choice3', "Choice follower 2", ("choice 5", "choice 6"), multi=True)
option3 = ChoiceOption('choice4', "Choice follower 3", ("choice 7", "choice 8"), multi=True)
descr1 = Leadership("choice1", "Common configuration 1",
[option, option1, option2, option3])
descr = OptionDescription("options", "Common configuration 2", [descr1])
descr = OptionDescription("choice1_leadership_value", "Leader followers with choices, leader is 'choice 2' and follower 1 is 'choice 4'", [descr])
return descr
async def get_values(api, allpath=False):
if allpath:
root = 'choice1_leadership_value.'
else:
root = ''
await api.option(root + 'options.choice1.choice1').value.set(['choice 2'])
await api.option(root + 'options.choice1.choice2', 0).value.set('choice 4')

View File

@ -0,0 +1,56 @@
{
"schema": {
"options": {
"properties": {
"options.choice": {
"type": "choice",
"isMulti": true,
"enum": [
"choice 1",
"choice 2"
],
"title": "Choice description"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {
"options.choice": {
"required": true,
"properties": [
"unique"
]
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice": {
"clearable": true,
"type": "choice"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,10 @@
from tiramisu.option import ChoiceOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice', "Choice description", ("choice 1", "choice 2"), multi=True)
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("choice1_multi", "Multi choice", [descr1])
return descr

View File

@ -0,0 +1,53 @@
{
"schema": {
"options": {
"properties": {
"options.choice": {
"type": "choice",
"enum": [
"",
"choice 1",
"choice 2"
],
"title": "Choice description"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice": {
"clearable": true,
"type": "choice",
"displayed": {
"choice 1": "renamed 1",
"choice 2": "renamed 2"
}
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,20 @@
from tiramisu.option import ChoiceOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = ChoiceOption('choice', "Choice description", ("choice 1", "choice 2"))
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("choice1_rename", "Rename displayed value", [descr1])
return descr
def get_form(allpath=False):
key = 'options.choice'
if allpath:
key = 'choice1_rename.' + key
return [{'key': key,
'displayed': {'choice 1': 'renamed 1',
'choice 2': 'renamed 2'}
}]

View File

@ -0,0 +1,85 @@
{
"schema": {
"options": {
"properties": {
"options.choice": {
"type": "choice",
"enum": [
"hide",
"show"
],
"value": "hide",
"title": "Choice description"
},
"options.unicode2": {
"type": "string",
"title": "Unicode 2"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {
"options.choice": {
"required": true,
"value": "hide"
},
"options.unicode2": {
"display": false,
"hidden": true
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.choice": {
"clearable": true,
"type": "choice",
"dependencies": {
"default": {
"show": [
"options.unicode2"
]
},
"expected": {
"show": {
"show": [
"options.unicode2"
]
},
"hide": {
"hide": [
"options.unicode2"
]
}
}
}
},
"options.unicode2": {
"clearable": true,
"type": "input"
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,14 @@
from tiramisu import ChoiceOption, StrOption, OptionDescription, Calculation, ParamValue, ParamOption, Params, calc_value
def get_description():
"""generate description for this test
"""
option1 = ChoiceOption('choice', "Choice description", ("hide", "show"), default='hide', properties=('mandatory',))
hidden_property = Calculation(calc_value,
Params(ParamValue('hidden'),
kwargs={'condition': ParamOption(option1, todict=True),
'expected': ParamValue('hide')}))
option2 = StrOption('unicode2', "Unicode 2", properties=(hidden_property,))
descr1 = OptionDescription("options", "Common configuration", [option1, option2])
descr = OptionDescription("choice1_requires", "Choice with requirement", [descr1])
return descr

View File

@ -0,0 +1,44 @@
{
"schema": {
"options": {
"properties": {
"options.date": {
"type": "date",
"title": "Date description"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.date": {
"clearable": true,
"remote": true
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

9
tests/dict/data/date1.py Normal file
View File

@ -0,0 +1,9 @@
from tiramisu.option import DateOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = DateOption('date', "Date description")
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("date1", "Simple date", [descr1])
return descr

View File

@ -0,0 +1,48 @@
{
"schema": {
"options": {
"properties": {
"options.date": {
"type": "date",
"title": "Date description frozen"
}
},
"type": "object",
"title": "Common configuration"
}
},
"model": {
"options.date": {
"readOnly": true
}
},
"global": {
"owner": "user",
"properties": [
"cache",
"demoting_error_warning",
"disabled",
"force_store_value",
"frozen",
"hidden",
"validator",
"warnings"
],
"permissives": [
"hidden"
]
},
"form": {
"options.date": {
"clearable": true,
"remote": true
},
"null": [
{
"title": "Configurer",
"type": "submit"
}
]
},
"version": "1.0"
}

View File

@ -0,0 +1,9 @@
from tiramisu.option import DateOption, OptionDescription
def get_description():
"""generate description for this test
"""
option = DateOption('date', "Date description frozen", properties=('frozen',))
descr1 = OptionDescription("options", "Common configuration", [option])
descr = OptionDescription("date1_frozen", "Simple date", [descr1])
return descr

Some files were not shown because too many files have changed in this diff Show More