Compare commits

...

12 Commits

Author SHA1 Message Date
2bcdb8adbb version: 1.0.17 2025-04-21 16:11:31 -04:00
3988308965 branch error filtering 2025-04-21 16:11:12 -04:00
b7f528d1f6 flow 2025-04-16 21:14:07 -04:00
2febb292dc flow update 2025-04-16 20:00:35 -04:00
d1831a28ec flow update 2025-04-16 19:34:09 -04:00
c5834ac544 flow updated 2025-04-16 18:07:41 -04:00
eb25f8489e version: 1.0.16 2025-04-16 14:43:07 -04:00
21937db8de improved compile schema error messages 2025-04-16 14:42:57 -04:00
28b689cac0 version: 1.0.15 2025-04-16 01:00:57 -04:00
cc04a1a8bb made errors consistent 2025-04-16 01:00:51 -04:00
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
6 changed files with 385 additions and 212 deletions

4
.env
View File

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

105
flow
View File

@ -9,7 +9,7 @@ source ./flows/rust
# Vars # Vars
POSTGRES_VERSION="17" POSTGRES_VERSION="17"
POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config" POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
DEPENDENCIES=(cargo git icu4c pkg-config "postgresql@${POSTGRES_VERSION}") DEPENDENCIES+=(icu4c pkg-config "postgresql@${POSTGRES_VERSION}")
CARGO_DEPENDENCIES=(cargo-pgrx==0.14.0) CARGO_DEPENDENCIES=(cargo-pgrx==0.14.0)
GITEA_ORGANIZATION="cellular" GITEA_ORGANIZATION="cellular"
GITEA_REPOSITORY="jspg" GITEA_REPOSITORY="jspg"
@ -20,133 +20,124 @@ env() {
# If not set, try to get it from kubectl # If not set, try to get it from kubectl
GITEA_TOKEN=$(kubectl get secret -n cellular gitea-git -o jsonpath='{.data.token}' | base64 --decode) GITEA_TOKEN=$(kubectl get secret -n cellular gitea-git -o jsonpath='{.data.token}' | base64 --decode)
if [ -z "$GITEA_TOKEN" ]; then if [ -z "$GITEA_TOKEN" ]; then
echo -e "❌ ${RED}GITEA_TOKEN is not set and couldn't be retrieved from kubectl${RESET}" >&2 error "GITEA_TOKEN is not set and couldn't be retrieved from kubectl" >&2
exit 1 return 2
fi fi
export GITEA_TOKEN export GITEA_TOKEN
fi fi
echo -e "💰 ${GREEN}Environment variables set${RESET}" success "Environment variables set"
} }
pgrx-prepare() { pgrx-prepare() {
echo -e "${BLUE}Initializing pgrx...${RESET}" info "Initializing pgrx..."
# Explicitly point to the postgresql@${POSTGRES_VERSION} pg_config, don't rely on 'which' # Explicitly point to the postgresql@${POSTGRES_VERSION} pg_config, don't rely on 'which'
local POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config" local POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
if [ ! -x "$POSTGRES_CONFIG_PATH" ]; then if [ ! -x "$POSTGRES_CONFIG_PATH" ]; then
echo -e "${RED}Error: pg_config not found or not executable at $POSTGRES_CONFIG_PATH.${RESET}" error "pg_config not found or not executable at $POSTGRES_CONFIG_PATH."
echo -e "${YELLOW}Ensure postgresql@${POSTGRES_VERSION} is installed correctly via Homebrew.${RESET}" warning "Ensure postgresql@${POSTGRES_VERSION} is installed correctly via Homebrew."
exit 1 return 2
fi fi
if cargo pgrx init --pg"$POSTGRES_VERSION"="$POSTGRES_CONFIG_PATH"; then if cargo pgrx init --pg"$POSTGRES_VERSION"="$POSTGRES_CONFIG_PATH"; then
echo -e "${GREEN}pgrx initialized successfully.${RESET}" success "pgrx initialized successfully."
else else
echo -e "${RED}Failed to initialize pgrx. Check PostgreSQL development packages are installed and $POSTGRES_CONFIG_PATH is valid.${RESET}" error "Failed to initialize pgrx. Check PostgreSQL development packages are installed and $POSTGRES_CONFIG_PATH is valid."
exit 1 return 2
fi fi
} }
build() { build() {
local version local version
version=$(get-version) || return 1 version=$(get-version) || return $?
local package_dir="./package" local package_dir="./package"
local tarball_name="${GITEA_REPOSITORY}.tar.gz" local tarball_name="${GITEA_REPOSITORY}.tar.gz"
local tarball_path="${package_dir}/${tarball_name}" local tarball_path="${package_dir}/${tarball_name}"
echo -e "📦 Creating source tarball v$version for ${GITEA_REPOSITORY} in $package_dir..." info "Creating source tarball v$version for ${GITEA_REPOSITORY} in $package_dir..."
# Clean previous package dir # Clean previous package dir
rm -rf "${package_dir}" rm -rf "${package_dir}"
mkdir -p "${package_dir}" mkdir -p "${package_dir}"
# Create the source tarball excluding specified patterns # Create the source tarball excluding specified patterns
echo -e " ${CYAN}Creating tarball: ${tarball_path}${RESET}" info "Creating tarball: ${tarball_path}"
if tar --exclude='.git*' --exclude='./target' --exclude='./package' --exclude='./flows' --exclude='./flow' -czf "${tarball_path}" .; then if tar --exclude='.git*' --exclude='./target' --exclude='./package' --exclude='./flows' --exclude='./flow' -czf "${tarball_path}" .; then
echo -e "✨ ${GREEN}Successfully created source tarball: ${tarball_path}${RESET}" success "Successfully created source tarball: ${tarball_path}"
else else
echo -e "❌ ${RED}Failed to create source tarball.${RESET}" >&2 error "Failed to create source tarball."
return 1 return 2
fi fi
} }
install() { install() {
local version local version
version=$(get-version) || return 1 version=$(get-version) || return $? # Propagate error
echo -e "🔧 ${CYAN}Building and installing PGRX extension v$version into local PostgreSQL...${RESET}" info "Building and installing PGRX extension v$version into local PostgreSQL..."
# Run the pgrx install command # Run the pgrx install command
# It implicitly uses --release unless --debug is passed
# It finds pg_config or you can add flags like --pg-config if needed
if ! cargo pgrx install; then if ! cargo pgrx install; then
echo -e "❌ ${RED}cargo pgrx install command failed.${RESET}" >&2 error "cargo pgrx install command failed."
return 1 return 2
fi fi
echo -e "✨ ${GREEN}PGRX extension v$version successfully built and installed.${RESET}" success "PGRX extension v$version successfully built and installed."
# Post-install modification to allow non-superuser usage # Post-install modification to allow non-superuser usage
# Get the installation path dynamically using pg_config
local pg_sharedir local pg_sharedir
pg_sharedir=$("$POSTGRES_CONFIG_PATH" --sharedir) pg_sharedir=$("$POSTGRES_CONFIG_PATH" --sharedir)
if [ -z "$pg_sharedir" ]; then local pg_config_status=$?
echo -e "❌ ${RED}Failed to determine PostgreSQL shared directory using pg_config.${RESET}" >&2 if [ $pg_config_status -ne 0 ] || [ -z "$pg_sharedir" ]; then
return 1 error "Failed to determine PostgreSQL shared directory using pg_config."
return 2
fi fi
local installed_control_path="${pg_sharedir}/extension/jspg.control" local installed_control_path="${pg_sharedir}/extension/jspg.control"
# Modify the control file # Modify the control file
if [ ! -f "$installed_control_path" ]; then if [ ! -f "$installed_control_path" ]; then
echo -e "❌ ${RED}Installed control file not found: '$installed_control_path'${RESET}" >&2 error "Installed control file not found: '$installed_control_path'"
return 1 return 2
fi fi
echo -e "🔧 ${CYAN}Modifying control file for non-superuser access: ${installed_control_path}${RESET}" info "Modifying control file for non-superuser access: ${installed_control_path}"
# Use sed -i '' for macOS compatibility # Use sed -i '' for macOS compatibility
if sed -i '' '/^superuser = false/d' "$installed_control_path" && \ if sed -i '' '/^superuser = false/d' "$installed_control_path" && \
echo 'trusted = true' >> "$installed_control_path"; then echo 'trusted = true' >> "$installed_control_path"; then
echo -e "✨ ${GREEN}Control file modified successfully.${RESET}" success "Control file modified successfully."
else else
echo -e "❌ ${RED}Failed to modify control file: ${installed_control_path}${RESET}" >&2 error "Failed to modify control file: ${installed_control_path}"
return 1 return 2
fi fi
} }
test() { test() {
echo -e "🧪 ${CYAN}Running jspg tests...${RESET}" info "Running jspg tests..."
cargo pgrx test "pg${POSTGRES_VERSION}" "$@" cargo pgrx test "pg${POSTGRES_VERSION}" "$@" || return $?
} }
clean() { clean() {
echo -e "🧹 ${CYAN}Cleaning build artifacts...${RESET}" info "Cleaning build artifacts..."
cargo clean # Use standard cargo clean cargo clean || return $?
} }
jspg-usage() { jspg-usage() {
echo -e " ${CYAN}JSPG Commands:${RESET}" printf "prepare\tCheck OS, Cargo, and PGRX dependencies.\n"
echo -e " prepare Check OS, Cargo, and PGRX dependencies." printf "install\tBuild and install the extension locally (after prepare).\n"
echo -e " install [opts] Run prepare, then build and install the extension locally." printf "reinstall\tClean, build, and install the extension locally (after prepare).\n"
echo -e " reinstall [opts] Run prepare, clean, then build and install the extension locally." printf "test\t\tRun pgrx integration tests.\n"
echo -e " test [opts] Run pgrx integration tests." printf "clean\t\tRemove pgrx build artifacts.\n"
echo -e " clean Remove pgrx build artifacts."
echo -e " build Build release artifacts into ./package/ (called by release)."
echo -e " tag Tag the current version (called by release)."
echo -e " package Upload artifacts from ./package/ (called by release)."
echo -e " release Perform a full release (increments patch, builds, tags, pushes, packages)."
} }
jspg-flow() { jspg-flow() {
case "$1" in case "$1" in
env) env; return 0;; env) env; return $?;;
prepare) base prepare; cargo-prepare; pgrx-prepare; return 0;; prepare) base-flow prepare && cargo-prepare && pgrx-prepare; return $?;;
build) build; return 0;; build) build; return $?;;
install) install; return 0;; install) install; return $?;;
reinstall) clean; install; return 0;; reinstall) clean && install; return $?;;
test) test; return 0;; test) test "${@:2}"; return $?;;
package) env; package; return 0;; clean) clean; return $?;;
release) env; release; return 0;;
clean) clean; return 0;;
*) return 1 ;; *) return 1 ;;
esac esac
} }

2
flows

Submodule flows updated: 9d758d581e...3e3954fb79

View File

@ -48,22 +48,24 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
} }
Err(e) => { Err(e) => {
let error = match &e { let error = match &e {
CompileError::ValidationError { url: _url, src } => { // Prefix url with _ CompileError::ValidationError { url: _url, src } => {
json!({ // Collect leaf errors from the meta-schema validation failure
"message": format!("Schema '{}' failed validation against its metaschema: {}", schema_id, src), let mut error_list = Vec::new();
"schema_path": schema_path, collect_leaf_errors(src, &mut error_list);
"error": format!("{:?}", src), // Return the flat list directly
}) json!(error_list)
} }
_ => { _ => {
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string(); // Prefix error_type with _ // Keep existing handling for other compilation errors
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string();
json!({ json!({
"message": format!("Schema '{}' compilation failed: {}", schema_id, e), "message": format!("Schema '{}' compilation failed: {}", schema_id, e),
"schema_path": schema_path, "schema_path": schema_path,
"error": format!("{:?}", e), "detail": format!("{:?}", e),
}) })
} }
}; };
// Ensure the outer structure remains { success: false, error: ... }
JsonB(json!({ JsonB(json!({
"success": false, "success": false,
"error": error "error": error
@ -89,10 +91,16 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
match cache.schemas.validate(&instance_value, *sch_index) { match cache.schemas.validate(&instance_value, *sch_index) {
Ok(_) => JsonB(json!({ "success": true })), Ok(_) => JsonB(json!({ "success": true })),
Err(validation_error) => { Err(validation_error) => {
let error = format_validation_error(&validation_error); // Collect all leaf errors first
let mut raw_error_list = Vec::new();
collect_leaf_errors(&validation_error, &mut raw_error_list);
// Filter the errors (e.g., deduplicate by instance_path)
let filtered_error_list = filter_boon_errors(raw_error_list);
JsonB(json!({ JsonB(json!({
"success": false, "success": false,
"error": error "error": filtered_error_list // Return the filtered list
})) }))
} }
} }
@ -100,28 +108,51 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
} }
} }
fn format_validation_error(error: &ValidationError) -> Value { // Recursively collects leaf errors into a flat list
let nested_errors: Vec<Value> = error.causes.iter().map(format_validation_error).collect(); fn collect_leaf_errors(error: &ValidationError, errors_list: &mut Vec<Value>) {
if error.causes.is_empty() {
// Use specific message for leaf errors, generic for containers let default_message = format!("{}", error);
let message = if error.causes.is_empty() { let message = if let Some(start_index) = default_message.find("': ") {
let default_message = format!("{}", error); // Use boon's default message for specific errors
// Try to strip the "at '<path>': " prefix
if let Some(start_index) = default_message.find("': ") {
default_message[start_index + 3..].to_string() default_message[start_index + 3..].to_string()
} else { } else {
default_message // Fallback if pattern not found default_message
}
} else {
"Validation failed due to nested errors".to_string() // Generic message for container errors
}; };
json!({ errors_list.push(json!({
"message": message, "message": message,
"schema_path": error.schema_url.to_string(), // Use schema_url directly "schema_path": error.schema_url.to_string(),
"instance_path": error.instance_location.to_string(), "instance_path": error.instance_location.to_string(),
"error": nested_errors // Recursively format nested errors }));
}) } else {
for cause in &error.causes {
collect_leaf_errors(cause, errors_list);
}
}
}
// Filters collected errors, e.g., deduplicating by instance_path
fn filter_boon_errors(raw_errors: Vec<Value>) -> Vec<Value> {
use std::collections::HashMap;
use std::collections::hash_map::Entry;
// Use a HashMap to keep only the first error for each instance_path
let mut unique_errors: HashMap<String, Value> = HashMap::new();
for error_value in raw_errors {
if let Some(instance_path_value) = error_value.get("instance_path") {
if let Some(instance_path_str) = instance_path_value.as_str() {
// Use Entry API to insert only if the key is not present
if let Entry::Vacant(entry) = unique_errors.entry(instance_path_str.to_string()) {
entry.insert(error_value);
}
}
}
// If error doesn't have instance_path or it's not a string, we might ignore it or handle differently.
// For now, we implicitly ignore errors without a valid string instance_path for deduplication.
}
// Collect the unique errors from the map values
unique_errors.into_values().collect()
} }
#[pg_extern(strict, parallel_safe)] #[pg_extern(strict, parallel_safe)]

View File

@ -1,7 +1,8 @@
use crate::*; use crate::*;
use serde_json::{json, Value}; use serde_json::{json, Value};
use pgrx::{JsonB, pg_test};
// Helper macro for asserting success with pretty JSON output on failure // Helper macro for asserting success (no changes needed, but ensure it's present)
macro_rules! assert_success_with_json { macro_rules! assert_success_with_json {
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => { ($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => {
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool); let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
@ -9,39 +10,183 @@ macro_rules! assert_success_with_json {
let base_msg = format!($fmt $(, $($args)*)?); let base_msg = format!($fmt $(, $($args)*)?);
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0) let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $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); let panic_msg = format!("Assertion Failed (expected success): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("{}", panic_msg); // Use the constructed string 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);
} }
}; };
} }
// Helper macro for asserting failure with pretty JSON output on failure // Updated helper macro for asserting failed JSON results with the new flat error structure
macro_rules! assert_failure_with_json { macro_rules! assert_failure_with_json {
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => { // --- Arms with error count and message substring check ---
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool); // With custom message:
if condition_result != Some(false) { ($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 base_msg = format!($fmt $(, $($args)*)?); 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)); if success != Some(false) {
// Construct the full message string first let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
let panic_msg = format!("Assertion Failed (expected failure): {}\nResult JSON:\n{}", base_msg, pretty_json); panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("{}", panic_msg); // Use the constructed string }
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);
}
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);
}
} }
}; };
// 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 error_val_opt = json_result.get("error"); // Changed key
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 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);
}
}
};
// 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 error_val_opt = json_result.get("error"); // Changed key
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 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);
}
}
};
// Without custom message (calls the one above with ""):
($result:expr) => {
assert_failure_with_json!($result, "");
};
} }
fn jsonb(val: Value) -> JsonB { fn jsonb(val: Value) -> JsonB {
JsonB(val) JsonB(val)
} }
fn setup_test() {
clear_json_schemas();
}
#[pg_test] #[pg_test]
fn test_cache_and_validate_json_schema() { fn test_cache_and_validate_json_schema() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id = "my_schema"; let schema_id = "my_schema";
let schema = json!({ let schema = json!({
"type": "object", "type": "object",
@ -61,61 +206,74 @@ fn test_cache_and_validate_json_schema() {
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance)); let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
assert_success_with_json!(valid_result, "Validation of valid instance should succeed."); 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)); 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."); 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
let error_obj_type = invalid_result_type.0.get("error").expect("Expected top-level 'error' object"); assert_eq!(errors_type[0]["instance_path"], "/age");
let causes_age = error_obj_type.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)"); assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
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);
// Missing field
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing)); let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
assert_failure_with_json!(invalid_result_missing, "Validation with missing field should fail."); assert_failure_with_json!(invalid_result_missing, 1, "missing properties 'age'", "Validation with missing field should fail.");
let error_obj_missing = invalid_result_missing.0.get("error").expect("Expected 'error' object for missing field"); let errors_missing = invalid_result_missing.0["error"].as_array().unwrap(); // Check 'error', expect array
let causes_missing = error_obj_missing.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)"); assert_eq!(errors_missing[0]["instance_path"], "");
assert!(!causes_missing.is_empty(), "Expected causes for missing field"); assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
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"));
// Schema not found
let non_existent_id = "non_existent_schema"; let non_existent_id = "non_existent_schema";
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({}))); 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."); assert_failure_with_json!(invalid_schema_result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
let error_obj = invalid_schema_result.0.get("error").expect("Expected top-level 'error' object"); // Check 'error' is an object for 'schema not found'
assert_eq!(error_obj["message"].as_str().expect("Expected message for cleared schema"), "Schema with id 'non_existent_schema' not found in cache"); 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
} }
#[pg_test] #[pg_test]
fn test_validate_json_schema_not_cached() { fn test_validate_json_schema_not_cached() {
setup_test(); clear_json_schemas(); // Call clear directly
let instance = json!({ "foo": "bar" }); let instance = json!({ "foo": "bar" });
let result = validate_json_schema("non_existent_schema", jsonb(instance)); let result = validate_json_schema("non_existent_schema", jsonb(instance));
assert_failure_with_json!(result, "Validation with non-existent schema should fail."); // Use the updated macro, expecting count 1 and specific message (handles object case)
assert_eq!(result.0.get("success"), Some(&Value::Bool(false)), "Expected 'success': false for non-existent schema"); assert_failure_with_json!(result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
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] #[pg_test]
fn test_cache_invalid_json_schema() { fn test_cache_invalid_json_schema() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id = "invalid_schema"; let schema_id = "invalid_schema";
let invalid_schema = json!({ "type": "invalid" }); // Schema with an invalid type *value*
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema)); let invalid_schema = json!({
assert_failure_with_json!(cache_result, "Caching invalid schema should fail."); "$id": "urn:invalid_schema",
"type": ["invalid_type_value"]
});
let error_obj = cache_result.0.get("error").expect("Expected 'error' object for failed cache"); let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
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); // Expect 2 leaf errors because the meta-schema validation fails at the type value
assert!(message.starts_with(expected_message_start), "Compile error message start mismatch: {}", message); // and within the type array itself.
assert_failure_with_json!(
cache_result,
2, // Expect exactly two leaf errors
"value must be one of", // Check message substring (present in both)
"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"));
} }
#[pg_test] #[pg_test]
fn test_validate_json_schema_detailed_validation_errors() { fn test_validate_json_schema_detailed_validation_errors() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id = "detailed_errors"; let schema_id = "detailed_errors";
let schema = json!({ let schema = json!({
"type": "object", "type": "object",
@ -135,42 +293,32 @@ fn test_validate_json_schema_detailed_validation_errors() {
let invalid_instance = json!({ let invalid_instance = json!({
"address": { "address": {
"street": 123, "street": 123, // Wrong type
"city": "Supercalifragilisticexpialidocious" "city": "Supercalifragilisticexpialidocious" // Too long
} }
}); });
let result = validate_json_schema(schema_id, jsonb(invalid_instance)); 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"); // Update: Expect 2 errors again, as boon reports both nested errors.
assert_eq!(error_obj["message"].as_str(), Some("Validation failed due to nested errors")); assert_failure_with_json!(result, 2);
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] #[pg_test]
fn test_validate_json_schema_oneof_validation_errors() { fn test_validate_json_schema_oneof_validation_errors() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id = "oneof_schema"; let schema_id = "oneof_schema";
let schema = json!({ let schema = json!({
"oneOf": [ "oneOf": [
{ { // Option 1: Object with string prop
"type": "object", "type": "object",
"properties": { "properties": {
"string_prop": { "type": "string", "maxLength": 5 } "string_prop": { "type": "string", "maxLength": 5 }
}, },
"required": ["string_prop"] "required": ["string_prop"]
}, },
{ { // Option 2: Object with number prop
"type": "object", "type": "object",
"properties": { "properties": {
"number_prop": { "type": "number", "minimum": 10 } "number_prop": { "type": "number", "minimum": 10 }
@ -182,52 +330,55 @@ fn test_validate_json_schema_oneof_validation_errors() {
let _ = cache_json_schema(schema_id, jsonb(schema)); let _ = cache_json_schema(schema_id, jsonb(schema));
let expected_urn = format!("urn:{}#", schema_id); // --- Test case 1: Fails string maxLength (in branch 0) AND missing number_prop (in branch 1) ---
// --- Test case 1: String length failure ---
let invalid_string_instance = json!({ "string_prop": "toolongstring" }); let invalid_string_instance = json!({ "string_prop": "toolongstring" });
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance)); 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"); // Expect 2 leaf errors. Check count only with the macro.
let error_obj_string = result_invalid_string.0.get("error").expect("Expected error object (string case)"); 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");
// Check the top-level error object directly: Input matches Branch 0 type, fails maxLength validation within it. // --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
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 invalid_number_instance = json!({ "number_prop": 5 });
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance)); 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"); // Expect 2 leaf errors. Check count only with the macro.
let error_obj_number = result_invalid_number.0.get("error").expect("Expected error object (number case)"); 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");
// Check the top-level error object directly: Input matches Branch 1 type, fails minimum validation within it. // --- Test case 3: Fails type check (not object) for both branches ---
assert_eq!(error_obj_number["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (number case)"); // Input: boolean, expected object for both branches
assert_eq!(error_obj_number["instance_path"].as_str(), Some(""), "Incorrect instance_path for number fail (number case)"); let invalid_bool_instance = json!(true); // Not an object
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)); 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"); // Expect only 1 leaf error after filtering, as both original errors have instance_path ""
let error_obj_bool = result_invalid_bool.0.get("error").expect("Expected error object (bool case)"); 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");
// Boon reports the failure for the first branch checked (Branch 0). // --- Test case 4: Fails missing required for both branches ---
assert_eq!(error_obj_bool["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (bool case)"); // Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
// Instance path is empty because the failure is at the root of the object being checked against Branch 0 let invalid_empty_obj = json!({});
assert_eq!(error_obj_bool["instance_path"].as_str(), Some(""), "Incorrect instance_path for bool fail"); let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
let actual_bool_fail_message_0 = error_obj_bool["message"].as_str().expect("Expected string message for branch 0 type fail"); // Expect only 1 leaf error after filtering, as both original errors have instance_path ""
let expected_bool_fail_message_0 = "Validation failed due to nested errors"; assert_failure_with_json!(result_empty_obj, 1);
assert_eq!(actual_bool_fail_message_0, expected_bool_fail_message_0, "Branch 0 type fail message mismatch: '{}'", actual_bool_fail_message_0); // 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");
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);
} }
#[pg_test] #[pg_test]
fn test_clear_json_schemas() { fn test_clear_json_schemas() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id = "schema_to_clear"; let schema_id = "schema_to_clear";
let schema = json!({ "type": "string" }); let schema = json!({ "type": "string" });
cache_json_schema(schema_id, jsonb(schema.clone())); cache_json_schema(schema_id, jsonb(schema.clone()));
@ -242,15 +393,13 @@ fn test_clear_json_schemas() {
let instance = json!("test"); let instance = json!("test");
let validate_result = validate_json_schema(schema_id, jsonb(instance)); let validate_result = validate_json_schema(schema_id, jsonb(instance));
assert_failure_with_json!(validate_result, "Validation should fail after clearing schemas."); // 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.");
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] #[pg_test]
fn test_show_json_schemas() { fn test_show_json_schemas() {
setup_test(); clear_json_schemas(); // Call clear directly
let schema_id1 = "schema1"; let schema_id1 = "schema1";
let schema_id2 = "schema2"; let schema_id2 = "schema2";
let schema = json!({ "type": "boolean" }); let schema = json!({ "type": "boolean" });
@ -258,7 +407,9 @@ fn test_show_json_schemas() {
cache_json_schema(schema_id1, jsonb(schema.clone())); cache_json_schema(schema_id1, jsonb(schema.clone()));
cache_json_schema(schema_id2, jsonb(schema.clone())); cache_json_schema(schema_id2, jsonb(schema.clone()));
let result = show_json_schemas(); let mut result = show_json_schemas(); // Make result mutable
assert!(result.contains(&schema_id1.to_string())); 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())); assert!(result.contains(&schema_id2.to_string()));
} }

View File

@ -1 +1 @@
1.0.13 1.0.17