def test_validate_no_choice_in_list(self): config = _root({'foo': None}) with self.assertRaises(confuse.ConfigValueError): config['foo'].get( confuse.OneOf([ confuse.String(), confuse.Integer(), ]))
def test_validate_bad_template(self): class BadTemplate(object): pass config = _root({}) with self.assertRaises(confuse.ConfigTemplateError): config.get(confuse.OneOf([BadTemplate()])) del BadTemplate
def test_validate_good_choice_in_list(self): config = _root({'foo': 2}) valid = config['foo'].get( confuse.OneOf([ confuse.String(), confuse.Integer(), ])) self.assertEqual(valid, 2)
def test_validate_first_good_choice_in_list(self): config = _root({'foo': 3.14}) valid = config['foo'].get( confuse.OneOf([ confuse.Integer(), confuse.Number(), ])) self.assertEqual(valid, 3)
def __init__(self): super(FetchArtPlugin, self).__init__() # Holds candidates corresponding to downloaded images between # fetching them and placing them in the filesystem. self.art_candidates = {} self.config.add({ 'auto': True, 'minwidth': 0, 'maxwidth': 0, 'enforce_ratio': False, 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], 'sources': ['filesystem', 'coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', 'fanarttv_key': None, 'store_source': False, }) self.config['google_key'].redact = True self.config['fanarttv_key'].redact = True self.minwidth = self.config['minwidth'].get(int) self.maxwidth = self.config['maxwidth'].get(int) # allow both pixel and percentage-based margin specifications self.enforce_ratio = self.config['enforce_ratio'].get( confuse.OneOf([ bool, confuse.String(pattern=self.PAT_PX), confuse.String(pattern=self.PAT_PERCENT) ])) self.margin_px = None self.margin_percent = None if type(self.enforce_ratio) is six.text_type: if self.enforce_ratio[-1] == u'%': self.margin_percent = float(self.enforce_ratio[:-1]) / 100 elif self.enforce_ratio[-2:] == u'px': self.margin_px = int(self.enforce_ratio[:-2]) else: # shouldn't happen raise confuse.ConfigValueError() self.enforce_ratio = True cover_names = self.config['cover_names'].as_str_seq() self.cover_names = list(map(util.bytestring_path, cover_names)) self.cautious = self.config['cautious'].get(bool) self.store_source = self.config['store_source'].get(bool) self.src_removed = (config['import']['delete'].get(bool) or config['import']['move'].get(bool)) if self.config['auto']: # Enable two import hooks when fetching is enabled. self.import_stages = [self.fetch_art] self.register_listener('import_task_files', self.assign_art) available_sources = list(SOURCES_ALL) if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') available_sources = [(s, c) for s in available_sources for c in ART_SOURCES[s].VALID_MATCHING_CRITERIA] sources = plugins.sanitize_pairs( self.config['sources'].as_pairs(default_value='*'), available_sources) if 'remote_priority' in self.config: self._log.warning( u'The `fetch_art.remote_priority` configuration option has ' u'been deprecated. Instead, place `filesystem` at the end of ' u'your `sources` list.') if self.config['remote_priority'].get(bool): fs = [] others = [] for s, c in sources: if s == 'filesystem': fs.append((s, c)) else: others.append((s, c)) sources = others + fs self.sources = [ ART_SOURCES[s](self._log, self.config, match_by=[c]) for s, c in sources ]
"""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',
import natsort class CrossCheckError(Exception): pass template = { # The name of this configuration (for logging purposes) 'name': str, # The mode in which to run # 'train': Create a new model # 'replay': Run an existing model # 'compete': Run two models against each other # 'play': Run a model against a human player (controller input) # 'play-2p': Play traditional human vs human 'mode': confuse.OneOf(['train', 'replay', 'compete', 'play', 'play-2p']), 'input': { 'feature-vector': str, 'controller-discretizer': str, # The 1+ scenarios that are run in parallel 'scenarios': confuse.Sequence({ # The name of a scenario 'name': str, # The filename of a scenario (save state) from which to start play 'save-state': str, # How play in this scenario will be judged 'scorekeeper': str, }), # The cost function to use when combining scenarios 'metascorekeeper': str, # Custom configs that are applied directly to the neat.ini files
def test_default_value(self): config = _root({}) valid = config['foo'].get(confuse.OneOf([], default='bar')) self.assertEqual(valid, 'bar')
# gameplay_tracker.py #from mongoengine import * import mongoengine import confuse import argparse import logging from datetime import datetime # TODO create docstrings VERSION = '0.1' template = { 'appName': str, 'logLevel': confuse.OneOf([ 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' ]), #str, #set this to be a confuse list (list must be valid log level) 'databases': { 'mongodb': { 'host': str, 'port': int, 'username': str, 'password': str, 'authentication_source': str, } } } config = confuse.Configuration('GameplayTracker', __name__).get(template) class User(mongoengine.Document):
import confuse import pathlib from typing import Optional from crosscheck.player.rendering import SimpleImageViewer template = { # The name of this configuration (for logging purposes) 'name': str, # The mode in which to run # 'train': Create a new model # 'replay': Run an existing model # 'compete': Run two models against each other # 'play': Run a model against a human player (controller input) # 'play-2p': Play traditional human vs human 'mode': confuse.OneOf(['train', 'replay', 'compete', 'play', 'play-2p']), # The 1+ scenarios that are run in serial 'scenarios': confuse.Sequence({ # The filename of a scenario (save state) from which to start play 'save-state': [str, None], }), } def main(argv): parser = argparse.ArgumentParser(description='Cross-check: NHL \'94 practice scenarios') parser.add_argument('config', help='App config.') args = parser.parse_args(argv) # Parse the config using confuse, bailing on failure
optional_type : type type of the optional value default : optional 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,
}, "safe_joint_positions": { "start": confuse.Sequence([float] * 6), "end": confuse.Sequence([float] * 6), }, "movement": { "offset_distance": float, "speed_placing": float, "speed_picking": float, "speed_travel": float, "zone_travel": ZoneDataTemplate(), "zone_pick": ZoneDataTemplate(), "zone_place": ZoneDataTemplate(), }, "pick": { "setup": confuse.OneOf(["rcs", "wobj", None], default=None), "wobj_pickingconf": { "origin_grid": { "x": confuse.Number(default=0.0), "y": confuse.Number(default=0.0), }, "xnum": confuse.Number(default=2), "ynum": confuse.Number(default=5), "grid_spacing": confuse.Number(default=125.0), "compression_height_factor": confuse.Number(default=0.95), "xaxis": confuse.Sequence([float] * 3), "yaxis": confuse.Sequence([float] * 3), }, }, "docker": { "timeout_ping": confuse.Number(default=10),