Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 710598752f | |||
| 5fbf64bac5 |
718
src/lib.rs
718
src/lib.rs
@ -2,9 +2,10 @@ use pgrx::*;
|
|||||||
|
|
||||||
pg_module_magic!();
|
pg_module_magic!();
|
||||||
|
|
||||||
use boon::{CompileError, Compiler, ErrorKind, SchemaIndex, Schemas, ValidationError};
|
use boon::{CompileError, Compiler, ErrorKind, SchemaIndex, Schemas, ValidationError, Type, Types};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value, Number};
|
||||||
|
use std::borrow::Cow;
|
||||||
use std::collections::hash_map::Entry;
|
use std::collections::hash_map::Entry;
|
||||||
use std::{collections::HashMap, sync::RwLock};
|
use std::{collections::HashMap, sync::RwLock};
|
||||||
|
|
||||||
@ -19,7 +20,7 @@ struct Error {
|
|||||||
path: String,
|
path: String,
|
||||||
code: String,
|
code: String,
|
||||||
message: String,
|
message: String,
|
||||||
cause: String,
|
cause: Value, // Changed from String to Value to store JSON
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
@ -185,101 +186,53 @@ fn collect_errors(error: &ValidationError, errors_list: &mut Vec<Error>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if error.causes.is_empty() && !is_structural {
|
if error.causes.is_empty() && !is_structural {
|
||||||
// Handle errors with multiple fields specially
|
let base_path = error.instance_location.to_string();
|
||||||
match &error.kind {
|
|
||||||
ErrorKind::Required { want } => {
|
// Match on error kind and handle each type
|
||||||
// Create a separate error for each missing required field
|
let errors_to_add = match &error.kind {
|
||||||
let base_path = error.instance_location.to_string();
|
ErrorKind::Type { got, want } => handle_type_error(&base_path, got, want),
|
||||||
for missing_field in want {
|
ErrorKind::Required { want } => handle_required_error(&base_path, want),
|
||||||
let field_path = if base_path.is_empty() {
|
ErrorKind::Dependency { prop, missing } => handle_dependency_error(&base_path, prop, missing, false),
|
||||||
format!("/{}", missing_field)
|
ErrorKind::DependentRequired { prop, missing } => handle_dependency_error(&base_path, prop, missing, true),
|
||||||
} else {
|
ErrorKind::AdditionalProperties { got } => handle_additional_properties_error(&base_path, got),
|
||||||
format!("{}/{}", base_path, missing_field)
|
ErrorKind::Enum { want } => handle_enum_error(&base_path, want),
|
||||||
};
|
ErrorKind::Const { want } => handle_const_error(&base_path, want),
|
||||||
|
ErrorKind::MinLength { got, want } => handle_min_length_error(&base_path, *got, *want),
|
||||||
errors_list.push(Error {
|
ErrorKind::MaxLength { got, want } => handle_max_length_error(&base_path, *got, *want),
|
||||||
path: field_path,
|
ErrorKind::Pattern { got, want } => handle_pattern_error(&base_path, got, want),
|
||||||
code: "REQUIRED_FIELD_MISSING".to_string(),
|
ErrorKind::Minimum { got, want } => handle_minimum_error(&base_path, got, want),
|
||||||
message: format!("Required field '{}' is missing", missing_field),
|
ErrorKind::Maximum { got, want } => handle_maximum_error(&base_path, got, want),
|
||||||
cause: format!("property '{}' is required", missing_field),
|
ErrorKind::ExclusiveMinimum { got, want } => handle_exclusive_minimum_error(&base_path, got, want),
|
||||||
});
|
ErrorKind::ExclusiveMaximum { got, want } => handle_exclusive_maximum_error(&base_path, got, want),
|
||||||
}
|
ErrorKind::MultipleOf { got, want } => handle_multiple_of_error(&base_path, got, want),
|
||||||
}
|
ErrorKind::MinItems { got, want } => handle_min_items_error(&base_path, *got, *want),
|
||||||
ErrorKind::Dependency { prop, missing } | ErrorKind::DependentRequired { prop, missing } => {
|
ErrorKind::MaxItems { got, want } => handle_max_items_error(&base_path, *got, *want),
|
||||||
// Create a separate error for each missing field
|
ErrorKind::UniqueItems { got } => handle_unique_items_error(&base_path, got),
|
||||||
let base_path = error.instance_location.to_string();
|
ErrorKind::MinProperties { got, want } => handle_min_properties_error(&base_path, *got, *want),
|
||||||
for missing_field in missing {
|
ErrorKind::MaxProperties { got, want } => handle_max_properties_error(&base_path, *got, *want),
|
||||||
let field_path = if base_path.is_empty() {
|
ErrorKind::AdditionalItems { got } => handle_additional_items_error(&base_path, *got),
|
||||||
format!("/{}", missing_field)
|
ErrorKind::Format { want, got, err } => handle_format_error(&base_path, want, got, err),
|
||||||
} else {
|
ErrorKind::PropertyName { prop } => handle_property_name_error(&base_path, prop),
|
||||||
format!("{}/{}", base_path, missing_field)
|
ErrorKind::Contains => handle_contains_error(&base_path),
|
||||||
};
|
ErrorKind::MinContains { got, want } => handle_min_contains_error(&base_path, got, *want),
|
||||||
|
ErrorKind::MaxContains { got, want } => handle_max_contains_error(&base_path, got, *want),
|
||||||
let (error_code, human_message) = match &error.kind {
|
ErrorKind::ContentEncoding { want, err } => handle_content_encoding_error(&base_path, want, err),
|
||||||
ErrorKind::Dependency { .. } => (
|
ErrorKind::ContentMediaType { want, err, .. } => handle_content_media_type_error(&base_path, want, err),
|
||||||
"DEPENDENCY_FAILED".to_string(),
|
ErrorKind::FalseSchema => handle_false_schema_error(&base_path),
|
||||||
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
ErrorKind::Not => handle_not_error(&base_path),
|
||||||
),
|
ErrorKind::RefCycle { url, kw_loc1, kw_loc2 } => handle_ref_cycle_error(&base_path, url, kw_loc1, kw_loc2),
|
||||||
ErrorKind::DependentRequired { .. } => (
|
ErrorKind::Reference { kw, url } => handle_reference_error(&base_path, kw, url),
|
||||||
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
ErrorKind::Schema { url } => handle_schema_error(&base_path, url),
|
||||||
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
ErrorKind::ContentSchema => handle_content_schema_error(&base_path),
|
||||||
),
|
ErrorKind::Group => handle_group_error(&base_path),
|
||||||
_ => unreachable!(),
|
ErrorKind::AllOf => handle_all_of_error(&base_path),
|
||||||
};
|
ErrorKind::AnyOf => handle_any_of_error(&base_path),
|
||||||
|
ErrorKind::OneOf(matched) => handle_one_of_error(&base_path, matched),
|
||||||
errors_list.push(Error {
|
};
|
||||||
path: field_path,
|
|
||||||
code: error_code,
|
// Add all generated errors
|
||||||
message: human_message,
|
for error in errors_to_add {
|
||||||
cause: format!("property '{}' required, if '{}' property exists", missing_field, prop),
|
errors_list.push(error);
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ErrorKind::AdditionalProperties { got } => {
|
|
||||||
// Create a separate error for each additional property that's not allowed
|
|
||||||
let base_path = error.instance_location.to_string();
|
|
||||||
for extra_prop in got {
|
|
||||||
let field_path = if base_path.is_empty() {
|
|
||||||
format!("/{}", extra_prop)
|
|
||||||
} else {
|
|
||||||
format!("{}/{}", base_path, extra_prop)
|
|
||||||
};
|
|
||||||
|
|
||||||
errors_list.push(Error {
|
|
||||||
path: field_path,
|
|
||||||
code: "ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
|
||||||
message: format!("Property '{}' is not allowed", extra_prop),
|
|
||||||
cause: format!("additionalProperty '{}' not allowed", extra_prop),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ErrorKind::Pattern { got, want } => {
|
|
||||||
// Special handling for pattern errors to include the pattern in the message
|
|
||||||
let display_value = if got.len() > 50 {
|
|
||||||
format!("{}...", &got[..50])
|
|
||||||
} else {
|
|
||||||
got.to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
errors_list.push(Error {
|
|
||||||
path: error.instance_location.to_string(),
|
|
||||||
code: "PATTERN_VIOLATED".to_string(),
|
|
||||||
message: format!("Value does not match pattern: {}", want),
|
|
||||||
cause: format!("'{}' does not match pattern {}", display_value, want),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
// Handle all other error types normally
|
|
||||||
let original_message = format!("{}", error.kind);
|
|
||||||
let (error_code, human_message) = convert_error_kind(&error.kind);
|
|
||||||
|
|
||||||
errors_list.push(Error {
|
|
||||||
path: error.instance_location.to_string(),
|
|
||||||
code: error_code,
|
|
||||||
message: human_message,
|
|
||||||
cause: original_message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Recurse into causes
|
// Recurse into causes
|
||||||
@ -289,163 +242,428 @@ fn collect_errors(error: &ValidationError, errors_list: &mut Vec<Error>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert ErrorKind to error code and human message
|
// Handler functions for each error kind
|
||||||
fn convert_error_kind(kind: &ErrorKind) -> (String, String) {
|
fn handle_type_error(base_path: &str, got: &Type, want: &Types) -> Vec<Error> {
|
||||||
match kind {
|
vec![Error {
|
||||||
ErrorKind::Type { .. } => (
|
path: base_path.to_string(),
|
||||||
"TYPE_MISMATCH".to_string(),
|
code: "TYPE_MISMATCH".to_string(),
|
||||||
"Field type does not match the expected type".to_string(),
|
message: format!("Expected {} but got {}",
|
||||||
|
want.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" or "),
|
||||||
|
got
|
||||||
),
|
),
|
||||||
ErrorKind::Required { .. } => (
|
cause: json!({
|
||||||
"REQUIRED_FIELD_MISSING".to_string(),
|
"got": got.to_string(),
|
||||||
"Required field is missing".to_string(),
|
"want": want.iter().map(|t| t.to_string()).collect::<Vec<_>>()
|
||||||
|
}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_required_error(base_path: &str, want: &[&str]) -> Vec<Error> {
|
||||||
|
// Create a separate error for each missing required field
|
||||||
|
want.iter().map(|missing_field| {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, missing_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
Error {
|
||||||
|
path: field_path,
|
||||||
|
code: "REQUIRED_FIELD_MISSING".to_string(),
|
||||||
|
message: format!("Required field '{}' is missing", missing_field),
|
||||||
|
cause: json!({ "want": [missing_field] }),
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_dependency_error(base_path: &str, prop: &str, missing: &[&str], is_dependent_required: bool) -> Vec<Error> {
|
||||||
|
// Create a separate error for each missing field
|
||||||
|
missing.iter().map(|missing_field| {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, missing_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (code, message) = if is_dependent_required {
|
||||||
|
(
|
||||||
|
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
"DEPENDENCY_FAILED".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
Error {
|
||||||
|
path: field_path,
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
cause: json!({ "prop": prop, "missing": [missing_field] }),
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_additional_properties_error(base_path: &str, got: &[Cow<str>]) -> Vec<Error> {
|
||||||
|
// Create a separate error for each additional property that's not allowed
|
||||||
|
got.iter().map(|extra_prop| {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", extra_prop)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, extra_prop)
|
||||||
|
};
|
||||||
|
|
||||||
|
Error {
|
||||||
|
path: field_path,
|
||||||
|
code: "ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
||||||
|
message: format!("Property '{}' is not allowed", extra_prop),
|
||||||
|
cause: json!({ "got": [extra_prop.to_string()] }),
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_enum_error(base_path: &str, want: &[Value]) -> Vec<Error> {
|
||||||
|
let message = if want.len() == 1 {
|
||||||
|
format!("Value must be {}", serde_json::to_string(&want[0]).unwrap_or_else(|_| "unknown".to_string()))
|
||||||
|
} else {
|
||||||
|
format!("Value must be one of: {}",
|
||||||
|
want.iter()
|
||||||
|
.map(|v| serde_json::to_string(v).unwrap_or_else(|_| "unknown".to_string()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ENUM_VIOLATED".to_string(),
|
||||||
|
message,
|
||||||
|
cause: json!({ "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_const_error(base_path: &str, want: &Value) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONST_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be exactly {}", serde_json::to_string(want).unwrap_or_else(|_| "unknown".to_string())),
|
||||||
|
cause: json!({ "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_length_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_LENGTH_VIOLATED".to_string(),
|
||||||
|
message: format!("String length must be at least {} characters, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_length_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_LENGTH_VIOLATED".to_string(),
|
||||||
|
message: format!("String length must be at most {} characters, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_pattern_error(base_path: &str, got: &Cow<str>, want: &str) -> Vec<Error> {
|
||||||
|
let display_value = if got.len() > 50 {
|
||||||
|
format!("{}...", &got[..50])
|
||||||
|
} else {
|
||||||
|
got.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "PATTERN_VIOLATED".to_string(),
|
||||||
|
message: format!("Value '{}' does not match pattern '{}'", display_value, want),
|
||||||
|
cause: json!({ "got": got.to_string(), "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_minimum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MINIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be at least {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_maximum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAXIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be at most {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_exclusive_minimum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be greater than {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_exclusive_maximum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be less than {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_multiple_of_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MULTIPLE_OF_VIOLATED".to_string(),
|
||||||
|
message: format!("{} is not a multiple of {}", got, want),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_items_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array must have at least {} items, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_items_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array must have at most {} items, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_unique_items_error(base_path: &str, got: &[usize; 2]) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "UNIQUE_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array items at positions {} and {} are duplicates", got[0], got[1]),
|
||||||
|
cause: json!({ "got": got }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_properties_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
message: format!("Object must have at least {} properties, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_properties_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
message: format!("Object must have at most {} properties, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_additional_items_error(base_path: &str, got: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ADDITIONAL_ITEMS_NOT_ALLOWED".to_string(),
|
||||||
|
message: format!("Last {} array items are not allowed", got),
|
||||||
|
cause: json!({ "got": got }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_format_error(base_path: &str, want: &str, got: &Cow<Value>, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "FORMAT_INVALID".to_string(),
|
||||||
|
message: format!("Value {} is not a valid {} format",
|
||||||
|
serde_json::to_string(got.as_ref()).unwrap_or_else(|_| "unknown".to_string()),
|
||||||
|
want
|
||||||
),
|
),
|
||||||
ErrorKind::DependentRequired { .. } => (
|
cause: json!({ "got": got, "want": want, "err": err.to_string() }),
|
||||||
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
}]
|
||||||
"Dependent required fields are missing".to_string(),
|
}
|
||||||
|
|
||||||
|
fn handle_property_name_error(base_path: &str, prop: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "INVALID_PROPERTY_NAME".to_string(),
|
||||||
|
message: format!("Property name '{}' is invalid", prop),
|
||||||
|
cause: json!({ "prop": prop }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_contains_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTAINS_FAILED".to_string(),
|
||||||
|
message: "No array items match the required schema".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_contains_error(base_path: &str, got: &[usize], want: usize) -> Vec<Error> {
|
||||||
|
let message = if got.is_empty() {
|
||||||
|
format!("At least {} array items must match the schema, but none do", want)
|
||||||
|
} else {
|
||||||
|
format!("At least {} array items must match the schema, but only {} do (at positions {})",
|
||||||
|
want,
|
||||||
|
got.len(),
|
||||||
|
got.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_CONTAINS_VIOLATED".to_string(),
|
||||||
|
message,
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_contains_error(base_path: &str, got: &[usize], want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_CONTAINS_VIOLATED".to_string(),
|
||||||
|
message: format!("At most {} array items can match the schema, but {} do (at positions {})",
|
||||||
|
want,
|
||||||
|
got.len(),
|
||||||
|
got.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
|
||||||
),
|
),
|
||||||
ErrorKind::Dependency { .. } => (
|
cause: json!({ "got": got, "want": want }),
|
||||||
"DEPENDENCY_FAILED".to_string(),
|
}]
|
||||||
"Dependency requirement not met".to_string(),
|
}
|
||||||
|
|
||||||
|
fn handle_content_encoding_error(base_path: &str, want: &str, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_ENCODING_INVALID".to_string(),
|
||||||
|
message: format!("Content is not valid {} encoding: {}", want, err),
|
||||||
|
cause: json!({ "want": want, "err": err.to_string() }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_content_media_type_error(base_path: &str, want: &str, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_MEDIA_TYPE_INVALID".to_string(),
|
||||||
|
message: format!("Content is not valid {} media type: {}", want, err),
|
||||||
|
cause: json!({ "want": want, "err": err.to_string() }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_false_schema_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "FALSE_SCHEMA".to_string(),
|
||||||
|
message: "This schema always fails validation".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_not_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "NOT_VIOLATED".to_string(),
|
||||||
|
message: "Value matches a schema that it should not match".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_ref_cycle_error(base_path: &str, url: &str, kw_loc1: &str, kw_loc2: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "REFERENCE_CYCLE".to_string(),
|
||||||
|
message: format!("Reference cycle detected: both '{}' and '{}' resolve to '{}'", kw_loc1, kw_loc2, url),
|
||||||
|
cause: json!({ "url": url, "kw_loc1": kw_loc1, "kw_loc2": kw_loc2 }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_reference_error(base_path: &str, kw: &str, url: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "REFERENCE_FAILED".to_string(),
|
||||||
|
message: format!("{} reference to '{}' failed validation", kw, url),
|
||||||
|
cause: json!({ "kw": kw, "url": url }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_schema_error(base_path: &str, url: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "SCHEMA_FAILED".to_string(),
|
||||||
|
message: format!("Schema '{}' validation failed", url),
|
||||||
|
cause: json!({ "url": url }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_content_schema_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_SCHEMA_FAILED".to_string(),
|
||||||
|
message: "Content schema validation failed".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_group_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "VALIDATION_FAILED".to_string(),
|
||||||
|
message: "Validation failed".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_all_of_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ALL_OF_VIOLATED".to_string(),
|
||||||
|
message: "Value does not match all required schemas".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_any_of_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ANY_OF_VIOLATED".to_string(),
|
||||||
|
message: "Value does not match any of the allowed schemas".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_one_of_error(base_path: &str, matched: &Option<(usize, usize)>) -> Vec<Error> {
|
||||||
|
let (message, cause) = match matched {
|
||||||
|
None => (
|
||||||
|
"Value must match exactly one schema, but matches none".to_string(),
|
||||||
|
json!({ "matched_indices": null })
|
||||||
),
|
),
|
||||||
ErrorKind::Enum { .. } => (
|
Some((i, j)) => (
|
||||||
"ENUM_VIOLATED".to_string(),
|
format!("Value must match exactly one schema, but matches schemas at positions {} and {}", i, j),
|
||||||
"Value is not one of the allowed options".to_string(),
|
json!({ "matched_indices": [i, j] })
|
||||||
),
|
),
|
||||||
ErrorKind::Const { .. } => (
|
};
|
||||||
"CONST_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required constant".to_string(),
|
vec![Error {
|
||||||
),
|
path: base_path.to_string(),
|
||||||
ErrorKind::MinLength { .. } => (
|
code: "ONE_OF_VIOLATED".to_string(),
|
||||||
"MIN_LENGTH_VIOLATED".to_string(),
|
message,
|
||||||
"Field length is below the minimum required".to_string(),
|
cause,
|
||||||
),
|
}]
|
||||||
ErrorKind::MaxLength { .. } => (
|
|
||||||
"MAX_LENGTH_VIOLATED".to_string(),
|
|
||||||
"Field length exceeds the maximum allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Pattern { .. } => (
|
|
||||||
"PATTERN_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required pattern".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Minimum { .. } => (
|
|
||||||
"MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value is below the minimum allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Maximum { .. } => (
|
|
||||||
"MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value exceeds the maximum allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::ExclusiveMinimum { .. } => (
|
|
||||||
"EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be greater than the minimum".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::ExclusiveMaximum { .. } => (
|
|
||||||
"EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be less than the maximum".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MultipleOf { .. } => (
|
|
||||||
"MULTIPLE_OF_VIOLATED".to_string(),
|
|
||||||
"Value is not a multiple of the required factor".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MinItems { .. } => (
|
|
||||||
"MIN_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has fewer items than required".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MaxItems { .. } => (
|
|
||||||
"MAX_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has more items than allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::UniqueItems { .. } => (
|
|
||||||
"UNIQUE_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array contains duplicate items".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MinProperties { .. } => (
|
|
||||||
"MIN_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has fewer properties than required".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MaxProperties { .. } => (
|
|
||||||
"MAX_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has more properties than allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::AdditionalProperties { .. } => (
|
|
||||||
"ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
|
||||||
"Object contains properties that are not allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::AdditionalItems { .. } => (
|
|
||||||
"ADDITIONAL_ITEMS_NOT_ALLOWED".to_string(),
|
|
||||||
"Array contains additional items that are not allowed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Format { want, .. } => (
|
|
||||||
"FORMAT_INVALID".to_string(),
|
|
||||||
format!("Invalid {} format", want),
|
|
||||||
),
|
|
||||||
ErrorKind::PropertyName { .. } => (
|
|
||||||
"INVALID_PROPERTY_NAME".to_string(),
|
|
||||||
"Property name is invalid".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Contains => (
|
|
||||||
"CONTAINS_FAILED".to_string(),
|
|
||||||
"No items match the required schema".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MinContains { .. } => (
|
|
||||||
"MIN_CONTAINS_VIOLATED".to_string(),
|
|
||||||
"Too few items match the required schema".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::MaxContains { .. } => (
|
|
||||||
"MAX_CONTAINS_VIOLATED".to_string(),
|
|
||||||
"Too many items match the required schema".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::ContentEncoding { .. } => (
|
|
||||||
"CONTENT_ENCODING_INVALID".to_string(),
|
|
||||||
"Content encoding is invalid".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::ContentMediaType { .. } => (
|
|
||||||
"CONTENT_MEDIA_TYPE_INVALID".to_string(),
|
|
||||||
"Content media type is invalid".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::FalseSchema => (
|
|
||||||
"FALSE_SCHEMA".to_string(),
|
|
||||||
"Schema validation always fails".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Not => (
|
|
||||||
"NOT_VIOLATED".to_string(),
|
|
||||||
"Value matched a schema it should not match".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::RefCycle { .. } => (
|
|
||||||
"REFERENCE_CYCLE".to_string(),
|
|
||||||
"Schema contains a reference cycle".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Reference { .. } => (
|
|
||||||
"REFERENCE_FAILED".to_string(),
|
|
||||||
"Reference validation failed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::Schema { .. } => (
|
|
||||||
"SCHEMA_FAILED".to_string(),
|
|
||||||
"Schema validation failed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::ContentSchema => (
|
|
||||||
"CONTENT_SCHEMA_FAILED".to_string(),
|
|
||||||
"Content schema validation failed".to_string(),
|
|
||||||
),
|
|
||||||
// These shouldn't appear as leaf errors due to is_structural check
|
|
||||||
ErrorKind::Group => (
|
|
||||||
"VALIDATION_FAILED".to_string(),
|
|
||||||
"Validation failed".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::AllOf => (
|
|
||||||
"ALL_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match all required schemas".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::AnyOf => (
|
|
||||||
"ANY_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match any of the allowed schemas".to_string(),
|
|
||||||
),
|
|
||||||
ErrorKind::OneOf(_) => (
|
|
||||||
"ONE_OF_VIOLATED".to_string(),
|
|
||||||
"Value must match exactly one schema".to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
||||||
|
|||||||
61
src/tests.rs
61
src/tests.rs
@ -151,12 +151,17 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
|
|
||||||
// Invalid type - age is negative
|
// Invalid type - age is negative
|
||||||
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
||||||
assert_failure_with_json!(invalid_result_type, 1, "Value is below the minimum allowed", "Validation with invalid type should fail.");
|
assert_failure_with_json!(invalid_result_type, 1, "Value must be at least 0, but got -5", "Validation with invalid type should fail.");
|
||||||
let errors_type = invalid_result_type.0["errors"].as_array().unwrap();
|
let errors_type = invalid_result_type.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_type[0]["details"]["path"], "/age");
|
assert_eq!(errors_type[0]["details"]["path"], "/age");
|
||||||
assert_eq!(errors_type[0]["details"]["context"], -5);
|
assert_eq!(errors_type[0]["details"]["context"], -5);
|
||||||
assert_eq!(errors_type[0]["details"]["schema"], "my_schema");
|
assert_eq!(errors_type[0]["details"]["schema"], "my_schema");
|
||||||
assert_eq!(errors_type[0]["code"], "MINIMUM_VIOLATED");
|
assert_eq!(errors_type[0]["code"], "MINIMUM_VIOLATED");
|
||||||
|
// Check the cause is now a JSON object
|
||||||
|
let cause_type = &errors_type[0]["details"]["cause"];
|
||||||
|
assert!(cause_type.is_object());
|
||||||
|
assert_eq!(cause_type["got"], -5);
|
||||||
|
assert_eq!(cause_type["want"], 0);
|
||||||
|
|
||||||
// Missing field
|
// Missing field
|
||||||
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
||||||
@ -165,6 +170,10 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
assert_eq!(errors_missing[0]["details"]["path"], "/age");
|
assert_eq!(errors_missing[0]["details"]["path"], "/age");
|
||||||
assert_eq!(errors_missing[0]["details"]["schema"], "my_schema");
|
assert_eq!(errors_missing[0]["details"]["schema"], "my_schema");
|
||||||
assert_eq!(errors_missing[0]["code"], "REQUIRED_FIELD_MISSING");
|
assert_eq!(errors_missing[0]["code"], "REQUIRED_FIELD_MISSING");
|
||||||
|
// Check the cause is now a JSON object
|
||||||
|
let cause_missing = &errors_missing[0]["details"]["cause"];
|
||||||
|
assert!(cause_missing.is_object());
|
||||||
|
assert_eq!(cause_missing["want"], json!(["age"]));
|
||||||
|
|
||||||
// Schema not found
|
// Schema not found
|
||||||
let non_existent_id = "non_existent_schema";
|
let non_existent_id = "non_existent_schema";
|
||||||
@ -173,6 +182,8 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
|
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_notfound[0]["code"], "SCHEMA_NOT_FOUND");
|
assert_eq!(errors_notfound[0]["code"], "SCHEMA_NOT_FOUND");
|
||||||
assert_eq!(errors_notfound[0]["details"]["schema"], "non_existent_schema");
|
assert_eq!(errors_notfound[0]["details"]["schema"], "non_existent_schema");
|
||||||
|
// Schema not found still has string cause (it's not from ErrorKind)
|
||||||
|
assert_eq!(errors_notfound[0]["details"]["cause"], "Schema must be cached before validation");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -200,7 +211,7 @@ fn test_cache_invalid_json_schema() {
|
|||||||
assert_failure_with_json!(
|
assert_failure_with_json!(
|
||||||
cache_result,
|
cache_result,
|
||||||
2, // Expect exactly two leaf errors
|
2, // Expect exactly two leaf errors
|
||||||
"Value is not one of the allowed options", // Updated to human-readable message
|
"Value must be one of", // Updated to human-readable message
|
||||||
"Caching invalid schema should fail with specific meta-schema validation errors."
|
"Caching invalid schema should fail with specific meta-schema validation errors."
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -219,6 +230,12 @@ fn test_cache_invalid_json_schema() {
|
|||||||
// Check schema field is present
|
// Check schema field is present
|
||||||
assert_eq!(errors_array[0]["details"]["schema"], "invalid_schema");
|
assert_eq!(errors_array[0]["details"]["schema"], "invalid_schema");
|
||||||
assert_eq!(errors_array[1]["details"]["schema"], "invalid_schema");
|
assert_eq!(errors_array[1]["details"]["schema"], "invalid_schema");
|
||||||
|
// Check that cause is now a JSON object with want array
|
||||||
|
for error in errors_array {
|
||||||
|
let cause = &error["details"]["cause"];
|
||||||
|
assert!(cause.is_object());
|
||||||
|
assert!(cause["want"].is_array());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -417,23 +434,32 @@ fn test_root_level_type_mismatch() {
|
|||||||
// Test 1: Validate null against array schema (simulating delete_tokens issue)
|
// Test 1: Validate null against array schema (simulating delete_tokens issue)
|
||||||
let null_instance = json!(null);
|
let null_instance = json!(null);
|
||||||
let null_result = validate_json_schema(schema_id, jsonb(null_instance));
|
let null_result = validate_json_schema(schema_id, jsonb(null_instance));
|
||||||
assert_failure_with_json!(null_result, 1, "Field type does not match the expected type");
|
assert_failure_with_json!(null_result, 1, "Expected array but got null");
|
||||||
let null_errors = null_result.0["errors"].as_array().unwrap();
|
let null_errors = null_result.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(null_errors[0]["code"], "TYPE_MISMATCH");
|
assert_eq!(null_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
assert_eq!(null_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
assert_eq!(null_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
||||||
assert_eq!(null_errors[0]["details"]["context"], json!(null));
|
assert_eq!(null_errors[0]["details"]["context"], json!(null));
|
||||||
assert_eq!(null_errors[0]["details"]["schema"], "array_schema");
|
assert_eq!(null_errors[0]["details"]["schema"], "array_schema");
|
||||||
assert!(null_errors[0]["details"]["cause"].as_str().unwrap().contains("want array"));
|
// Check cause is now a JSON object
|
||||||
|
let cause_null = &null_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_null.is_object());
|
||||||
|
assert_eq!(cause_null["got"], "null");
|
||||||
|
assert_eq!(cause_null["want"], json!(["array"]));
|
||||||
|
|
||||||
// Test 2: Validate object against array schema
|
// Test 2: Validate object against array schema
|
||||||
let object_instance = json!({"id": "not-an-array"});
|
let object_instance = json!({"id": "not-an-array"});
|
||||||
let object_result = validate_json_schema(schema_id, jsonb(object_instance.clone()));
|
let object_result = validate_json_schema(schema_id, jsonb(object_instance.clone()));
|
||||||
assert_failure_with_json!(object_result, 1, "Field type does not match the expected type");
|
assert_failure_with_json!(object_result, 1, "Expected array but got object");
|
||||||
let object_errors = object_result.0["errors"].as_array().unwrap();
|
let object_errors = object_result.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(object_errors[0]["code"], "TYPE_MISMATCH");
|
assert_eq!(object_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
assert_eq!(object_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
assert_eq!(object_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
||||||
assert_eq!(object_errors[0]["details"]["context"], object_instance);
|
assert_eq!(object_errors[0]["details"]["context"], object_instance);
|
||||||
assert_eq!(object_errors[0]["details"]["schema"], "array_schema");
|
assert_eq!(object_errors[0]["details"]["schema"], "array_schema");
|
||||||
|
// Check cause is now a JSON object
|
||||||
|
let cause_object = &object_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_object.is_object());
|
||||||
|
assert_eq!(cause_object["got"], "object");
|
||||||
|
assert_eq!(cause_object["want"], json!(["array"]));
|
||||||
|
|
||||||
// Test 3: Valid empty array
|
// Test 3: Valid empty array
|
||||||
let valid_empty = json!([]);
|
let valid_empty = json!([]);
|
||||||
@ -454,12 +480,17 @@ fn test_root_level_type_mismatch() {
|
|||||||
// String at root when object expected
|
// String at root when object expected
|
||||||
let string_instance = json!("not an object");
|
let string_instance = json!("not an object");
|
||||||
let string_result = validate_json_schema(object_schema_id, jsonb(string_instance));
|
let string_result = validate_json_schema(object_schema_id, jsonb(string_instance));
|
||||||
assert_failure_with_json!(string_result, 1, "Field type does not match the expected type");
|
assert_failure_with_json!(string_result, 1, "Expected object but got string");
|
||||||
let string_errors = string_result.0["errors"].as_array().unwrap();
|
let string_errors = string_result.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(string_errors[0]["code"], "TYPE_MISMATCH");
|
assert_eq!(string_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
assert_eq!(string_errors[0]["details"]["path"], ""); // Root level path
|
assert_eq!(string_errors[0]["details"]["path"], ""); // Root level path
|
||||||
assert_eq!(string_errors[0]["details"]["schema"], "object_schema");
|
assert_eq!(string_errors[0]["details"]["schema"], "object_schema");
|
||||||
assert_eq!(string_errors[0]["details"]["context"], json!("not an object"));
|
assert_eq!(string_errors[0]["details"]["context"], json!("not an object"));
|
||||||
|
// Check cause is now a JSON object
|
||||||
|
let cause_string = &string_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_string.is_object());
|
||||||
|
assert_eq!(cause_string["got"], "string");
|
||||||
|
assert_eq!(cause_string["want"], json!(["object"]));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -534,11 +565,15 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_root_strict = validate_json_schema(schema_id, jsonb(invalid_root_extra.clone()));
|
let result_root_strict = validate_json_schema(schema_id, jsonb(invalid_root_extra.clone()));
|
||||||
assert_failure_with_json!(result_root_strict, 1, "Schema validation always fails");
|
assert_failure_with_json!(result_root_strict, 1, "This schema always fails validation");
|
||||||
let errors_root = result_root_strict.0["errors"].as_array().unwrap();
|
let errors_root = result_root_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_root[0]["code"], "FALSE_SCHEMA");
|
assert_eq!(errors_root[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_root[0]["details"]["path"], "/extraField");
|
assert_eq!(errors_root[0]["details"]["path"], "/extraField");
|
||||||
assert_eq!(errors_root[0]["details"]["schema"], "strict_test");
|
assert_eq!(errors_root[0]["details"]["schema"], "strict_test");
|
||||||
|
// Check cause is now a JSON object (empty for FalseSchema)
|
||||||
|
let cause_root = &errors_root[0]["details"]["cause"];
|
||||||
|
assert!(cause_root.is_object());
|
||||||
|
assert_eq!(cause_root, &json!({}));
|
||||||
|
|
||||||
// Should pass with non-strict schema
|
// Should pass with non-strict schema
|
||||||
let result_root_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_root_extra));
|
let result_root_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_root_extra));
|
||||||
@ -555,7 +590,7 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_nested_strict = validate_json_schema(schema_id, jsonb(invalid_nested_extra.clone()));
|
let result_nested_strict = validate_json_schema(schema_id, jsonb(invalid_nested_extra.clone()));
|
||||||
assert_failure_with_json!(result_nested_strict, 1, "Schema validation always fails");
|
assert_failure_with_json!(result_nested_strict, 1, "This schema always fails validation");
|
||||||
let errors_nested = result_nested_strict.0["errors"].as_array().unwrap();
|
let errors_nested = result_nested_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_nested[0]["code"], "FALSE_SCHEMA");
|
assert_eq!(errors_nested[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_nested[0]["details"]["path"], "/profile/extraNested");
|
assert_eq!(errors_nested[0]["details"]["path"], "/profile/extraNested");
|
||||||
@ -579,7 +614,7 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_deep_strict = validate_json_schema(schema_id, jsonb(invalid_deep_extra.clone()));
|
let result_deep_strict = validate_json_schema(schema_id, jsonb(invalid_deep_extra.clone()));
|
||||||
assert_failure_with_json!(result_deep_strict, 1, "Schema validation always fails");
|
assert_failure_with_json!(result_deep_strict, 1, "This schema always fails validation");
|
||||||
let errors_deep = result_deep_strict.0["errors"].as_array().unwrap();
|
let errors_deep = result_deep_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_deep[0]["code"], "FALSE_SCHEMA");
|
assert_eq!(errors_deep[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_deep[0]["details"]["path"], "/profile/preferences/extraDeep");
|
assert_eq!(errors_deep[0]["details"]["path"], "/profile/preferences/extraDeep");
|
||||||
@ -599,7 +634,7 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_array_strict = validate_json_schema(schema_id, jsonb(invalid_array_item_extra.clone()));
|
let result_array_strict = validate_json_schema(schema_id, jsonb(invalid_array_item_extra.clone()));
|
||||||
assert_failure_with_json!(result_array_strict, 1, "Schema validation always fails");
|
assert_failure_with_json!(result_array_strict, 1, "This schema always fails validation");
|
||||||
let errors_array = result_array_strict.0["errors"].as_array().unwrap();
|
let errors_array = result_array_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_array[0]["code"], "FALSE_SCHEMA");
|
assert_eq!(errors_array[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_array[0]["details"]["path"], "/tags/0/extraInArray");
|
assert_eq!(errors_array[0]["details"]["path"], "/tags/0/extraInArray");
|
||||||
@ -680,7 +715,7 @@ fn test_auto_strict_validation() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let result_invalid_conditional = validate_json_schema(schema_id_conditional, jsonb(invalid_conditional));
|
let result_invalid_conditional = validate_json_schema(schema_id_conditional, jsonb(invalid_conditional));
|
||||||
assert_failure_with_json!(result_invalid_conditional, 1, "Schema validation always fails");
|
assert_failure_with_json!(result_invalid_conditional, 1, "This schema always fails validation");
|
||||||
let errors_conditional = result_invalid_conditional.0["errors"].as_array().unwrap();
|
let errors_conditional = result_invalid_conditional.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_conditional[0]["code"], "FALSE_SCHEMA");
|
assert_eq!(errors_conditional[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_conditional[0]["details"]["path"], "/extra");
|
assert_eq!(errors_conditional[0]["details"]["path"], "/extra");
|
||||||
@ -1116,7 +1151,7 @@ fn test_unevaluated_properties_errors() {
|
|||||||
let result = validate_json_schema(schema_id, jsonb(instance_uneval));
|
let result = validate_json_schema(schema_id, jsonb(instance_uneval));
|
||||||
|
|
||||||
// Should get 3 separate FALSE_SCHEMA errors, one for each unevaluated property
|
// Should get 3 separate FALSE_SCHEMA errors, one for each unevaluated property
|
||||||
assert_failure_with_json!(result, 3, "Schema validation always fails");
|
assert_failure_with_json!(result, 3, "This schema always fails validation");
|
||||||
|
|
||||||
let errors = result.0["errors"].as_array().unwrap();
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
@ -1177,7 +1212,7 @@ fn test_unevaluated_properties_errors() {
|
|||||||
let complex_result = validate_json_schema(complex_schema_id, jsonb(complex_instance));
|
let complex_result = validate_json_schema(complex_schema_id, jsonb(complex_instance));
|
||||||
|
|
||||||
// Should get 2 FALSE_SCHEMA errors for unevaluated properties
|
// Should get 2 FALSE_SCHEMA errors for unevaluated properties
|
||||||
assert_failure_with_json!(complex_result, 2, "Schema validation always fails");
|
assert_failure_with_json!(complex_result, 2, "This schema always fails validation");
|
||||||
|
|
||||||
let complex_errors = complex_result.0["errors"].as_array().unwrap();
|
let complex_errors = complex_result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user