Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_config_parameters(self):
w = wilson.Wilson({'qd1_1123': 1}, 1000, 'SMEFT', 'Warsaw')
with self.assertRaises(vol.MultipleInvalid):
# value must be dict
w.set_option('parameters', 4)
with self.assertRaises(vol.MultipleInvalid):
# dict value must be number
w.set_option('parameters', {'bla': 'blo'})
# int should be OK but corced to float
w.set_option('parameters', {'bla': 1})
self.assertTrue(type(w.get_option('parameters')['bla']), float)
self.assertEqual(w.get_option('parameters'), {'bla': 1.})
w.set_option('parameters', {'m_b': 4.0})
self.assertEqual(w.get_option('parameters'), {'m_b': 4.0})
self.assertEqual(w.parameters['m_b'], 4.0)
def test_schema_bad_schema(self):
"""Test bad customize schemas."""
for value in (
{'test.test': 10},
{'test.test': ['hello']},
{'entity_id': {'a': 'b'}},
{'entity_id': 10},
[{'test.test': 'value'}],
):
with pytest.raises(
MultipleInvalid,
message="{} should have raised MultipleInvalid".format(
value)):
customize.CUSTOMIZE_SCHEMA(value)
"port": "aaa",
"name": "Name",
"zones": {11: {}},
"sources": {1: {"name": "b"}},
},
# Source missing name
{
"platform": "monoprice",
"port": "aaa",
"name": "Name",
"zones": {11: {"name": "a"}},
"sources": {1: {}},
},
)
for value in schemas:
with pytest.raises(vol.MultipleInvalid):
PLATFORM_SCHEMA(value)
def __init__(self, error):
if isinstance(error, voluptuous.MultipleInvalid):
message = "\n".join(map(str, error.errors))
else:
message = str(error)
super().__init__(self, message)
def validate_with_humanized_errors(data, schema, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH):
try:
return schema(data)
except (Invalid, MultipleInvalid) as e:
raise Error(humanize_error(data, e, max_sub_error_length))
def normalize_config(config_path):
if not os.path.isfile(config_path):
raise ValidationError('no configuration file found')
with open(config_path, 'r') as f:
try:
config = yaml.load(f)
except Exception:
raise ValidationError('invalid yaml file')
schema = _config_schema()
try:
config = schema(config)
except MultipleInvalid:
raise ValidationError('configuration file invalid')
config['name'] = config['name'].lower()
# no space in project name
if ' ' in config['name']:
raise ValidationError('space in project name is invalid')
# validate routes
routes = config.get('routes')
if routes:
for route in routes:
if ' ' in route or route == '':
raise ValidationError('invalid route: {}'.format(route))
routes = [route.lower() for route in routes]
routes = list(set(routes))
config['routes'] = routes
# validate models
models = config.get('models')
def validate(d, fname=None):
from dvc.utils.compat import convert_to_unicode
try:
Stage.COMPILED_SCHEMA(convert_to_unicode(d))
except MultipleInvalid as exc:
raise StageFileFormatError(fname, exc)
def _format_voluptuous_error(data, validation_error,
max_sub_error_length=500):
errors = []
if isinstance(validation_error, MultipleInvalid):
errors.extend(sorted(
sub_error.path[0] for sub_error in validation_error.errors))
else:
errors.append(validation_error.path[0])
errors = ['`{}`'.format(e) for e in errors]
if len(errors) == 1:
adj = ''
vars = errors[0]
verb = 'is'
elif len(errors) == 2:
adj = 'Both of '
vars = ' and '.join(errors)
verb = 'are'
else:
adj = 'All of '
def voluptuous_errors(error):
# FIXME(sileht): remove error at payload root
payload = voluptuous_error(error)
payload["errors"] = []
if isinstance(error, voluptuous.MultipleInvalid):
payload["errors"].extend(map(voluptuous_error, error.errors))
else:
payload["errors"].extend(voluptuous_error(error))
return flask.make_response(flask.jsonify(payload), 400)
def expect_one_of(dct, *args):
"""Return the first attribute found in dct, else Raise MultipleInvalid if at
least one required attribute is not present in dct.
"""
for arg in args:
if dct.get(arg) is not None:
return arg
error_string = '{}'.format(args[0])
for arg in args[1:]:
error_string += ' or {}'.format(arg)
error_string += ' is required'
error = Invalid(error_string)
raise MultipleInvalid(errors=[error])