You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.6 KiB

4 years ago
  1. from voluptuous import Invalid, MultipleInvalid
  2. from voluptuous.error import Error
  3. MAX_VALIDATION_ERROR_ITEM_LENGTH = 500
  4. def _nested_getitem(data, path):
  5. for item_index in path:
  6. try:
  7. data = data[item_index]
  8. except (KeyError, IndexError, TypeError):
  9. # The index is not present in the dictionary, list or other
  10. # indexable or data is not subscriptable
  11. return None
  12. return data
  13. def humanize_error(data, validation_error, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH):
  14. """ Provide a more helpful + complete validation error message than that provided automatically
  15. Invalid and MultipleInvalid do not include the offending value in error messages,
  16. and MultipleInvalid.__str__ only provides the first error.
  17. """
  18. if isinstance(validation_error, MultipleInvalid):
  19. return '\n'.join(sorted(
  20. humanize_error(data, sub_error, max_sub_error_length)
  21. for sub_error in validation_error.errors
  22. ))
  23. else:
  24. offending_item_summary = repr(_nested_getitem(data, validation_error.path))
  25. if len(offending_item_summary) > max_sub_error_length:
  26. offending_item_summary = offending_item_summary[:max_sub_error_length - 3] + '...'
  27. return '%s. Got %s' % (validation_error, offending_item_summary)
  28. def validate_with_humanized_errors(data, schema, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH):
  29. try:
  30. return schema(data)
  31. except (Invalid, MultipleInvalid) as e:
  32. raise Error(humanize_error(data, e, max_sub_error_length))