error handling improvements to jspg to match drop structure

This commit is contained in:
2025-06-06 13:58:50 -04:00
parent 8ec6a5b58a
commit dce50d9dc3
5 changed files with 374 additions and 780 deletions

View File

@ -31,11 +31,14 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
// Use schema_path when adding the resource
if let Err(e) = compiler.add_resource(&schema_path, schema_value.clone()) {
return JsonB(json!({
"success": false,
"error": {
"message": format!("Failed to add schema resource '{}': {}", schema_id, e),
"schema_path": schema_path
}
"errors": [{
"code": "SCHEMA_RESOURCE_ADD_FAILED",
"message": format!("Failed to add schema resource '{}'", schema_id),
"details": {
"path": schema_path,
"cause": format!("{}", e)
}
}]
}));
}
@ -44,32 +47,30 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
Ok(sch_index) => {
// Store the index using the original schema_id as the key
cache.id_to_index.insert(schema_id.to_string(), sch_index);
JsonB(json!({ "success": true }))
JsonB(json!({ "response": "success" }))
}
Err(e) => {
let error = match &e {
CompileError::ValidationError { url: _url, src } => {
let errors = match &e {
CompileError::ValidationError { url: _url, src } => {
// Collect leaf errors from the meta-schema validation failure
let mut error_list = Vec::new();
collect_leaf_errors(src, &mut error_list);
// Filter and deduplicate errors, returning as a single JSON Value (Array)
json!(filter_boon_errors(error_list))
collect_validation_errors(src, &mut error_list);
// Filter and format errors properly - no instance for schema compilation
format_drop_errors(error_list, &schema_value)
}
_ => {
// Keep existing handling for other compilation errors
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string();
json!({
"message": format!("Schema '{}' compilation failed: {}", schema_id, e),
"schema_path": schema_path,
"detail": format!("{:?}", e),
})
// Other compilation errors
vec![json!({
"code": "SCHEMA_COMPILATION_FAILED",
"message": format!("Schema '{}' compilation failed", schema_id),
"details": {
"path": schema_path,
"cause": format!("{:?}", e)
}
})]
}
};
// Ensure the outer structure remains { success: false, error: ... }
JsonB(json!({
"success": false,
"error": error
}))
JsonB(json!({ "errors": errors }))
}
}
}
@ -81,97 +82,233 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
// Lookup uses the original schema_id
match cache.id_to_index.get(schema_id) {
None => JsonB(json!({
"success": false,
"error": {
"message": format!("Schema with id '{}' not found in cache", schema_id)
}
"errors": [{
"code": "SCHEMA_NOT_FOUND",
"message": format!("Schema '{}' not found in cache", schema_id),
"details": {
"cause": "Schema must be cached before validation"
}
}]
})),
Some(sch_index) => {
let instance_value: Value = instance.0;
match cache.schemas.validate(&instance_value, *sch_index) {
Ok(_) => JsonB(json!({ "success": true })),
Ok(_) => JsonB(json!({ "response": "success" })),
Err(validation_error) => {
// Directly use the result of format_validation_error
// which now includes the top-level success indicator and flat error list
let mut error_list = Vec::new();
collect_leaf_errors(&validation_error, &mut error_list);
JsonB(json!({
"success": false,
"error": filter_boon_errors(error_list) // Filter and deduplicate errors
}))
collect_validation_errors(&validation_error, &mut error_list);
let errors = format_drop_errors(error_list, &instance_value);
JsonB(json!({ "errors": errors }))
}
}
}
}
}
// Recursively collects leaf errors into a flat list
fn collect_leaf_errors(error: &ValidationError, errors_list: &mut Vec<Value>) {
if error.causes.is_empty() {
let default_message = format!("{}", error);
let message = if let Some(start_index) = default_message.find("': ") {
default_message[start_index + 3..].to_string()
} else {
default_message
};
// Recursively collects validation errors
fn collect_validation_errors(error: &ValidationError, errors_list: &mut Vec<(String, String, String)>) {
// Check if this is a structural error that we should skip
let error_message = format!("{}", error.kind);
let is_structural = error_message == "validation failed" ||
error_message == "allOf failed" ||
error_message == "anyOf failed" ||
error_message == "not failed" ||
error_message.starts_with("oneOf failed");
if error.causes.is_empty() && !is_structural {
// This is a leaf error that's not structural
// Format just the error kind, not the whole validation error
let message = format!("{}", error.kind);
errors_list.push(json!({
"message": message,
"schema_path": error.schema_url.to_string(),
"instance_path": error.instance_location.to_string(),
}));
errors_list.push((
error.instance_location.to_string(),
error.schema_url.to_string(),
message
));
} else {
// Recurse into causes
for cause in &error.causes {
collect_leaf_errors(cause, errors_list);
collect_validation_errors(cause, errors_list);
}
}
}
// Filters collected errors, removing structural noise and then deduplicating by instance_path
fn filter_boon_errors(raw_errors: Vec<Value>) -> Vec<Value> {
// Formats errors according to DropError structure
fn format_drop_errors(raw_errors: Vec<(String, String, String)>, instance: &Value) -> Vec<Value> {
use std::collections::HashMap;
use std::collections::hash_map::Entry;
// Define schema keywords that indicate structural paths, not instance paths
let structural_path_segments = [
"/allOf/", "/anyOf/", "/oneOf/",
"/if/", "/then/", "/else/",
"/not/"
// Note: "/properties/" and "/items/" are generally valid,
// but might appear spuriously in boon's paths for complex types.
// We exclude only the explicitly logical/combinatorial ones for now.
];
// We don't filter structural paths from instance paths anymore
// because instance paths shouldn't contain these segments anyway
// The issue was likely with schema paths, not instance paths
let plausible_errors = raw_errors;
// 1. Filter out errors with instance_paths containing structural segments
let plausible_errors: Vec<Value> = raw_errors.into_iter().filter(|error_value| {
if let Some(instance_path_value) = error_value.get("instance_path") {
if let Some(instance_path_str) = instance_path_value.as_str() {
// Keep if NONE of the structural segments are present
!structural_path_segments.iter().any(|&segment| instance_path_str.contains(segment))
} else {
false // Invalid instance_path type, filter out
}
} else {
false // No instance_path field, filter out
}
}).collect();
// 2. Deduplicate the remaining plausible errors by instance_path
// 2. Deduplicate by instance_path and format as DropError
let mut unique_errors: HashMap<String, Value> = HashMap::new();
for error_value in plausible_errors {
if let Some(instance_path_value) = error_value.get("instance_path") {
if let Some(instance_path_str) = instance_path_value.as_str() {
if let Entry::Vacant(entry) = unique_errors.entry(instance_path_str.to_string()) {
entry.insert(error_value);
for (instance_path, schema_path, message) in plausible_errors {
if let Entry::Vacant(entry) = unique_errors.entry(instance_path.clone()) {
// Convert message to error code and make it human readable
let (code, human_message) = enhance_error_message(&message);
// Extract the failing value from the instance
let failing_value = extract_value_at_path(instance, &instance_path);
entry.insert(json!({
"code": code,
"message": human_message,
"details": {
"path": schema_path,
"context": json!({
"instance_path": instance_path,
"failing_value": failing_value
}),
"cause": message // Original error message
}
}
}));
}
}
// Collect the unique errors
unique_errors.into_values().collect()
}
// Helper function to extract value at a JSON pointer path
fn extract_value_at_path(instance: &Value, path: &str) -> Value {
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let mut current = instance;
for part in parts {
match current {
Value::Object(map) => {
if let Some(value) = map.get(part) {
current = value;
} else {
return Value::Null;
}
}
Value::Array(arr) => {
if let Ok(index) = part.parse::<usize>() {
if let Some(value) = arr.get(index) {
current = value;
} else {
return Value::Null;
}
} else {
return Value::Null;
}
}
_ => return Value::Null,
}
}
current.clone()
}
// Helper to convert validation messages to error codes and human-readable messages
fn enhance_error_message(message: &str) -> (String, String) {
// Match exact boon error message patterns
let trimmed = message.trim();
if trimmed.contains("value must be one of") {
("ENUM_VIOLATED".to_string(),
"Value is not one of the allowed options".to_string())
} else if trimmed.contains("length must be >=") && trimmed.contains("but got") {
("MIN_LENGTH_VIOLATED".to_string(),
"Field length is below the minimum required".to_string())
} else if trimmed.contains("length must be <=") && trimmed.contains("but got") {
("MAX_LENGTH_VIOLATED".to_string(),
"Field length exceeds the maximum allowed".to_string())
} else if trimmed.contains("must be >=") && trimmed.contains("but got") {
("MINIMUM_VIOLATED".to_string(),
"Value is below the minimum allowed".to_string())
} else if trimmed.contains("must be <=") && trimmed.contains("but got") {
("MAXIMUM_VIOLATED".to_string(),
"Value exceeds the maximum allowed".to_string())
} else if trimmed.contains("must be >") && trimmed.contains("but got") {
("EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
"Value must be greater than the minimum".to_string())
} else if trimmed.contains("must be <") && trimmed.contains("but got") {
("EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
"Value must be less than the maximum".to_string())
} else if trimmed.contains("does not match pattern") {
("PATTERN_VIOLATED".to_string(),
"Value does not match the required pattern".to_string())
} else if trimmed.contains("missing properties") {
("REQUIRED_FIELD_MISSING".to_string(),
"Required field is missing".to_string())
} else if trimmed.contains("want") && trimmed.contains("but got") {
("TYPE_MISMATCH".to_string(),
"Field type does not match the expected type".to_string())
} else if trimmed.starts_with("value must be") && !trimmed.contains("one of") {
("CONST_VIOLATED".to_string(),
"Value does not match the required constant".to_string())
} else if trimmed.contains("is not valid") && trimmed.contains(":") {
("FORMAT_INVALID".to_string(),
extract_format_message(trimmed))
} else if trimmed.contains("items at") && trimmed.contains("are equal") {
("UNIQUE_ITEMS_VIOLATED".to_string(),
"Array contains duplicate items".to_string())
} else if trimmed.contains("additionalProperties") && trimmed.contains("not allowed") {
("ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
"Object contains properties that are not allowed".to_string())
} else if trimmed.contains("is not multipleOf") {
("MULTIPLE_OF_VIOLATED".to_string(),
"Value is not a multiple of the required factor".to_string())
} else if trimmed.contains("minimum") && trimmed.contains("properties required") {
("MIN_PROPERTIES_VIOLATED".to_string(),
"Object has fewer properties than required".to_string())
} else if trimmed.contains("maximum") && trimmed.contains("properties required") {
("MAX_PROPERTIES_VIOLATED".to_string(),
"Object has more properties than allowed".to_string())
} else if trimmed.contains("minimum") && trimmed.contains("items required") {
("MIN_ITEMS_VIOLATED".to_string(),
"Array has fewer items than required".to_string())
} else if trimmed.contains("maximum") && trimmed.contains("items required") {
("MAX_ITEMS_VIOLATED".to_string(),
"Array has more items than allowed".to_string())
} else if trimmed == "false schema" {
("FALSE_SCHEMA".to_string(),
"Schema validation always fails".to_string())
} else if trimmed == "not failed" {
("NOT_VIOLATED".to_string(),
"Value matched a schema it should not match".to_string())
} else if trimmed == "allOf failed" {
("ALL_OF_VIOLATED".to_string(),
"Value does not match all required schemas".to_string())
} else if trimmed == "anyOf failed" {
("ANY_OF_VIOLATED".to_string(),
"Value does not match any of the allowed schemas".to_string())
} else if trimmed.contains("oneOf failed") {
("ONE_OF_VIOLATED".to_string(),
"Value must match exactly one schema".to_string())
} else if trimmed == "validation failed" {
("VALIDATION_FAILED".to_string(),
"Validation failed".to_string())
} else {
// For any unmatched patterns, try to provide a generic human-readable message
// while preserving the original error in details.cause
("VALIDATION_FAILED".to_string(),
"Validation failed".to_string())
}
}
// Extract a better format message
fn extract_format_message(message: &str) -> String {
if message.contains("date-time") {
"Invalid date-time format".to_string()
} else if message.contains("email") {
"Invalid email format".to_string()
} else if message.contains("uri") {
"Invalid URI format".to_string()
} else if message.contains("uuid") {
"Invalid UUID format".to_string()
} else {
"Invalid format".to_string()
}
}
#[pg_extern(strict, parallel_safe)]
fn json_schema_cached(schema_id: &str) -> bool {
let cache = SCHEMA_CACHE.read().unwrap();
@ -179,19 +316,20 @@ fn json_schema_cached(schema_id: &str) -> bool {
}
#[pg_extern(strict)]
fn clear_json_schemas() {
fn clear_json_schemas() -> JsonB {
let mut cache = SCHEMA_CACHE.write().unwrap();
*cache = BoonCache {
schemas: Schemas::new(),
id_to_index: HashMap::new(),
};
JsonB(json!({ "response": "success" }))
}
#[pg_extern(strict, parallel_safe)]
fn show_json_schemas() -> Vec<String> {
fn show_json_schemas() -> JsonB {
let cache = SCHEMA_CACHE.read().unwrap();
let ids: Vec<String> = cache.id_to_index.keys().cloned().collect();
ids
JsonB(json!({ "response": ids }))
}
/// This module is required by `cargo pgrx test` invocations.
@ -214,4 +352,4 @@ pub mod pg_test {
#[pg_schema]
mod tests {
include!("tests.rs");
}
}

View File

@ -2,94 +2,67 @@ use crate::*;
use serde_json::{json, Value};
use pgrx::{JsonB, pg_test};
// Helper macro for asserting success (no changes needed, but ensure it's present)
// Helper macro for asserting success with Drop-style response
macro_rules! assert_success_with_json {
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => {
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
if condition_result != Some(true) {
let has_response = $result_jsonb.0.get("response").is_some();
let has_errors = $result_jsonb.0.get("errors").is_some();
if !has_response || has_errors {
let base_msg = format!($fmt $(, $($args)*)?);
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
let panic_msg = format!("Assertion Failed (expected success): {}\nResult JSON:\n{}", base_msg, pretty_json);
let panic_msg = format!("Assertion Failed (expected success with 'response' field): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("{}", panic_msg);
}
};
// Simpler version without message
($result_jsonb:expr) => {
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
if condition_result != Some(true) {
let has_response = $result_jsonb.0.get("response").is_some();
let has_errors = $result_jsonb.0.get("errors").is_some();
if !has_response || has_errors {
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
let panic_msg = format!("Assertion Failed (expected success)\nResult JSON:\n{}", pretty_json);
let panic_msg = format!("Assertion Failed (expected success with 'response' field)\nResult JSON:\n{}", pretty_json);
panic!("{}", panic_msg);
}
};
}
// Updated helper macro for asserting failed JSON results with the new flat error structure
// Helper macro for asserting failed JSON results with Drop-style errors
macro_rules! assert_failure_with_json {
// --- Arms with error count and message substring check ---
// With custom message:
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr, $fmt:literal $(, $($args:tt)*)?) => {
let json_result = &$result.0;
let success = json_result.get("success").and_then(Value::as_bool);
let error_val_opt = json_result.get("error"); // Changed key
let has_response = json_result.get("response").is_some();
let errors_opt = json_result.get("errors");
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
if has_response || errors_opt.is_none() {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("Assertion Failed (expected failure with 'errors' field): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
match error_val_opt {
Some(error_val) => {
if error_val.is_array() {
let errors_array = error_val.as_array().unwrap();
if errors_array.len() != $expected_error_count {
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
if errors_array.len() != $expected_error_count {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
}
if $expected_error_count > 0 {
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
match first_error_message {
Some(msg) => {
if !msg.contains($expected_first_message_contains) {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
panic!("Assertion Failed (first error message mismatch): Expected contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
}
if $expected_error_count > 0 {
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
match first_error_message {
Some(msg) => {
if !msg.contains($expected_first_message_contains) {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (first error message mismatch): Expected contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
}
}
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (first error in array has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
}
} else if error_val.is_object() {
// Handle single error object case (like 'schema not found')
if $expected_error_count != 1 {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, but got a single error object. {}\nResult JSON:\n{}", $expected_error_count, base_msg, pretty_json);
}
let message = error_val.get("message").and_then(Value::as_str);
match message {
Some(msg) => {
if !msg.contains($expected_first_message_contains) {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (error message mismatch): Expected object message contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
}
}
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (error object has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
} else {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (first error in array has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
}
};
@ -102,37 +75,20 @@ macro_rules! assert_failure_with_json {
// With custom message:
($result:expr, $expected_error_count:expr, $fmt:literal $(, $($args:tt)*)?) => {
let json_result = &$result.0;
let success = json_result.get("success").and_then(Value::as_bool);
let error_val_opt = json_result.get("error"); // Changed key
let has_response = json_result.get("response").is_some();
let errors_opt = json_result.get("errors");
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
if has_response || errors_opt.is_none() {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("Assertion Failed (expected failure with 'errors' field): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
match error_val_opt {
Some(error_val) => {
if error_val.is_array() {
let errors_array = error_val.as_array().unwrap();
if errors_array.len() != $expected_error_count {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
}
} else if error_val.is_object() {
if $expected_error_count != 1 {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, but got a single error object. {}\nResult JSON:\n{}", $expected_error_count, base_msg, pretty_json);
}
// Count check passes if expected is 1 and got object
} else {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
if errors_array.len() != $expected_error_count {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
}
};
// Without custom message (calls the one above with ""):
@ -144,33 +100,20 @@ macro_rules! assert_failure_with_json {
// With custom message:
($result:expr, $fmt:literal $(, $($args:tt)*)?) => {
let json_result = &$result.0;
let success = json_result.get("success").and_then(Value::as_bool);
let error_val_opt = json_result.get("error"); // Changed key
let has_response = json_result.get("response").is_some();
let errors_opt = json_result.get("errors");
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
if has_response || errors_opt.is_none() {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("Assertion Failed (expected failure with 'errors' field): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
match error_val_opt {
Some(error_val) => {
if error_val.is_object() {
// OK: single error object is a failure
} else if error_val.is_array() {
if error_val.as_array().unwrap().is_empty() {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected errors, but 'error' array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
// OK: non-empty error array is a failure
} else {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
None => {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
if errors_array.is_empty() {
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
panic!("Assertion Failed (expected errors, but 'errors' array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
};
// Without custom message (calls the one above with ""):
@ -206,42 +149,41 @@ fn test_cache_and_validate_json_schema() {
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
assert_success_with_json!(valid_result, "Validation of valid instance should succeed.");
// Invalid type
// Invalid type - age is negative
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
assert_failure_with_json!(invalid_result_type, 1, "must be >=0", "Validation with invalid type should fail.");
let errors_type = invalid_result_type.0["error"].as_array().unwrap(); // Check 'error', expect array
assert_eq!(errors_type[0]["instance_path"], "/age");
assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
assert_failure_with_json!(invalid_result_type, 1, "Value is below the minimum allowed", "Validation with invalid type should fail.");
let errors_type = invalid_result_type.0["errors"].as_array().unwrap();
assert_eq!(errors_type[0]["details"]["context"]["instance_path"], "/age");
assert_eq!(errors_type[0]["details"]["path"], "urn:my_schema#/properties/age");
assert_eq!(errors_type[0]["code"], "MINIMUM_VIOLATED");
// Missing field
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
assert_failure_with_json!(invalid_result_missing, 1, "missing properties 'age'", "Validation with missing field should fail.");
let errors_missing = invalid_result_missing.0["error"].as_array().unwrap(); // Check 'error', expect array
assert_eq!(errors_missing[0]["instance_path"], "");
assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
assert_failure_with_json!(invalid_result_missing, 1, "Required field is missing", "Validation with missing field should fail.");
let errors_missing = invalid_result_missing.0["errors"].as_array().unwrap();
assert_eq!(errors_missing[0]["details"]["context"]["instance_path"], "");
assert_eq!(errors_missing[0]["details"]["path"], "urn:my_schema#");
assert_eq!(errors_missing[0]["code"], "REQUIRED_FIELD_MISSING");
// Schema not found
let non_existent_id = "non_existent_schema";
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({})));
assert_failure_with_json!(invalid_schema_result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
// Check 'error' is an object for 'schema not found'
let error_notfound_obj = invalid_schema_result.0["error"].as_object().expect("'error' should be an object for schema not found");
assert!(error_notfound_obj.contains_key("message")); // Check message exists
// Removed checks for schema_path/instance_path as they aren't added in lib.rs for this case
assert_failure_with_json!(invalid_schema_result, 1, "Schema 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
assert_eq!(errors_notfound[0]["code"], "SCHEMA_NOT_FOUND");
}
#[pg_test]
fn test_validate_json_schema_not_cached() {
clear_json_schemas(); // Call clear directly
clear_json_schemas();
let instance = json!({ "foo": "bar" });
let result = validate_json_schema("non_existent_schema", jsonb(instance));
// Use the updated macro, expecting count 1 and specific message (handles object case)
assert_failure_with_json!(result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
assert_failure_with_json!(result, 1, "Schema 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
}
#[pg_test]
fn test_cache_invalid_json_schema() {
clear_json_schemas(); // Call clear directly
clear_json_schemas();
let schema_id = "invalid_schema";
// Schema with an invalid type *value*
let invalid_schema = json!({
@ -256,19 +198,22 @@ fn test_cache_invalid_json_schema() {
assert_failure_with_json!(
cache_result,
2, // Expect exactly two leaf errors
"value must be one of", // Check message substring (present in both)
"Value is not one of the allowed options", // Updated to human-readable message
"Caching invalid schema should fail with specific meta-schema validation errors."
);
// Ensure the error is an array and check specifics
let error_array = cache_result.0["error"].as_array().expect("Error field should be an array");
assert_eq!(error_array.len(), 2);
// Note: Order might vary depending on boon's internal processing, check both possibilities or sort.
// Assuming the order shown in the logs for now:
assert_eq!(error_array[0]["instance_path"], "/type");
assert!(error_array[0]["message"].as_str().unwrap().contains("value must be one of"));
assert_eq!(error_array[1]["instance_path"], "/type/0");
assert!(error_array[1]["message"].as_str().unwrap().contains("value must be one of"));
// Ensure the errors array exists and check specifics
let errors_array = cache_result.0["errors"].as_array().expect("Errors field should be an array");
assert_eq!(errors_array.len(), 2);
// Both errors should have ENUM_VIOLATED code
assert_eq!(errors_array[0]["code"], "ENUM_VIOLATED");
assert_eq!(errors_array[1]["code"], "ENUM_VIOLATED");
// Check instance paths are preserved in context
let paths: Vec<&str> = errors_array.iter()
.map(|e| e["details"]["context"]["instance_path"].as_str().unwrap())
.collect();
assert!(paths.contains(&"/type"));
assert!(paths.contains(&"/type/0"));
}
#[pg_test]
@ -336,9 +281,15 @@ fn test_validate_json_schema_oneof_validation_errors() {
// Expect 2 leaf errors. Check count only with the macro.
assert_failure_with_json!(result_invalid_string, 2);
// Explicitly check that both expected errors are present, ignoring order
let errors_string = result_invalid_string.0["error"].as_array().expect("Expected error array for invalid string");
assert!(errors_string.iter().any(|e| e["instance_path"] == "/string_prop" && e["message"].as_str().unwrap().contains("length must be <=5")), "Missing maxLength error");
assert!(errors_string.iter().any(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("missing properties 'number_prop'")), "Missing number_prop required error");
let errors_string = result_invalid_string.0["errors"].as_array().expect("Expected error array for invalid string");
assert!(errors_string.iter().any(|e|
e["details"]["context"]["instance_path"] == "/string_prop" &&
e["code"] == "MAX_LENGTH_VIOLATED"
), "Missing maxLength error");
assert!(errors_string.iter().any(|e|
e["details"]["context"]["instance_path"] == "" &&
e["code"] == "REQUIRED_FIELD_MISSING"
), "Missing number_prop required error");
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
let invalid_number_instance = json!({ "number_prop": 5 });
@ -346,9 +297,15 @@ fn test_validate_json_schema_oneof_validation_errors() {
// Expect 2 leaf errors. Check count only with the macro.
assert_failure_with_json!(result_invalid_number, 2);
// Explicitly check that both expected errors are present, ignoring order
let errors_number = result_invalid_number.0["error"].as_array().expect("Expected error array for invalid number");
assert!(errors_number.iter().any(|e| e["instance_path"] == "/number_prop" && e["message"].as_str().unwrap().contains("must be >=10")), "Missing minimum error");
assert!(errors_number.iter().any(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("missing properties 'string_prop'")), "Missing string_prop required error");
let errors_number = result_invalid_number.0["errors"].as_array().expect("Expected error array for invalid number");
assert!(errors_number.iter().any(|e|
e["details"]["context"]["instance_path"] == "/number_prop" &&
e["code"] == "MINIMUM_VIOLATED"
), "Missing minimum error");
assert!(errors_number.iter().any(|e|
e["details"]["context"]["instance_path"] == "" &&
e["code"] == "REQUIRED_FIELD_MISSING"
), "Missing string_prop required error");
// --- Test case 3: Fails type check (not object) for both branches ---
// Input: boolean, expected object for both branches
@ -357,8 +314,10 @@ fn test_validate_json_schema_oneof_validation_errors() {
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
assert_failure_with_json!(result_invalid_bool, 1);
// Explicitly check that the single remaining error is the type error for the root instance path
let errors_bool = result_invalid_bool.0["error"].as_array().expect("Expected error array for invalid bool");
assert_eq!(errors_bool.iter().filter(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("want object")).count(), 1, "Expected one 'want object' error at root after filtering");
let errors_bool = result_invalid_bool.0["errors"].as_array().expect("Expected error array for invalid bool");
assert_eq!(errors_bool.len(), 1, "Expected exactly one error after deduplication");
assert_eq!(errors_bool[0]["code"], "TYPE_MISMATCH");
assert_eq!(errors_bool[0]["details"]["context"]["instance_path"], "");
// --- Test case 4: Fails missing required for both branches ---
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
@ -367,49 +326,53 @@ fn test_validate_json_schema_oneof_validation_errors() {
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
assert_failure_with_json!(result_empty_obj, 1);
// Explicitly check that the single remaining error is one of the expected missing properties errors
let errors_empty = result_empty_obj.0["error"].as_array().expect("Expected error array for empty object");
let errors_empty = result_empty_obj.0["errors"].as_array().expect("Expected error array for empty object");
assert_eq!(errors_empty.len(), 1, "Expected exactly one error after filtering empty object");
let the_error = &errors_empty[0];
assert_eq!(the_error["instance_path"], "", "Expected instance_path to be empty string");
let message = the_error["message"].as_str().unwrap();
assert!(message.contains("missing properties 'string_prop'") || message.contains("missing properties 'number_prop'"),
"Error message should indicate missing string_prop or number_prop, got: {}", message);
assert_eq!(errors_empty[0]["code"], "REQUIRED_FIELD_MISSING");
assert_eq!(errors_empty[0]["details"]["context"]["instance_path"], "");
// The human message should be generic
assert_eq!(errors_empty[0]["message"], "Required field is missing");
}
#[pg_test]
fn test_clear_json_schemas() {
clear_json_schemas(); // Call clear directly
let clear_result = clear_json_schemas();
assert_success_with_json!(clear_result);
let schema_id = "schema_to_clear";
let schema = json!({ "type": "string" });
cache_json_schema(schema_id, jsonb(schema.clone()));
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
assert_success_with_json!(cache_result);
let show_result1 = show_json_schemas();
assert!(show_result1.contains(&schema_id.to_string()));
let schemas1 = show_result1.0["response"].as_array().unwrap();
assert!(schemas1.contains(&json!(schema_id)));
clear_json_schemas();
let clear_result2 = clear_json_schemas();
assert_success_with_json!(clear_result2);
let show_result2 = show_json_schemas();
assert!(show_result2.is_empty());
let schemas2 = show_result2.0["response"].as_array().unwrap();
assert!(schemas2.is_empty());
let instance = json!("test");
let validate_result = validate_json_schema(schema_id, jsonb(instance));
// Use the updated macro, expecting count 1 and specific message (handles object case)
assert_failure_with_json!(validate_result, 1, "Schema with id 'schema_to_clear' not found", "Validation should fail after clearing schemas.");
assert_failure_with_json!(validate_result, 1, "Schema 'schema_to_clear' not found", "Validation should fail after clearing schemas.");
}
#[pg_test]
fn test_show_json_schemas() {
clear_json_schemas(); // Call clear directly
let _ = clear_json_schemas();
let schema_id1 = "schema1";
let schema_id2 = "schema2";
let schema = json!({ "type": "boolean" });
cache_json_schema(schema_id1, jsonb(schema.clone()));
cache_json_schema(schema_id2, jsonb(schema.clone()));
let _ = cache_json_schema(schema_id1, jsonb(schema.clone()));
let _ = cache_json_schema(schema_id2, jsonb(schema.clone()));
let mut result = show_json_schemas(); // Make result mutable
result.sort(); // Sort for deterministic testing
assert_eq!(result, vec!["schema1".to_string(), "schema2".to_string()]); // Check exact content
assert!(result.contains(&schema_id1.to_string())); // Keep specific checks too if desired
assert!(result.contains(&schema_id2.to_string()));
}
let result = show_json_schemas();
let schemas = result.0["response"].as_array().unwrap();
assert_eq!(schemas.len(), 2);
assert!(schemas.contains(&json!(schema_id1)));
assert!(schemas.contains(&json!(schema_id2)));
}