Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def check_error(self, message, func, *args, **kwargs):
"""Like assertRaises but checks for the message string too."""
klass = kwargs.pop('klass', errors.ConfigurationError)
try:
func(*args, **kwargs)
except klass as e:
self.assertEqual(
message, _str_exc(e),
f'\nGot:\n{_str_exc(e)!r}\nExpected:\n{message!r}\n')
else:
self.fail('no exception raised')
def collapse_named_section(self, section):
try:
return {'target': target_config}[section]
except KeyError:
raise errors.ConfigurationError(section)
self.assertEqual(
def _render_config_stack(self, type_obj, config_stack):
conf = {}
for key in config_stack:
typename = type_obj.types.get(key)
if typename is None:
if not type_obj.allow_unknowns:
raise errors.ConfigurationError(f'Type of {key!r} unknown')
typename = 'str'
is_ref = typename.startswith('ref:')
is_refs = typename.startswith('refs:')
if typename.startswith('lazy_'):
typename = typename[5:]
if typename.startswith('refs:') or typename in ('list', 'str'):
result = config_stack.render_prepends(self, key, typename, flatten=(typename != 'str'))
if typename == 'str':
result = ' '.join(result)
else:
result = config_stack.render_val(self, key, typename)
if is_ref:
if self._section_is_inherit_only(sections[0]):
if sections[0].render_value(self, 'inherit-only', 'bool'):
raise errors.CollapseInheritOnly(
'cannot collapse inherit-only section')
relevant_sections = self._get_inherited_sections(_name, sections)
config_stack = _ConfigStack()
for data in relevant_sections:
for key in data.section.keys():
config_stack[key].append(data)
kls = config_stack.render_val(self, 'class', 'callable')
if kls is None:
raise errors.ConfigurationError('no class specified')
type_obj = basics.ConfigType(kls)
is_default = bool(config_stack.render_val(self, 'default', 'bool'))
for key in ('inherit', 'inherit-only', 'class', 'default'):
config_stack.pop(key, None)
collapsed = CollapsedConfig(type_obj, self._render_config_stack(type_obj, config_stack),
self, default=is_default, debug=self.debug)
return collapsed
inherit_names = set([name])
for current_section, section_stack in slist:
current_conf = section_stack[0]
if 'inherit' not in current_conf:
continue
prepend, inherits, append = current_conf.render_value(
self, 'inherit', 'list')
if prepend is not None or append is not None:
raise errors.ConfigurationError(
'Prepending or appending to the inherit list makes no sense')
for inherit in inherits:
if inherit == current_section:
# self-inherit. Mkae use of section_stack to handle this.
if len(section_stack) == 1:
# nothing else to self inherit.
raise errors.ConfigurationError(
f'Self-inherit {inherit!r} cannot be found')
if isinstance(section_stack, deque):
slist.append((inherit, list(section_stack)[1:]))
else:
slist.append((inherit, section_stack[1:]))
else:
if inherit in inherit_names:
raise errors.ConfigurationError(
f'Inherit {inherit!r} is recursive')
inherit_names.add(inherit)
target = self.sections_lookup.get(inherit)
if target is None:
raise errors.ConfigurationError(
f'Inherit target {inherit!r} cannot be found')
slist.append((inherit, target))
return [_section_data(name, stack[0]) for (name, stack) in slist]
"""
try:
defaults = self.types.get(type_name, {}).items()
except IGNORED_EXCEPTIONS:
raise
except Exception as e:
raise errors.ConfigurationError(
f'Collapsing defaults for {type_name!r}') from e
defaults = [(name, section) for name, section in defaults if section.default]
if not defaults:
return None
if len(defaults) > 1:
defaults = ', '.join(map(repr, sorted(x[0] for x in defaults)))
raise errors.ConfigurationError(
f'type {type_name} incorrectly has multiple default sections: {defaults}')
try:
return defaults[0][1].instantiate()
except IGNORED_EXCEPTIONS:
raise
except Exception as e:
raise errors.ConfigurationError(
f'failed instantiating default {type_name} {defaults[0][0]!r}') from e
return None
def collapse_named_section(self, name, raise_on_missing=True):
"""Collapse a config by name, possibly returning a cached instance.
@returns: :obj:`CollapsedConfig`.
If there is no section with this name a ConfigurationError is raised,
unless raise_on_missing is False in which case None is returned.
"""
if name in self._refs:
raise errors.ConfigurationError(f'Reference to {name!r} is recursive')
self._refs.add(name)
try:
result = self.rendered_sections.get(name)
if result is not None:
return result
section_stack = self.sections_lookup.get(name)
if section_stack is None:
if not raise_on_missing:
return None
raise errors.ConfigurationError(f'no section called {name!r}')
try:
result = self.collapse_section(section_stack, name)
result.name = name
except IGNORED_EXCEPTIONS:
raise
except Exception as e:
for v in value:
if not isinstance(v, str):
v = ConfigSection(v)
result.append(v)
return 'refs', result
else:
if len(value) != 1:
raise errors.ConfigurationError('only one argument required')
if not isinstance(value[0], str):
raise errors.ConfigurationError(f'{value!r} should be a string')
if arg_type == 'str':
return [None, basics.str_to_str(value[0]), None]
elif arg_type == 'bool':
return basics.str_to_bool(value[0])
else:
raise errors.ConfigurationError(f'unsupported type {arg_type!r}')
return l
elif arg_type == 'repr':
if callable(value):
return 'callable', value
if isinstance(value, ConfigSection):
return 'ref', value
if isinstance(value, str):
return 'str', value
if isinstance(value, bool):
return 'bool', value
if isinstance(value, (list, tuple)):
if not value or isinstance(value[0], str):
return 'list', value
if isinstance(value[0], ConfigSection):
return 'refs', value
raise errors.ConfigurationError(f'unsupported type for {value!r}')
elif not isinstance(value, {'list': (list, tuple),
'str': str,
'bool': bool}[arg_type]):
raise errors.ConfigurationError(
f'{value!r} does not have type {arg_type!r}')
return value