Created
January 14, 2015 15:27
-
-
Save robdennis/bf13312a078fe8557101 to your computer and use it in GitHub Desktop.
example of config object validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from configobj import ConfigObj, flatten_errors | |
from validate import Validator | |
DEFAULTS = {"CATEGORIES": ['bas', 'bap']} | |
allowed_category_options = "option({0})".format( | |
', '.join([repr(cat) for cat in DEFAULTS['CATEGORIES']]) | |
) | |
CONFIGSPEC = '''\ | |
logfile = string | |
[foo] | |
user = string | |
pass = string | |
[__many__] | |
category = {0} | |
'''.format(allowed_category_options).splitlines() | |
UNFORMATTED_CONFIGSPEC = '''\ | |
logfile = string | |
[foo] | |
user = string | |
pass = string | |
[__many__] | |
category = allowed_category_options | |
'''.splitlines() | |
BAD_CFG_CONTENT = """\ | |
logfile = foo | |
[foo] | |
user = bar | |
pass = baz | |
[bar] | |
category = unknown | |
""".splitlines() | |
GOOD_CFG_CONTENT = """\ | |
logfile = foo | |
[foo] | |
user = bar | |
pass = baz | |
[bar] | |
category = bas | |
""".splitlines() | |
for name, spec in [('formatted', CONFIGSPEC), | |
('unformatted', UNFORMATTED_CONFIGSPEC)]: | |
bad_config_file = ConfigObj(BAD_CFG_CONTENT, configspec=spec) | |
good_config_file = ConfigObj(GOOD_CFG_CONTENT, configspec=spec) | |
validator = Validator() | |
bad_results = bad_config_file.validate(validator, preserve_errors=True) | |
print('expected to fail: {0}: {1!r}'.format(name, flatten_errors(bad_config_file, bad_results))) | |
good_results = good_config_file.validate(validator, preserve_errors=True) | |
print('expected to pass: {0}: {1!r}'.format(name, flatten_errors(good_config_file, good_results))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment