def test_filename_relative_to_sibling_with_recursion(self): config = _root({'foo': '/', 'bar': 'r', 'baz': 'z'}) with self.assertRaises(confuse.ConfigTemplateError): config.get({ 'foo': confuse.Filename(relative_to='bar'), 'bar': confuse.Filename(relative_to='baz'), 'baz': confuse.Filename(relative_to='foo') })
def test_filename_relative_to_sibling(self): config = _root({'foo': '/', 'bar': 'baz'}) valid = config.get({ 'foo': confuse.Filename(), 'bar': confuse.Filename(relative_to='foo') }) self.assertEqual(valid.foo, os.path.realpath('/')) self.assertEqual(valid.bar, os.path.realpath('/baz'))
def test_filename_with_file_source(self): source = confuse.ConfigSource({'foo': 'foo/bar'}, filename='/baz/config.yaml') config = _root(source) config.config_dir = lambda: '/config/path' valid = config['foo'].get(confuse.Filename()) self.assertEqual(valid, os.path.realpath('/config/path/foo/bar'))
def test_filename_in_app_dir_overrides_config_source_dir(self): source = confuse.ConfigSource({'foo': 'foo/bar'}, filename='/baz/config.yaml', base_for_paths=True) config = _root(source) config.config_dir = lambda: '/config/path' valid = config['foo'].get(confuse.Filename(in_app_dir=True)) self.assertEqual(valid, os.path.realpath('/config/path/foo/bar'))
def __init__(self): super(SpotifyPlugin, self).__init__() self.config.add({ 'mode': 'list', 'tiebreak': 'popularity', 'show_failures': False, 'artist_field': 'albumartist', 'album_field': 'album', 'track_field': 'title', 'region_filter': None, 'regex': [], 'client_id': '4e414367a1d14c75a5c5129a627fcab8', 'client_secret': 'f82bdc09b2254f1a8286815d02fd46dc', 'tokenfile': 'spotify_token.json', }) self.config['client_secret'].redact = True self.tokenfile = self.config['tokenfile'].get( confuse.Filename(in_app_dir=True) ) # Path to the JSON file for storing the OAuth access token. self.setup()
import argparse import logging import os import shutil import urllib.parse import confuse import git APP_NAME = 'forksync' CONFIG_TEMPLATE = { 'ssh_key': confuse.Filename(), 'cache_dir': confuse.Filename(default='/cache'), 'log_level': confuse.String(default='INFO'), 'repositories': confuse.Sequence({ 'origin': confuse.String(), 'upstream': confuse.String() }) } logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(APP_NAME) def fix_https_url(url): scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
def test_filename_wrong_type(self): config = _root({'foo': 8}) with self.assertRaises(confuse.ConfigTypeError): config['foo'].get(confuse.Filename())
def test_filename_relative_to_sibling_needs_template(self): config = _root({'foo': '/', 'bar': 'baz'}) with self.assertRaises(confuse.ConfigTemplateError): config.get({'bar': confuse.Filename(relative_to='foo')})
def test_filename_with_non_file_source(self): config = _root({'foo': 'foo/bar'}) valid = config['foo'].get(confuse.Filename()) self.assertEqual(valid, os.path.join(os.getcwd(), 'foo', 'bar'))
def test_filename_relative_to_self(self): config = _root({'foo': 'bar'}) with self.assertRaises(confuse.ConfigTemplateError): config.get({'foo': confuse.Filename(relative_to='foo')})
def test_filename_relative_to_sibling_needs_siblings(self): config = _root({'foo': 'bar'}) with self.assertRaises(confuse.ConfigTemplateError): config['foo'].get(confuse.Filename(relative_to='bar'))
From upstream master, commit by Szabolcs on Github. https://github.com/beetbox/confuse/commit/6c97e03d125cbbae5ce08040b1207d33ae3ef01c """ def value(self, view, template=None): return pathlib.Path(super(Path, self).value(view, template)) ABB_RCF_CONF_TEMPLATE = { # Two following is set by command line arguments "debug": confuse.TypeTemplate(bool, default=False), "verbose": confuse.TypeTemplate(bool, default=False), # is_target_real is set either by command line argument, during run or in conf file "target": confuse.TypeTemplate(str, default=None), "paths": { "json_dir": confuse.Filename(default=str(DEFAULT_JSON_DIR)), "conf_dir": confuse.Filename(default=str(DEFAULT_JSON_DIR)), "log_dir": confuse.Filename(default=str(DEFAULT_LOG_DIR)), }, "wobjs": { "picking_wobj_name": str, "placing_wobj_name": str }, "tool": { "tool_name": str, "io_needles_pin": str, "grip_state": int, "release_state": int, "wait_before_io": confuse.Number(default=2), "wait_after_io": confuse.Number(default=0.5), },
"""Convert zonedata from :obj:`str` to number if needed.""" if isinstance(value, (int, float)): if not -1 >= value >= 2000: # arbitrary max value self.fail("ZoneData needs to be from -1 to 2000", view) return value if value.upper() not in self.ZONE_DICT.keys(): self.fail( "ZoneData must match one of {0}".format(", ".join( self.ZONE_DICT.keys())), view, ) return self.ZONE_DICT[value.upper()] ABB_RCF_CONF_TEMPLATE = { "log_dir": confuse.Filename(), "pick_conf": confuse.Path(), "run_data_path": confuse.Template(), # Already type checked by argparse "publish_tf_xform": bool, "edit_sequence": confuse.TypeTemplate(bool, default=False), "robot_client": { "controller": str, "docker": { "timeout_ping": float, "sleep_after_up": float }, "wobjs": { "pick": str, "place": str }, "tools": {
def test_filename_relative_to_working_dir(self): config = _root({'foo': 'bar'}) valid = config['foo'].get(confuse.Filename(cwd='/dev/null')) self.assertEqual(valid, os.path.realpath('/dev/null/bar'))
def _tokenfile(self): """Get the path to the JSON file for storing the OAuth token. """ return self.config['tokenfile'].get(confuse.Filename(in_app_dir=True))
def test_missing_required_value(self): config = _root({}) with self.assertRaises(confuse.NotFoundError): config['foo'].get(confuse.Filename())
def test_default_none(self): config = _root({}) valid = config['foo'].get(confuse.Filename(None)) self.assertEqual(valid, None)
def test_default_value(self): config = _root({}) valid = config['foo'].get(confuse.Filename('foo/bar')) self.assertEqual(valid, 'foo/bar')
"""Convert zonedata from :obj:`str` to number if needed.""" if isinstance(value, (int, float)): if not -1 >= value >= 2000: # arbitrary max value self.fail("ZoneData needs to be from -1 to 2000", view) return value if value.upper() not in self.ZONE_DICT.keys(): self.fail( "ZoneData must match one of {0}".format(", ".join( self.ZONE_DICT.keys())), view, ) return self.ZONE_DICT[value.upper()] ABB_RCF_CONF_TEMPLATE = { "logfile": confuse.Filename(), "run_data_path": confuse.Template(), # Already type checked by argparse "robot_client": { "controller": str, "docker": { "timeout_ping": float, "sleep_after_up": float }, "wobjs": { "pick": str, "place": str }, "tools": { "pick_place": { "name": str, "io_pin_needles": str,
default value if not specified Returns ------- template: type optional type template """ template = confuse.as_template(optional_type) template.default = default return template template = { "version": optional(confuse.OneOf([str, int]), __version__), "host": str, "port": optional(int), "path": optional(confuse.Filename()), "mongo": { "url": str, "name": str, "username": optional(str), "password": optional(str), }, "interface": { "port": confuse.OneOf([confuse.String(pattern="COM\\d+$"), confuse.Filename()]), "baudrate": int, "encoding": optional(str, "utf-8"), },
def test_filename_working_dir_overrides_sibling(self): config = _root({'foo': 'bar'}) valid = config.get( {'foo': confuse.Filename(cwd='/dev/null', relative_to='baz')}) self.assertEqual(valid.foo, os.path.realpath('/dev/null/bar'))
def test_filename_in_app_dir_non_file_source(self): source = confuse.ConfigSource({'foo': 'foo/bar'}) config = _root(source) config.config_dir = lambda: '/config/path' valid = config['foo'].get(confuse.Filename(in_app_dir=True)) self.assertEqual(valid, os.path.realpath('/config/path/foo/bar'))
"""An example application using Confuse for configuration.""" from __future__ import division, absolute_import, print_function import confuse import argparse template = { 'library': confuse.Filename(), 'import_write': confuse.OneOf([bool, 'ask', 'skip']), 'ignore': confuse.StrSeq(), 'plugins': list, 'paths': { 'directory': confuse.Filename(), 'default': confuse.Filename(relative_to='directory'), }, 'servers': confuse.Sequence({ 'hostname': str, 'options': confuse.StrSeq(), }) } config = confuse.LazyConfig('ConfuseExample', __name__) def main(): parser = argparse.ArgumentParser(description='example Confuse program') parser.add_argument('--library', '-l', dest='library', metavar='LIBPATH', help='library database file') parser.add_argument('--directory',
From upstream master, commit by Szabolcs on Github. https://github.com/beetbox/confuse/commit/6c97e03d125cbbae5ce08040b1207d33ae3ef01c """ def value(self, view, template=None): return pathlib.Path(super(Path, self).value(view, template)) ABB_RCF_CONF_TEMPLATE = { # Two following is set by command line arguments "debug": confuse.TypeTemplate(bool, default=False), "verbose": confuse.TypeTemplate(bool, default=False), # is_target_real is set either by command line argument, during run or in conf file "target": confuse.TypeTemplate(str, default=None), "paths": { "json_dir": confuse.Filename(default=str(DEFAULT_JSON_DIR)), "conf_dir": confuse.Filename(default=str(DEFAULT_CONF_DIR)), "log_dir": confuse.Filename(default=str(DEFAULT_LOG_DIR)), "pick_conf_dir": confuse.Filename(default=str(DEFAULT_PICK_CONF_DIR)), }, "wobjs": { "picking_wobj_name": str, "placing_wobj_name": str }, "tool": { "tool_name": str, "io_needles_pin": str, "grip_state": int, "release_state": int, "wait_before_io": confuse.Number(default=2), "wait_after_io": confuse.Number(default=0.5),