error handling improvements to jspg to match drop structure
This commit is contained in:
297
src/tests.rs
297
src/tests.rs
@ -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)));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user