Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c734983a59 | |||
| 9b11f661bc | |||
| f3a733626e | |||
| 2bcdb8adbb | |||
| 3988308965 | |||
| b7f528d1f6 | |||
| 2febb292dc | |||
| d1831a28ec | |||
| c5834ac544 | |||
| eb25f8489e | |||
| 21937db8de | |||
| 28b689cac0 | |||
| cc04a1a8bb |
4
.env
4
.env
@ -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
|
||||||
|
|||||||
106
flow
106
flow
@ -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,125 @@ 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) 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;;
|
release) env; release; return $?;;
|
||||||
clean) clean; return 0;;
|
|
||||||
*) return 1 ;;
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|||||||
2
flows
2
flows
Submodule flows updated: 9d758d581e...3e3954fb79
78
src/lib.rs
78
src/lib.rs
@ -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
|
||||||
@ -80,20 +82,26 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
match cache.id_to_index.get(schema_id) {
|
match cache.id_to_index.get(schema_id) {
|
||||||
None => JsonB(json!({
|
None => JsonB(json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"errors": [json!({
|
"error": {
|
||||||
"message": format!("Schema with id '{}' not found in cache", schema_id),
|
"message": format!("Schema with id '{}' not found in cache", schema_id)
|
||||||
"schema_path": "",
|
}
|
||||||
"instance_path": ""
|
|
||||||
})]
|
|
||||||
})),
|
})),
|
||||||
Some(sch_index) => {
|
Some(sch_index) => {
|
||||||
let instance_value: Value = instance.0;
|
let instance_value: Value = instance.0;
|
||||||
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) => {
|
||||||
// Directly use the result of format_validation_error
|
// Collect all leaf errors first
|
||||||
// which now includes the top-level success indicator and flat error list
|
let mut raw_error_list = Vec::new();
|
||||||
JsonB(format_validation_error(&validation_error))
|
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!({
|
||||||
|
"success": false,
|
||||||
|
"error": filtered_error_list // Return the filtered list
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -111,26 +119,40 @@ fn collect_leaf_errors(error: &ValidationError, errors_list: &mut Vec<Value>) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
errors_list.push(json!({
|
errors_list.push(json!({
|
||||||
"message": message,
|
"message": message,
|
||||||
"schema_path": error.schema_url.to_string(),
|
"schema_path": error.schema_url.to_string(),
|
||||||
"instance_path": error.instance_location.to_string(),
|
"instance_path": error.instance_location.to_string(),
|
||||||
}));
|
}));
|
||||||
} else {
|
} else {
|
||||||
for cause in &error.causes {
|
for cause in &error.causes {
|
||||||
collect_leaf_errors(cause, errors_list);
|
collect_leaf_errors(cause, errors_list);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formats validation errors into a flat list JSON structure
|
// Filters collected errors, e.g., deduplicating by instance_path
|
||||||
fn format_validation_error(error: &ValidationError) -> Value {
|
fn filter_boon_errors(raw_errors: Vec<Value>) -> Vec<Value> {
|
||||||
let mut all_errors = Vec::new();
|
use std::collections::HashMap;
|
||||||
collect_leaf_errors(error, &mut all_errors);
|
use std::collections::hash_map::Entry;
|
||||||
|
|
||||||
json!({
|
// Use a HashMap to keep only the first error for each instance_path
|
||||||
"success": false,
|
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
||||||
"errors": all_errors // Flat list of specific errors
|
|
||||||
})
|
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)]
|
||||||
|
|||||||
203
src/tests.rs
203
src/tests.rs
@ -33,38 +33,63 @@ macro_rules! assert_failure_with_json {
|
|||||||
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||||
let json_result = &$result.0;
|
let json_result = &$result.0;
|
||||||
let success = json_result.get("success").and_then(Value::as_bool);
|
let success = json_result.get("success").and_then(Value::as_bool);
|
||||||
let errors_opt = json_result.get("errors").and_then(Value::as_array);
|
let error_val_opt = json_result.get("error"); // Changed key
|
||||||
let base_msg = format!($fmt $(, $($args)*)?);
|
let base_msg = format!($fmt $(, $($args)*)?);
|
||||||
|
|
||||||
if success != Some(false) {
|
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));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
match errors_opt {
|
match error_val_opt {
|
||||||
Some(errors) => {
|
Some(error_val) => {
|
||||||
if errors.len() != $expected_error_count {
|
if error_val.is_array() {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let errors_array = error_val.as_array().unwrap();
|
||||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors.len(), base_msg, pretty_json);
|
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));
|
||||||
if $expected_error_count > 0 {
|
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
||||||
let first_error_message = errors[0].get("message").and_then(Value::as_str);
|
}
|
||||||
match first_error_message {
|
if $expected_error_count > 0 {
|
||||||
Some(msg) => {
|
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
|
||||||
if !msg.contains($expected_first_message_contains) {
|
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));
|
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);
|
panic!("Assertion Failed (first error in array 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 (first error 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 => {
|
None => {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
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);
|
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -78,23 +103,35 @@ macro_rules! assert_failure_with_json {
|
|||||||
($result:expr, $expected_error_count:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
($result:expr, $expected_error_count:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||||
let json_result = &$result.0;
|
let json_result = &$result.0;
|
||||||
let success = json_result.get("success").and_then(Value::as_bool);
|
let success = json_result.get("success").and_then(Value::as_bool);
|
||||||
let errors_opt = json_result.get("errors").and_then(Value::as_array);
|
let error_val_opt = json_result.get("error"); // Changed key
|
||||||
let base_msg = format!($fmt $(, $($args)*)?);
|
let base_msg = format!($fmt $(, $($args)*)?);
|
||||||
|
|
||||||
if success != Some(false) {
|
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));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
match errors_opt {
|
match error_val_opt {
|
||||||
Some(errors) => {
|
Some(error_val) => {
|
||||||
if errors.len() != $expected_error_count {
|
if error_val.is_array() {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let errors_array = error_val.as_array().unwrap();
|
||||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors.len(), base_msg, pretty_json);
|
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 => {
|
None => {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
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);
|
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -108,23 +145,31 @@ macro_rules! assert_failure_with_json {
|
|||||||
($result:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
($result:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||||
let json_result = &$result.0;
|
let json_result = &$result.0;
|
||||||
let success = json_result.get("success").and_then(Value::as_bool);
|
let success = json_result.get("success").and_then(Value::as_bool);
|
||||||
let errors_opt = json_result.get("errors").and_then(Value::as_array);
|
let error_val_opt = json_result.get("error"); // Changed key
|
||||||
let base_msg = format!($fmt $(, $($args)*)?);
|
let base_msg = format!($fmt $(, $($args)*)?);
|
||||||
|
|
||||||
if success != Some(false) {
|
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));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
match errors_opt {
|
match error_val_opt {
|
||||||
Some(errors) => {
|
Some(error_val) => {
|
||||||
if errors.is_empty() {
|
if error_val.is_object() {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
// OK: single error object is a failure
|
||||||
panic!("Assertion Failed (expected errors, but errors array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
} 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 => {
|
None => {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
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);
|
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -164,14 +209,14 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
// Invalid type
|
// 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, 1, "must be >=0", "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["errors"].as_array().unwrap();
|
let errors_type = invalid_result_type.0["error"].as_array().unwrap(); // Check 'error', expect array
|
||||||
assert_eq!(errors_type[0]["instance_path"], "/age");
|
assert_eq!(errors_type[0]["instance_path"], "/age");
|
||||||
assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
|
assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
|
||||||
|
|
||||||
// Missing field
|
// 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, 1, "missing properties 'age'", "Validation with missing field should fail.");
|
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();
|
let errors_missing = invalid_result_missing.0["error"].as_array().unwrap(); // Check 'error', expect array
|
||||||
assert_eq!(errors_missing[0]["instance_path"], "");
|
assert_eq!(errors_missing[0]["instance_path"], "");
|
||||||
assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
|
assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
|
||||||
|
|
||||||
@ -179,9 +224,10 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
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, 1, "Schema with id 'non_existent_schema' not found", "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 errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
|
// Check 'error' is an object for 'schema not found'
|
||||||
assert_eq!(errors_notfound[0]["schema_path"], ""); // Schema path is empty for this error type
|
let error_notfound_obj = invalid_schema_result.0["error"].as_object().expect("'error' should be an object for schema not found");
|
||||||
assert_eq!(errors_notfound[0]["instance_path"], ""); // Instance path is empty
|
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]
|
||||||
@ -189,7 +235,7 @@ fn test_validate_json_schema_not_cached() {
|
|||||||
clear_json_schemas(); // Call clear directly
|
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));
|
||||||
// Use the updated macro
|
// Use the updated macro, expecting count 1 and specific message (handles object case)
|
||||||
assert_failure_with_json!(result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
assert_failure_with_json!(result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -205,26 +251,24 @@ fn test_cache_invalid_json_schema() {
|
|||||||
|
|
||||||
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
|
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
|
||||||
|
|
||||||
// Manually check the structure for cache_json_schema failure
|
// Expect 2 leaf errors because the meta-schema validation fails at the type value
|
||||||
let json_result = &cache_result.0;
|
// and within the type array itself.
|
||||||
let success = json_result.get("success").and_then(Value::as_bool);
|
assert_failure_with_json!(
|
||||||
let error_obj = json_result.get("error").and_then(Value::as_object);
|
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."
|
||||||
|
);
|
||||||
|
|
||||||
if success != Some(false) {
|
// Ensure the error is an array and check specifics
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let error_array = cache_result.0["error"].as_array().expect("Error field should be an array");
|
||||||
panic!("Assertion Failed (expected failure, success was not false): Caching invalid schema should fail.\nResult JSON:\n{}", pretty_json);
|
assert_eq!(error_array.len(), 2);
|
||||||
}
|
// Note: Order might vary depending on boon's internal processing, check both possibilities or sort.
|
||||||
if error_obj.is_none() {
|
// Assuming the order shown in the logs for now:
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
assert_eq!(error_array[0]["instance_path"], "/type");
|
||||||
panic!("Assertion Failed (expected 'error' object, but none found): Caching invalid schema should return an error object.\nResult JSON:\n{}", pretty_json);
|
assert!(error_array[0]["message"].as_str().unwrap().contains("value must be one of"));
|
||||||
}
|
assert_eq!(error_array[1]["instance_path"], "/type/0");
|
||||||
// Check specific fields within the error object
|
assert!(error_array[1]["message"].as_str().unwrap().contains("value must be one of"));
|
||||||
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]
|
#[pg_test]
|
||||||
@ -289,36 +333,47 @@ fn test_validate_json_schema_oneof_validation_errors() {
|
|||||||
// --- Test case 1: Fails string maxLength (in branch 0) AND missing number_prop (in branch 1) ---
|
// --- 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 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));
|
||||||
// Expect 2 leaf errors: one for maxLength (branch 0), one for missing prop (branch 1)
|
// Expect 2 leaf errors. Check count only with the macro.
|
||||||
// Check the first error message reported by boon (maxLength).
|
assert_failure_with_json!(result_invalid_string, 2);
|
||||||
assert_failure_with_json!(result_invalid_string, 2, "length must be <=5", "Validation with invalid string length should have 2 leaf errors");
|
// Explicitly check that both expected errors are present, ignoring order
|
||||||
let _errors_string = result_invalid_string.0["errors"].as_array().unwrap(); // Prefix with _
|
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");
|
||||||
|
|
||||||
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
|
// --- 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 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));
|
||||||
// Expect 2 leaf errors: one for minimum (branch 1), one for missing prop (branch 0)
|
// Expect 2 leaf errors. Check count only with the macro.
|
||||||
// Check the first error message reported by boon (missing prop).
|
assert_failure_with_json!(result_invalid_number, 2);
|
||||||
assert_failure_with_json!(result_invalid_number, 2, "missing properties 'string_prop'", "Validation with invalid number should have 2 leaf errors");
|
// Explicitly check that both expected errors are present, ignoring order
|
||||||
let _errors_number = result_invalid_number.0["errors"].as_array().unwrap(); // Prefix with _
|
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");
|
||||||
|
|
||||||
// --- Test case 3: Fails type check (not object) for both branches ---
|
// --- Test case 3: Fails type check (not object) for both branches ---
|
||||||
// Input: boolean, expected object for both branches
|
// Input: boolean, expected object for both branches
|
||||||
let invalid_bool_instance = json!(true); // Not an object
|
let invalid_bool_instance = json!(true); // Not an object
|
||||||
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));
|
||||||
// Expect 2 leaf errors, one "Type" error for each branch
|
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
|
||||||
// Check the first error reported by boon (want object).
|
assert_failure_with_json!(result_invalid_bool, 1);
|
||||||
assert_failure_with_json!(result_invalid_bool, 2, "want object", "Validation with invalid bool should have 2 leaf errors");
|
// Explicitly check that the single remaining error is the type error for the root instance path
|
||||||
let _errors_bool = result_invalid_bool.0["errors"].as_array().unwrap(); // Prefix with _
|
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");
|
||||||
|
|
||||||
// --- Test case 4: Fails missing required for both branches ---
|
// --- Test case 4: Fails missing required for both branches ---
|
||||||
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
|
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
|
||||||
let invalid_empty_obj = json!({});
|
let invalid_empty_obj = json!({});
|
||||||
let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
|
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
|
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
|
||||||
// Check the first error reported by boon (missing string_prop).
|
assert_failure_with_json!(result_empty_obj, 1);
|
||||||
assert_failure_with_json!(result_empty_obj, 2, "missing properties 'string_prop'", "Validation with empty object should have 2 leaf errors");
|
// Explicitly check that the single remaining error is one of the expected missing properties errors
|
||||||
let _errors_empty = result_empty_obj.0["errors"].as_array().unwrap(); // Prefix with _
|
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]
|
||||||
@ -338,7 +393,7 @@ 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));
|
||||||
// Use the updated macro
|
// Use the updated macro, expecting count 1 and specific message (handles object case)
|
||||||
assert_failure_with_json!(validate_result, 1, "Schema with id 'schema_to_clear' not found", "Validation should fail after clearing schemas.");
|
assert_failure_with_json!(validate_result, 1, "Schema with id 'schema_to_clear' not found", "Validation should fail after clearing schemas.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user