better support for warnings_only

This commit is contained in:
Emmanuel Garette 2020-08-04 16:49:21 +02:00
parent dc8010f0af
commit 659243ba8f
4 changed files with 31 additions and 30 deletions

View File

@ -156,7 +156,9 @@ class Calculation:
option_bag: OptionBag, option_bag: OptionBag,
leadership_must_have_index: bool=False, leadership_must_have_index: bool=False,
orig_value: Any=undefined, orig_value: Any=undefined,
allow_raises=False) -> Any: allow_value_error=False,
force_value_warning=False,
) -> Any:
return await carry_out_calculation(option_bag.option, return await carry_out_calculation(option_bag.option,
callback=self.function, callback=self.function,
callback_params=self.params, callback_params=self.params,
@ -164,7 +166,9 @@ class Calculation:
config_bag=option_bag.config_bag, config_bag=option_bag.config_bag,
leadership_must_have_index=leadership_must_have_index, leadership_must_have_index=leadership_must_have_index,
orig_value=orig_value, orig_value=orig_value,
allow_raises=allow_raises) allow_value_error=allow_value_error,
force_value_warning=force_value_warning,
)
async def help(self, async def help(self,
option_bag: OptionBag, option_bag: OptionBag,
@ -361,18 +365,18 @@ async def carry_out_calculation(option,
config_bag: Optional[ConfigBag], config_bag: Optional[ConfigBag],
orig_value=undefined, orig_value=undefined,
leadership_must_have_index: bool=False, leadership_must_have_index: bool=False,
allow_raises: int=False): allow_value_error: bool=False,
force_value_warning: bool=False,
):
"""a function that carries out a calculation for an option's value """a function that carries out a calculation for an option's value
:param option: the option :param option: the option
:param callback: the name of the callback function :param callback: the name of the callback function
:type callback: str
:param callback_params: the callback's parameters :param callback_params: the callback's parameters
(only keyword parameters are allowed) (only keyword parameters are allowed)
:type callback_params: dict
:param index: if an option is multi, only calculates the nth value :param index: if an option is multi, only calculates the nth value
:type index: int :param allow_value_error: to know if carry_out_calculation can return ValueError or ValueWarning (for example if it's a validation)
:param allow_raises: to know if carry_out_calculation is used to validate a value :param force_value_warning: transform valueError to ValueWarning object
The callback_params is a dict. Key is used to build args (if key is '') The callback_params is a dict. Key is used to build args (if key is '')
and kwargs (otherwise). Values are tuple of: and kwargs (otherwise). Values are tuple of:
@ -411,7 +415,8 @@ async def carry_out_calculation(option,
continue continue
ret = calculate(option, ret = calculate(option,
callback, callback,
allow_raises, allow_value_error,
force_value_warning,
args, args,
kwargs) kwargs)
if isinstance(ret, list) and not option.impl_is_dynoptiondescription() and \ if isinstance(ret, list) and not option.impl_is_dynoptiondescription() and \
@ -436,9 +441,11 @@ async def carry_out_calculation(option,
def calculate(option, def calculate(option,
callback: Callable, callback: Callable,
allow_raises: bool, allow_value_error: bool,
force_value_warning: bool,
args, args,
kwargs): kwargs,
):
"""wrapper that launches the 'callback' """wrapper that launches the 'callback'
:param callback: callback function :param callback: callback function
@ -448,12 +455,12 @@ def calculate(option,
""" """
try: try:
return callback(*args, **kwargs) return callback(*args, **kwargs)
except ValueError as err: except (ValueError, ValueWarning) as err:
if allow_raises: if allow_value_error:
if force_value_warning:
raise ValueWarning(str(err))
raise err raise err
error = err error = err
except ValueWarning as err:
raise err
except Exception as err: except Exception as err:
# import traceback # import traceback
# traceback.print_exc() # traceback.print_exc()

View File

@ -106,7 +106,7 @@ class Base:
context_od) -> Set[str]: context_od) -> Set[str]:
ret = set(getattr(self, '_dependencies', STATIC_TUPLE)) ret = set(getattr(self, '_dependencies', STATIC_TUPLE))
if context_od and hasattr(context_od, '_dependencies'): if context_od and hasattr(context_od, '_dependencies'):
# if context is set in options, add those options # add options that have context is set in calculation
return set(context_od._dependencies) | ret return set(context_od._dependencies) | ret
return ret return ret

View File

@ -84,7 +84,9 @@ class Option(BaseOption):
is_multi = True is_multi = True
_multi = submulti _multi = submulti
else: else:
raise ValueError(_('invalid multi type "{}"').format(multi)) raise ValueError(_('invalid multi type "{}" for "{}"').format(multi,
name,
))
if _multi != 1: if _multi != 1:
_setattr(self, '_multi', _multi) _setattr(self, '_multi', _multi)
if multi is not False and default is None: if multi is not False and default is None:
@ -335,7 +337,9 @@ class Option(BaseOption):
if ((check_error and not calc_is_warnings_only) or if ((check_error and not calc_is_warnings_only) or
(not check_error and calc_is_warnings_only)): (not check_error and calc_is_warnings_only)):
try: try:
kwargs = {'allow_raises': True} kwargs = {'allow_value_error': True,
'force_value_warning': calc_is_warnings_only,
}
if _index is not None and option_bag.index == _index: if _index is not None and option_bag.index == _index:
soption_bag = option_bag soption_bag = option_bag
else: else:
@ -346,17 +350,6 @@ class Option(BaseOption):
await validator.execute(soption_bag, await validator.execute(soption_bag,
leadership_must_have_index=True, leadership_must_have_index=True,
**kwargs) **kwargs)
except ValueError as err:
if calc_is_warnings_only:
warnings.warn_explicit(ValueWarning(val,
self._display_name,
self,
'{0}'.format(err),
_index),
ValueWarning,
self.__class__.__name__, 306)
else:
raise err
except ValueWarning as warn: except ValueWarning as warn:
warnings.warn_explicit(ValueWarning(val, warnings.warn_explicit(ValueWarning(val,
self._display_name, self._display_name,
@ -364,7 +357,7 @@ class Option(BaseOption):
'{0}'.format(warn), '{0}'.format(warn),
_index), _index),
ValueWarning, ValueWarning,
self.__class__.__name__, 316) self.__class__.__name__, 356)
async def do_validation(_value, async def do_validation(_value,
_index): _index):

View File

@ -241,7 +241,8 @@ class Values:
await option_bag.config_bag.context.cfgimpl_reset_cache(option_bag) await option_bag.config_bag.context.cfgimpl_reset_cache(option_bag)
async def calculate_value(self, async def calculate_value(self,
option_bag: OptionBag) -> Any: option_bag: OptionBag,
) -> Any:
# if value has callback, calculate value # if value has callback, calculate value
callback, callback_params = option_bag.option.impl_get_callback() callback, callback_params = option_bag.option.impl_get_callback()