Ejemplo n.º 1
0
def check_json_matches_schema(jsondata,
                              schema_filename: str,
                              base_path: str = "",
                              base_uri: str = ""):
    """
    Check the given json data against the jsonschema in the given schema file,
    raising an exception on error.  The exception text includes one or more
    validation error messages.

    schema_filename is relative to the schema root directory.

    may raise SchemaError or ValidationError
    """
    set_schema_base_path(base_path=base_path, base_uri=base_uri)

    try:
        validator = Validator(_load_json_schema(schema_filename))
    except SchemaError as e:
        raise SchemaError('{} is invalid: {}'.format(schema_filename, e))

    err_msg_l = []
    for error in validator.iter_errors(jsondata):
        err_msg_l.append('{}: {}'.format(
            ' '.join([str(word) for word in error.path]), error.message))
    if err_msg_l:
        raise ValidationError(' + '.join(err_msg_l))
    else:
        return True
Ejemplo n.º 2
0
def validate_data(data: Dict[str, Any],
                  validator: Draft7Validator) -> ValidationResult:
    error_messages = []
    for error in validator.iter_errors(data):
        if error.path:
            # Elements of the error path may be integers or other non-string types,
            # but we need strings for use with join()
            error_path_for_message = ".".join([str(x) for x in error.path])
            error_message = f"'{error_path_for_message}' invalid due to {error.message}"
        else:
            error_message = error.message
        error_messages.append(error_message)

    error_msg = "; ".join(error_messages) if error_messages else None
    result = ValidationResult(errors=error_messages, error_msg=error_msg)
    return result