Compare commits

..

7 Commits

Author SHA1 Message Date
3ceb8a0770 version: 1.0.14 2025-04-16 00:38:10 -04:00
499bf68b2a more error cleanup 2025-04-16 00:38:04 -04:00
6ca00f27e9 version: 1.0.13 2025-04-15 23:30:57 -04:00
520be66035 better error messaging 2025-04-15 23:30:47 -04:00
c3146ca433 flow update 2025-04-15 01:52:12 -04:00
b4d9628b05 version: 1.0.12 2025-04-15 00:25:39 -04:00
635d31d723 more validation fixes 2025-04-15 00:25:29 -04:00
5 changed files with 443 additions and 310 deletions

4
.env
View File

@ -1,7 +1,7 @@
ENVIRONMENT=local
DATABASE_PASSWORD=2HwURf1Za7m5ZKtECAfQJGpni3832RV3
DATABASE_PASSWORD=QgSvstSjoc6fKphMzNgT3SliNY10eSRS
DATABASE_ROLE=agreego_admin
DATABASE_HOST=127.1.27.10
DATABASE_HOST=127.1.27.9
DATABASE_PORT=5432
POSTGRES_PASSWORD=xzIq5JT0xY3F+2m1GtnrKDdK29sNSXVVYZHPKJVh8pI=
DATABASE_NAME=agreego

2
flows

Submodule flows updated: db55335254...9d758d581e

View File

@ -4,7 +4,7 @@ pg_module_magic!();
use serde_json::{json, Value};
use std::{collections::HashMap, sync::RwLock};
use boon::{Compiler, Schemas, ValidationError, SchemaIndex};
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
use lazy_static::lazy_static;
struct BoonCache {
@ -23,36 +23,52 @@ lazy_static! {
fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
let mut cache = SCHEMA_CACHE.write().unwrap();
let schema_value: Value = schema.0;
let schema_path = format!("urn:{}", schema_id);
let mut compiler = Compiler::new();
compiler.enable_format_assertions();
let schema_url = format!("urn:jspg:{}", schema_id);
if let Err(e) = compiler.add_resource(&schema_url, schema_value) {
// 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": {
"kind": "SchemaResourceError",
"message": format!("Failed to add schema resource: {}", e),
"schema_id": schema_id
"message": format!("Failed to add schema resource '{}': {}", schema_id, e),
"schema_path": schema_path
}
}));
}
match compiler.compile(&schema_url, &mut cache.schemas) {
// Use schema_path when compiling
match compiler.compile(&schema_path, &mut cache.schemas) {
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 }))
}
Err(e) => JsonB(json!({
"success": false,
"error": {
"kind": "SchemaCompilationError",
"message": format!("Schema compilation failed: {}", e),
"schema_id": schema_id
}
})),
Err(e) => {
let error = match &e {
CompileError::ValidationError { url: _url, src } => { // Prefix url with _
json!({
"message": format!("Schema '{}' failed validation against its metaschema: {}", schema_id, src),
"schema_path": schema_path,
"error": format!("{:?}", src),
})
}
_ => {
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string(); // Prefix error_type with _
json!({
"message": format!("Schema '{}' compilation failed: {}", schema_id, e),
"schema_path": schema_path,
"error": format!("{:?}", e),
})
}
};
JsonB(json!({
"success": false,
"error": error
}))
}
}
}
@ -60,41 +76,60 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
let cache = SCHEMA_CACHE.read().unwrap();
// Lookup uses the original schema_id
match cache.id_to_index.get(schema_id) {
None => JsonB(json!({
"success": false,
"error": {
"kind": "SchemaNotFound",
"message": format!("Schema with id '{}' not found in cache", schema_id)
}
"errors": [json!({
"message": format!("Schema with id '{}' not found in cache", schema_id),
"schema_path": "",
"instance_path": ""
})]
})),
Some(sch_index) => {
let instance_value: Value = instance.0;
match cache.schemas.validate(&instance_value, *sch_index) {
Ok(_) => JsonB(json!({ "success": true })),
Err(validation_error) => {
let error = format_validation_error(&validation_error);
JsonB(json!({
"success": false,
"error": error
}))
// Directly use the result of format_validation_error
// which now includes the top-level success indicator and flat error list
JsonB(format_validation_error(&validation_error))
}
}
}
}
}
// 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
};
errors_list.push(json!({
"message": message,
"schema_path": error.schema_url.to_string(),
"instance_path": error.instance_location.to_string(),
}));
} else {
for cause in &error.causes {
collect_leaf_errors(cause, errors_list);
}
}
}
// Formats validation errors into a flat list JSON structure
fn format_validation_error(error: &ValidationError) -> Value {
let mut all_errors = Vec::new();
collect_leaf_errors(error, &mut all_errors);
json!({
"instance_path": error.instance_location.to_string(),
"schema_path": error.schema_url.to_string(),
"kind": format!("{:?}", error.kind),
"message": format!("{}", error),
"error": error
.causes
.iter()
.map(format_validation_error)
.collect::<Vec<_>>()
"success": false,
"errors": all_errors // Flat list of specific errors
})
}
@ -120,286 +155,24 @@ fn show_json_schemas() -> Vec<String> {
ids
}
#[pg_schema]
#[cfg(any(test, feature = "pg_test"))]
mod tests {
use pgrx::*;
use pgrx::pg_test;
use super::*;
use serde_json::json;
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!(cache_result.0["success"].as_bool().unwrap());
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
assert!(valid_result.0["success"].as_bool().unwrap());
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
assert!(!invalid_result_type.0["success"].as_bool().unwrap());
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 first_cause_age = &causes_age[0];
assert!(first_cause_age["kind"].as_str().unwrap().contains("Minimum"), "Kind '{}' should contain Minimum", first_cause_age["kind"]);
let msg = first_cause_age["message"].as_str().unwrap_or("");
assert!(msg.contains("must be >=0"), "Error message mismatch for age minimum: {}", msg);
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
assert!(!invalid_result_missing.0["success"].as_bool().unwrap());
let error_obj_missing = invalid_result_missing.0.get("error").expect("Expected top-level 'error' object");
let causes_missing = error_obj_missing.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes) for missing");
assert!(!causes_missing.is_empty(), "Expected causes for missing age");
let first_cause_missing = &causes_missing[0];
assert!(first_cause_missing["kind"].as_str().unwrap().contains("Required"));
let msg_missing = first_cause_missing["message"].as_str().unwrap_or("");
assert!(msg_missing.contains("missing properties 'age'"), "Error message mismatch for missing 'age': {}", msg_missing);
assert!(first_cause_missing["instance_path"] == "", "Expected empty instance path for missing field");
let non_existent_id = "non_existent_schema";
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({})));
assert!(!invalid_schema_result.0["success"].as_bool().unwrap());
let schema_not_found_error = invalid_schema_result.0
.get("error") // Top level error object
.expect("Expected top-level 'error' object for schema not found");
assert_eq!(schema_not_found_error["kind"], "SchemaNotFound");
assert!(schema_not_found_error["message"].as_str().unwrap().contains(non_existent_id));
}
#[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!(!result.0["success"].as_bool().unwrap());
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
assert_eq!(error_obj["kind"], "SchemaNotFound");
assert!(error_obj["message"].as_str().unwrap().contains("non_existent_schema"));
}
#[pg_test]
fn test_cache_invalid_json_schema() {
setup_test();
let schema_id = "invalid_schema";
let invalid_schema_json = "{\"type\": \"string\" \"maxLength\": 5}";
let invalid_schema_value: Result<Value, _> = serde_json::from_str(invalid_schema_json);
assert!(invalid_schema_value.is_err(), "Test setup assumes invalid JSON string");
let schema_representing_invalid = json!({
"type": 123
});
let result = cache_json_schema(schema_id, jsonb(schema_representing_invalid.clone()));
assert!(!result.0["success"].as_bool().unwrap());
let error_obj = result.0.get("error").expect("Expected top-level 'error' object for compilation failure");
assert_eq!(error_obj.get("kind").and_then(Value::as_str), Some("SchemaCompilationError"));
assert!(error_obj.get("message").and_then(Value::as_str).is_some(), "Expected 'message' field in error object");
assert!(error_obj["message"].as_str().unwrap().contains("Schema compilation failed")); // Check content of message
assert_eq!(error_obj.get("schema_id").and_then(Value::as_str), Some(schema_id));
}
#[pg_test]
fn test_validate_json_schema_detailed_validation_errors() {
setup_test();
let schema_id = "detailed_schema";
let schema = json!({
"type": "object",
"properties": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string", "maxLength": 10 }
},
"required": ["street", "city"]
}
},
"required": ["address"]
});
let invalid_instance = json!({
"address": {
"street": 123,
"city": "Supercalifragilisticexpialidocious"
}
});
assert!(cache_json_schema(schema_id, jsonb(schema.clone())).0["success"].as_bool().unwrap());
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
assert!(!result.0["success"].as_bool().unwrap());
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
let causes = error_obj.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert!(causes.len() >= 2, "Expected at least 2 detailed causes");
let street_error = causes.iter().find(|e| e["instance_path"] == "/address/street").expect("Missing street error");
assert!(street_error["kind"].as_str().unwrap().contains("Type"), "Kind '{}' should contain Type", street_error["kind"]);
let street_msg = street_error["message"].as_str().unwrap_or("null");
assert!(street_msg.contains("want string, but got number"), "Street message mismatch: {}", street_msg);
let city_error = causes.iter().find(|e| e["instance_path"] == "/address/city").expect("Missing city error");
assert!(city_error["kind"].as_str().unwrap().contains("MaxLength"), "Kind '{}' should contain MaxLength", city_error["kind"]);
let city_msg = city_error["message"].as_str().unwrap_or("null");
assert!(city_msg.contains("length must be <=10"), "City message mismatch: {}", city_msg);
assert_eq!(causes.len(), 2, "Expected exactly 2 errors (street type, city length)");
}
#[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"]
}
]
});
cache_json_schema(schema_id, jsonb(schema));
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
assert!(!result_invalid_string.0["success"].as_bool().unwrap());
let error_obj_string = result_invalid_string.0.get("error").expect("Expected top-level 'error' object");
assert!(error_obj_string["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_string["kind"]);
assert!(error_obj_string["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_string["message"]); // Final adjustment
let causes_string = error_obj_string.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert_eq!(causes_string.len(), 1, "Expected one cause for oneOf failure (string)");
let nested_causes_string = causes_string[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for string oneOf");
assert_eq!(nested_causes_string.len(), 2, "Expected two nested causes for string oneOf");
let string_schema_fail = nested_causes_string.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0/properties/string_prop")).expect("Missing nested cause for string schema");
assert_eq!(string_schema_fail["instance_path"].as_str().unwrap(), "/string_prop", "Instance path should be /string_prop");
assert!(string_schema_fail["kind"].as_str().unwrap().contains("MaxLength"), "Nested string cause kind should be MaxLength");
let number_schema_fail = nested_causes_string.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1")).expect("Missing nested cause for number schema");
assert_eq!(number_schema_fail["instance_path"].as_str().unwrap(), "", "Instance path for branch 2 type mismatch should be empty");
assert!(number_schema_fail["kind"].as_str().unwrap().contains("Required"), "Nested number cause kind should be Required");
let invalid_number_instance = json!({ "number_prop": 5 });
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
assert!(!result_invalid_number.0["success"].as_bool().unwrap());
let error_obj_number = result_invalid_number.0.get("error").expect("Expected top-level 'error' object");
assert!(error_obj_number["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_number["kind"]);
assert!(error_obj_number["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_number["message"]); // Final adjustment
let causes_number = error_obj_number.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert_eq!(causes_number.len(), 1, "Expected one cause for oneOf failure (number)");
let nested_causes_number = causes_number[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for number oneOf");
assert_eq!(nested_causes_number.len(), 2, "Expected two nested causes for number oneOf");
let string_schema_fail_num = nested_causes_number.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0")).expect("Missing nested cause for string schema (number case)");
assert_eq!(string_schema_fail_num["instance_path"].as_str().unwrap(), "", "Instance path for branch 1 type mismatch should be empty");
assert!(string_schema_fail_num["kind"].as_str().unwrap().contains("Required"), "Nested string cause kind should be Required (number case)");
let number_schema_fail_num = nested_causes_number.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1/properties/number_prop")).expect("Missing nested cause for number schema (number case)");
assert_eq!(number_schema_fail_num["instance_path"].as_str().unwrap(), "/number_prop", "Instance path should be /number_prop (number case)");
assert!(number_schema_fail_num["kind"].as_str().unwrap().contains("Minimum"), "Nested number cause kind should be Minimum (number case)");
let invalid_bool_instance = json!({ "other_prop": true });
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
assert!(!result_invalid_bool.0["success"].as_bool().unwrap());
let error_obj_bool = result_invalid_bool.0.get("error").expect("Expected top-level 'error' object");
assert!(error_obj_bool["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_bool["kind"]);
assert!(error_obj_bool["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_bool["message"]); // Final adjustment
let causes_bool = error_obj_bool.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert_eq!(causes_bool.len(), 1, "Expected one cause for oneOf failure (bool)");
let nested_causes_bool = causes_bool[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for bool oneOf");
assert_eq!(nested_causes_bool.len(), 2, "Expected two nested causes for bool oneOf");
let bool_fail_0 = nested_causes_bool.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0")).expect("Missing nested cause for branch 0 type fail");
assert_eq!(bool_fail_0["instance_path"].as_str().unwrap(), "", "Instance path for branch 0 type fail should be empty");
assert!(bool_fail_0["kind"].as_str().unwrap().contains("Required"), "Nested bool cause 0 kind should be Required");
let bool_fail_1 = nested_causes_bool.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1")).expect("Missing nested cause for branch 1 type fail");
assert_eq!(bool_fail_1["instance_path"].as_str().unwrap(), "", "Instance path for branch 1 type fail should be empty");
assert!(bool_fail_1["kind"].as_str().unwrap().contains("Required"), "Nested bool cause 1 kind should be Required");
}
#[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!(!validate_result.0["success"].as_bool().unwrap());
let error_obj = validate_result.0.get("error").expect("Expected top-level 'error' object");
assert_eq!(error_obj["kind"], "SchemaNotFound");
assert!(error_obj["message"].as_str().unwrap().contains(schema_id));
}
#[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()));
}
}
/// This module is required by `cargo pgrx test` invocations.
/// It must be visible at the root of your extension crate.
#[cfg(test)]
pub mod pg_test {
pub fn setup(_options: Vec<&str>) {
// perform one-off initialization when the pg_test framework starts
}
#[must_use]
pub fn postgresql_conf_options() -> Vec<&'static str> {
// return any postgresql.conf settings that are required for your tests
vec![]
}
}
#[cfg(any(test, feature = "pg_test"))]
#[pg_schema]
mod tests {
include!("tests.rs");
}

360
src/tests.rs Normal file
View File

@ -0,0 +1,360 @@
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)
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));
let panic_msg = format!("Assertion Failed (expected success): {}\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 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);
panic!("{}", panic_msg);
}
};
}
// Updated helper macro for asserting failed JSON results with the new flat error structure
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 errors_opt = json_result.get("errors").and_then(Value::as_array);
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
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);
}
match errors_opt {
Some(errors) => {
if errors.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.len(), base_msg, pretty_json);
}
if $expected_error_count > 0 {
let first_error_message = errors[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 has no 'message' string): {}\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 'errors' array, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
};
// Without custom message (calls the one above with ""):
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr) => {
assert_failure_with_json!($result, $expected_error_count, $expected_first_message_contains, "");
};
// --- Arms with error count check only ---
// 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 errors_opt = json_result.get("errors").and_then(Value::as_array);
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
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);
}
match errors_opt {
Some(errors) => {
if errors.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.len(), 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 'errors' array, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
};
// Without custom message (calls the one above with ""):
($result:expr, $expected_error_count:expr) => {
assert_failure_with_json!($result, $expected_error_count, "");
};
// --- Arms checking failure only (expects at least one error) ---
// 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 errors_opt = json_result.get("errors").and_then(Value::as_array);
let base_msg = format!($fmt $(, $($args)*)?);
if success != Some(false) {
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);
}
match errors_opt {
Some(errors) => {
if errors.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);
}
}
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 'errors' array, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
}
}
};
// Without custom message (calls the one above with ""):
($result:expr) => {
assert_failure_with_json!($result, "");
};
}
fn jsonb(val: Value) -> JsonB {
JsonB(val)
}
#[pg_test]
fn test_cache_and_validate_json_schema() {
clear_json_schemas(); // Call clear directly
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.");
// Invalid type
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["errors"].as_array().unwrap();
assert_eq!(errors_type[0]["instance_path"], "/age");
assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
// 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["errors"].as_array().unwrap();
assert_eq!(errors_missing[0]["instance_path"], "");
assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
// 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.");
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
assert_eq!(errors_notfound[0]["schema_path"], ""); // Schema path is empty for this error type
assert_eq!(errors_notfound[0]["instance_path"], ""); // Instance path is empty
}
#[pg_test]
fn test_validate_json_schema_not_cached() {
clear_json_schemas(); // Call clear directly
let instance = json!({ "foo": "bar" });
let result = validate_json_schema("non_existent_schema", jsonb(instance));
// Use the updated macro
assert_failure_with_json!(result, 1, "Schema with id '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
let schema_id = "invalid_schema";
// Schema with an invalid type *value*
let invalid_schema = json!({
"$id": "urn:invalid_schema",
"type": ["invalid_type_value"]
});
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
// Manually check the structure for cache_json_schema failure
let json_result = &cache_result.0;
let success = json_result.get("success").and_then(Value::as_bool);
let error_obj = json_result.get("error").and_then(Value::as_object);
if success != Some(false) {
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): Caching invalid schema should fail.\nResult JSON:\n{}", pretty_json);
}
if error_obj.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 'error' object, but none found): Caching invalid schema should return an error object.\nResult JSON:\n{}", pretty_json);
}
// Check specific fields within the error object
let message = error_obj.unwrap().get("message").and_then(Value::as_str);
// Updated check based on the actual error message seen in the logs
if message.map_or(true, |m| !m.contains("failed validation against its metaschema") || !m.contains("/type/0': value must be one of")) {
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 metaschema validation failure message containing '/type/0' error detail.\nResult JSON:\n{}", pretty_json);
}
}
#[pg_test]
fn test_validate_json_schema_detailed_validation_errors() {
clear_json_schemas(); // Call clear directly
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, // Wrong type
"city": "Supercalifragilisticexpialidocious" // Too long
}
});
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
// Update: Expect 2 errors again, as boon reports both nested errors.
assert_failure_with_json!(result, 2);
}
#[pg_test]
fn test_validate_json_schema_oneof_validation_errors() {
clear_json_schemas(); // Call clear directly
let schema_id = "oneof_schema";
let schema = json!({
"oneOf": [
{ // Option 1: Object with string prop
"type": "object",
"properties": {
"string_prop": { "type": "string", "maxLength": 5 }
},
"required": ["string_prop"]
},
{ // Option 2: Object with number prop
"type": "object",
"properties": {
"number_prop": { "type": "number", "minimum": 10 }
},
"required": ["number_prop"]
}
]
});
let _ = cache_json_schema(schema_id, jsonb(schema));
// --- Test case 1: Fails string maxLength (in branch 0) AND missing number_prop (in branch 1) ---
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
// Expect 2 leaf errors: one for maxLength (branch 0), one for missing prop (branch 1)
// Check the first error message reported by boon (maxLength).
assert_failure_with_json!(result_invalid_string, 2, "length must be <=5", "Validation with invalid string length should have 2 leaf errors");
let _errors_string = result_invalid_string.0["errors"].as_array().unwrap(); // Prefix with _
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
let invalid_number_instance = json!({ "number_prop": 5 });
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
// Expect 2 leaf errors: one for minimum (branch 1), one for missing prop (branch 0)
// Check the first error message reported by boon (missing prop).
assert_failure_with_json!(result_invalid_number, 2, "missing properties 'string_prop'", "Validation with invalid number should have 2 leaf errors");
let _errors_number = result_invalid_number.0["errors"].as_array().unwrap(); // Prefix with _
// --- Test case 3: Fails type check (not object) for both branches ---
// Input: boolean, expected object for both branches
let invalid_bool_instance = json!(true); // Not an object
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
// Expect 2 leaf errors, one "Type" error for each branch
// Check the first error reported by boon (want object).
assert_failure_with_json!(result_invalid_bool, 2, "want object", "Validation with invalid bool should have 2 leaf errors");
let _errors_bool = result_invalid_bool.0["errors"].as_array().unwrap(); // Prefix with _
// --- Test case 4: Fails missing required for both branches ---
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
let invalid_empty_obj = json!({});
let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
// Expect 2 leaf errors: one required error for branch 0, one required error for branch 1
// Check the first error reported by boon (missing string_prop).
assert_failure_with_json!(result_empty_obj, 2, "missing properties 'string_prop'", "Validation with empty object should have 2 leaf errors");
let _errors_empty = result_empty_obj.0["errors"].as_array().unwrap(); // Prefix with _
}
#[pg_test]
fn test_clear_json_schemas() {
clear_json_schemas(); // Call clear directly
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));
// Use the updated macro
assert_failure_with_json!(validate_result, 1, "Schema with id '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 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 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()));
}

View File

@ -1 +1 @@
1.0.11
1.0.14