better error messaging
This commit is contained in:
264
src/tests.rs
Normal file
264
src/tests.rs
Normal file
@ -0,0 +1,264 @@
|
||||
use crate::*;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
// Helper macro for asserting success with pretty JSON output on failure
|
||||
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 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));
|
||||
// Construct the full message string first
|
||||
let panic_msg = format!("Assertion Failed (expected success): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
panic!("{}", panic_msg); // Use the constructed string
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Helper macro for asserting failure with pretty JSON output on failure
|
||||
macro_rules! assert_failure_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(false) {
|
||||
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));
|
||||
// Construct the full message string first
|
||||
let panic_msg = format!("Assertion Failed (expected failure): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
panic!("{}", panic_msg); // Use the constructed string
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn jsonb(val: Value) -> JsonB {
|
||||
JsonB(val)
|
||||
}
|
||||
|
||||
fn setup_test() {
|
||||
clear_json_schemas();
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_cache_and_validate_json_schema() {
|
||||
setup_test();
|
||||
let schema_id = "my_schema";
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": { "type": "string" },
|
||||
"age": { "type": "integer", "minimum": 0 }
|
||||
},
|
||||
"required": ["name", "age"]
|
||||
});
|
||||
let valid_instance = json!({ "name": "Alice", "age": 30 });
|
||||
let invalid_instance_type = json!({ "name": "Bob", "age": -5 });
|
||||
let invalid_instance_missing = json!({ "name": "Charlie" });
|
||||
|
||||
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||
assert_success_with_json!(cache_result, "Cache operation should succeed.");
|
||||
|
||||
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
|
||||
assert_success_with_json!(valid_result, "Validation of valid instance should succeed.");
|
||||
|
||||
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
||||
assert_failure_with_json!(invalid_result_type, "Validation with invalid type should fail.");
|
||||
|
||||
let error_obj_type = invalid_result_type.0.get("error").expect("Expected top-level 'error' object");
|
||||
let causes_age = error_obj_type.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||
assert!(!causes_age.is_empty(), "Expected causes for invalid age");
|
||||
let age_error = causes_age.iter().find(|e| e["instance_path"].as_str() == Some("/age")).expect("Missing cause for /age instance path");
|
||||
let age_error_message = age_error["message"].as_str().expect("Expected string message for age error");
|
||||
assert_eq!(age_error_message, "must be >=0, but got -5", "Age error message mismatch: '{}'", age_error_message);
|
||||
|
||||
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
||||
assert_failure_with_json!(invalid_result_missing, "Validation with missing field should fail.");
|
||||
let error_obj_missing = invalid_result_missing.0.get("error").expect("Expected 'error' object for missing field");
|
||||
let causes_missing = error_obj_missing.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||
assert!(!causes_missing.is_empty(), "Expected causes for missing field");
|
||||
let missing_prop_error = causes_missing.iter().find(|e| e["instance_path"].as_str() == Some("")).expect("Missing cause for root instance path");
|
||||
let expected_missing_message = "missing properties 'age'";
|
||||
assert_eq!(missing_prop_error["message"].as_str().expect("Expected string message for missing prop error"), expected_missing_message, "Missing property error message mismatch: '{}'", missing_prop_error["message"].as_str().unwrap_or("null"));
|
||||
|
||||
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, "Validation with non-existent schema should fail.");
|
||||
let error_obj = invalid_schema_result.0.get("error").expect("Expected top-level 'error' object");
|
||||
assert_eq!(error_obj["message"].as_str().expect("Expected message for cleared schema"), "Schema with id 'non_existent_schema' not found in cache");
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_not_cached() {
|
||||
setup_test();
|
||||
let instance = json!({ "foo": "bar" });
|
||||
let result = validate_json_schema("non_existent_schema", jsonb(instance));
|
||||
assert_failure_with_json!(result, "Validation with non-existent schema should fail.");
|
||||
assert_eq!(result.0.get("success"), Some(&Value::Bool(false)), "Expected 'success': false for non-existent schema");
|
||||
let error_obj = result.0.get("error").expect("Expected nested 'error' object for non-existent schema failure");
|
||||
let error_message = error_obj["message"].as_str().expect("Expected message string for non-existent schema");
|
||||
assert!(error_message.contains("non_existent_schema") && error_message.contains("not found"), "Error message mismatch for non-existent schema: '{}'", error_message);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_cache_invalid_json_schema() {
|
||||
setup_test();
|
||||
let schema_id = "invalid_schema";
|
||||
let invalid_schema = json!({ "type": "invalid" });
|
||||
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
|
||||
assert_failure_with_json!(cache_result, "Caching invalid schema should fail.");
|
||||
|
||||
let error_obj = cache_result.0.get("error").expect("Expected 'error' object for failed cache");
|
||||
let message = error_obj.get("message").and_then(Value::as_str).expect("Message field missing");
|
||||
let expected_message_start = &format!("Schema '{}' failed validation against its metaschema: ", schema_id);
|
||||
assert!(message.starts_with(expected_message_start), "Compile error message start mismatch: {}", message);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_detailed_validation_errors() {
|
||||
setup_test();
|
||||
let schema_id = "detailed_errors";
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"address": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"street": { "type": "string" },
|
||||
"city": { "type": "string", "maxLength": 10 }
|
||||
},
|
||||
"required": ["street", "city"]
|
||||
}
|
||||
},
|
||||
"required": ["address"]
|
||||
});
|
||||
let _ = cache_json_schema(schema_id, jsonb(schema));
|
||||
|
||||
let invalid_instance = json!({
|
||||
"address": {
|
||||
"street": 123,
|
||||
"city": "Supercalifragilisticexpialidocious"
|
||||
}
|
||||
});
|
||||
|
||||
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
|
||||
assert_failure_with_json!(result, "Validation should fail for detailed errors test.");
|
||||
|
||||
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
|
||||
assert_eq!(error_obj["message"].as_str(), Some("Validation failed due to nested errors"));
|
||||
|
||||
let causes_array = error_obj.get("error").and_then(Value::as_array).expect("Expected nested error array");
|
||||
assert_eq!(causes_array.len(), 2, "Expected exactly 2 top-level errors (street type, city length)");
|
||||
|
||||
let street_error = causes_array.iter().find(|e| e["instance_path"].as_str() == Some("/address/street")).expect("Missing street error");
|
||||
assert_eq!(street_error["message"].as_str().expect("Expected string message for street error"), "want string, but got number", "Street error message mismatch");
|
||||
|
||||
let city_error = causes_array.iter().find(|e| e["instance_path"].as_str() == Some("/address/city")).expect("Missing city error");
|
||||
let expected_city_error_message = "length must be <=10, but got 34";
|
||||
assert_eq!(city_error["message"].as_str().expect("Expected string message for city error"), expected_city_error_message, "City error message mismatch");
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_oneof_validation_errors() {
|
||||
setup_test();
|
||||
let schema_id = "oneof_schema";
|
||||
let schema = json!({
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"string_prop": { "type": "string", "maxLength": 5 }
|
||||
},
|
||||
"required": ["string_prop"]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"number_prop": { "type": "number", "minimum": 10 }
|
||||
},
|
||||
"required": ["number_prop"]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
let _ = cache_json_schema(schema_id, jsonb(schema));
|
||||
|
||||
let expected_urn = format!("urn:{}#", schema_id);
|
||||
|
||||
// --- Test case 1: String length failure ---
|
||||
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
|
||||
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
|
||||
assert_failure_with_json!(result_invalid_string, "Validation with invalid string length should fail");
|
||||
let error_obj_string = result_invalid_string.0.get("error").expect("Expected error object (string case)");
|
||||
|
||||
// Check the top-level error object directly: Input matches Branch 0 type, fails maxLength validation within it.
|
||||
assert_eq!(error_obj_string["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (string case)");
|
||||
assert_eq!(error_obj_string["instance_path"].as_str(), Some(""), "Incorrect instance_path for string fail (string case)");
|
||||
let actual_string_schema_fail_message = error_obj_string["message"].as_str().expect("Expected string message for string schema fail");
|
||||
let expected_string_schema_fail_message = "Validation failed due to nested errors";
|
||||
assert_eq!(actual_string_schema_fail_message, expected_string_schema_fail_message, "String schema fail message mismatch: '{}'", actual_string_schema_fail_message);
|
||||
|
||||
// --- Test case 2: Number type failure ---
|
||||
let invalid_number_instance = json!({ "number_prop": 5 });
|
||||
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
|
||||
assert_failure_with_json!(result_invalid_number, "Validation with invalid number should fail");
|
||||
let error_obj_number = result_invalid_number.0.get("error").expect("Expected error object (number case)");
|
||||
|
||||
// Check the top-level error object directly: Input matches Branch 1 type, fails minimum validation within it.
|
||||
assert_eq!(error_obj_number["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (number case)");
|
||||
assert_eq!(error_obj_number["instance_path"].as_str(), Some(""), "Incorrect instance_path for number fail (number case)");
|
||||
let actual_number_schema_fail_message_num = error_obj_number["message"].as_str().expect("Expected string message for number schema fail (number case)");
|
||||
let expected_number_schema_fail_message_num = "Validation failed due to nested errors";
|
||||
assert_eq!(actual_number_schema_fail_message_num, expected_number_schema_fail_message_num, "Number schema fail message mismatch (number case): '{}'", actual_number_schema_fail_message_num);
|
||||
|
||||
// --- Test case 3: Bool type failure ---
|
||||
let invalid_bool_instance = json!({ "bool_prop": 123 });
|
||||
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
|
||||
assert_failure_with_json!(result_invalid_bool, "Validation with invalid bool should fail");
|
||||
let error_obj_bool = result_invalid_bool.0.get("error").expect("Expected error object (bool case)");
|
||||
|
||||
// Boon reports the failure for the first branch checked (Branch 0).
|
||||
assert_eq!(error_obj_bool["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (bool case)");
|
||||
// Instance path is empty because the failure is at the root of the object being checked against Branch 0
|
||||
assert_eq!(error_obj_bool["instance_path"].as_str(), Some(""), "Incorrect instance_path for bool fail");
|
||||
let actual_bool_fail_message_0 = error_obj_bool["message"].as_str().expect("Expected string message for branch 0 type fail");
|
||||
let expected_bool_fail_message_0 = "Validation failed due to nested errors";
|
||||
assert_eq!(actual_bool_fail_message_0, expected_bool_fail_message_0, "Branch 0 type fail message mismatch: '{}'", actual_bool_fail_message_0);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_clear_json_schemas() {
|
||||
setup_test();
|
||||
let schema_id = "schema_to_clear";
|
||||
let schema = json!({ "type": "string" });
|
||||
cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||
|
||||
let show_result1 = show_json_schemas();
|
||||
assert!(show_result1.contains(&schema_id.to_string()));
|
||||
|
||||
clear_json_schemas();
|
||||
|
||||
let show_result2 = show_json_schemas();
|
||||
assert!(show_result2.is_empty());
|
||||
|
||||
let instance = json!("test");
|
||||
let validate_result = validate_json_schema(schema_id, jsonb(instance));
|
||||
assert_failure_with_json!(validate_result, "Validation should fail after clearing schemas.");
|
||||
|
||||
let error_obj = validate_result.0.get("error").expect("Expected top-level 'error' object");
|
||||
assert_eq!(error_obj["message"].as_str().expect("Expected message for cleared schema"), "Schema with id 'schema_to_clear' not found in cache");
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_show_json_schemas() {
|
||||
setup_test();
|
||||
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 result = show_json_schemas();
|
||||
assert!(result.contains(&schema_id1.to_string()));
|
||||
assert!(result.contains(&schema_id2.to_string()));
|
||||
}
|
||||
Reference in New Issue
Block a user