| 1 | use crate::{paths::Location, ValidationError}; |
| 2 | use ahash::AHashMap; |
| 3 | use referencing::Uri; |
| 4 | use serde::{ |
| 5 | ser::{SerializeMap, SerializeSeq, SerializeStruct}, |
| 6 | Serialize, |
| 7 | }; |
| 8 | use std::{fmt, sync::Arc}; |
| 9 | |
| 10 | /// Annotations associated with an output unit. |
| 11 | #[derive(Debug, Clone, PartialEq)] |
| 12 | pub struct Annotations(Arc<serde_json::Value>); |
| 13 | |
| 14 | impl Annotations { |
| 15 | /// Create a new `Annotations` instance. |
| 16 | #[must_use] |
| 17 | pub(crate) fn new(v: serde_json::Value) -> Self { |
| 18 | Annotations(Arc::new(v)) |
| 19 | } |
| 20 | |
| 21 | /// Create a new `Annotations` instance from an Arc. |
| 22 | #[must_use] |
| 23 | pub(crate) fn from_arc(v: Arc<serde_json::Value>) -> Self { |
| 24 | Annotations(v) |
| 25 | } |
| 26 | |
| 27 | /// Returns the inner [`serde_json::Value`] of the annotation. |
| 28 | #[inline] |
| 29 | #[must_use] |
| 30 | pub fn into_inner(self) -> serde_json::Value { |
| 31 | Arc::try_unwrap(self.0).unwrap_or_else(|arc| (*arc).clone()) |
| 32 | } |
| 33 | |
| 34 | /// The `serde_json::Value` of the annotation. |
| 35 | #[must_use] |
| 36 | pub fn value(&self) -> &serde_json::Value { |
| 37 | &self.0 |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl serde::Serialize for Annotations { |
| 42 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 43 | where |
| 44 | S: serde::Serializer, |
| 45 | { |
| 46 | self.0.serialize(serializer) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Description of a validation error used within evaluation outputs. |
| 51 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 52 | pub struct ErrorDescription { |
| 53 | keyword: &'static str, |
| 54 | message: String, |
| 55 | } |
| 56 | |
| 57 | impl ErrorDescription { |
| 58 | #[inline] |
| 59 | #[must_use] |
| 60 | pub(crate) fn new(keyword: &'static str, message: String) -> Self { |
| 61 | Self { keyword, message } |
| 62 | } |
| 63 | |
| 64 | /// Create an `ErrorDescription` from a `ValidationError`. |
| 65 | #[inline] |
| 66 | #[must_use] |
| 67 | pub(crate) fn from_validation_error(e: &ValidationError<'_>) -> Self { |
| 68 | ErrorDescription { |
| 69 | keyword: e.kind().keyword(), |
| 70 | message: e.to_string(), |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Returns the keyword associated with this error. |
| 75 | #[inline] |
| 76 | #[must_use] |
| 77 | pub fn keyword(&self) -> &'static str { |
| 78 | self.keyword |
| 79 | } |
| 80 | |
| 81 | /// Returns the inner [`String`] of the error description. |
| 82 | #[inline] |
| 83 | #[must_use] |
| 84 | pub fn into_inner(self) -> String { |
| 85 | self.message |
| 86 | } |
| 87 | |
| 88 | /// Returns the message of the error description. |
| 89 | #[inline] |
| 90 | #[must_use] |
| 91 | pub fn message(&self) -> &str { |
| 92 | &self.message |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl fmt::Display for ErrorDescription { |
| 97 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 98 | f.write_str(&self.message) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, PartialEq)] |
| 103 | pub(crate) struct EvaluationNode { |
| 104 | pub(crate) keyword_location: Location, |
| 105 | pub(crate) absolute_keyword_location: Option<Arc<Uri<String>>>, |
| 106 | pub(crate) schema_location: Arc<str>, |
| 107 | pub(crate) instance_location: Location, |
| 108 | pub(crate) valid: bool, |
| 109 | pub(crate) annotations: Option<Annotations>, |
| 110 | pub(crate) dropped_annotations: Option<Annotations>, |
| 111 | pub(crate) errors: Vec<ErrorDescription>, |
| 112 | pub(crate) children: Vec<EvaluationNode>, |
| 113 | } |
| 114 | |
| 115 | impl EvaluationNode { |
| 116 | pub(crate) fn valid( |
| 117 | keyword_location: Location, |
| 118 | absolute_keyword_location: Option<Arc<Uri<String>>>, |
| 119 | schema_location: impl Into<Arc<str>>, |
| 120 | instance_location: Location, |
| 121 | annotations: Option<Annotations>, |
| 122 | children: Vec<EvaluationNode>, |
| 123 | ) -> Self { |
| 124 | let schema_location = schema_location.into(); |
| 125 | EvaluationNode { |
| 126 | keyword_location, |
| 127 | absolute_keyword_location, |
| 128 | schema_location, |
| 129 | instance_location, |
| 130 | valid: true, |
| 131 | annotations, |
| 132 | dropped_annotations: None, |
| 133 | errors: Vec::new(), |
| 134 | children, |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub(crate) fn invalid( |
| 139 | keyword_location: Location, |
| 140 | absolute_keyword_location: Option<Arc<Uri<String>>>, |
| 141 | schema_location: impl Into<Arc<str>>, |
| 142 | instance_location: Location, |
| 143 | annotations: Option<Annotations>, |
| 144 | errors: Vec<ErrorDescription>, |
| 145 | children: Vec<EvaluationNode>, |
| 146 | ) -> Self { |
| 147 | let schema_location = schema_location.into(); |
| 148 | EvaluationNode { |
| 149 | keyword_location, |
| 150 | absolute_keyword_location, |
| 151 | schema_location, |
| 152 | instance_location, |
| 153 | valid: false, |
| 154 | annotations: None, |
| 155 | dropped_annotations: annotations, |
| 156 | errors, |
| 157 | children, |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Result of evaluating a JSON instance against a schema. |
| 163 | /// |
| 164 | /// This type provides access to structured output formats as defined in the |
| 165 | /// [JSON Schema specification](https://json-schema.org/draft/2020-12/json-schema-core#name-output-structure). |
| 166 | /// |
| 167 | /// # Output Formats |
| 168 | /// |
| 169 | /// The evaluation result can be accessed in three standard formats: |
| 170 | /// |
| 171 | /// - **Flag**: Simple boolean validity indicator via [`flag()`](Self::flag) |
| 172 | /// - **List**: Flat list of all evaluation units via [`list()`](Self::list) |
| 173 | /// - **Hierarchical**: Nested tree structure via [`hierarchical()`](Self::hierarchical) |
| 174 | /// |
| 175 | /// All formats are serializable to JSON using `serde_json`. |
| 176 | /// |
| 177 | /// # Examples |
| 178 | /// |
| 179 | /// ```rust |
| 180 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 181 | /// use serde_json::json; |
| 182 | /// |
| 183 | /// let schema = json!({"type": "string", "minLength": 3}); |
| 184 | /// let validator = jsonschema::validator_for(&schema)?; |
| 185 | /// |
| 186 | /// // Evaluate an instance |
| 187 | /// let instance = json!("ab"); |
| 188 | /// let evaluation = validator.evaluate(&instance); |
| 189 | /// |
| 190 | /// // Check validity with flag format |
| 191 | /// let flag = evaluation.flag(); |
| 192 | /// assert!(!flag.valid); |
| 193 | /// |
| 194 | /// // Get structured output as JSON |
| 195 | /// let list_output = serde_json::to_value(evaluation.list())?; |
| 196 | /// println!("{}", serde_json::to_string_pretty(&list_output)?); |
| 197 | /// |
| 198 | /// // Iterate over errors |
| 199 | /// for error in evaluation.iter_errors() { |
| 200 | /// println!("Error at {}: {}", error.instance_location, error.error); |
| 201 | /// } |
| 202 | /// # Ok(()) |
| 203 | /// # } |
| 204 | /// ``` |
| 205 | #[derive(Debug)] |
| 206 | pub struct Evaluation { |
| 207 | root: EvaluationNode, |
| 208 | } |
| 209 | |
| 210 | impl Evaluation { |
| 211 | pub(crate) fn new(root: EvaluationNode) -> Self { |
| 212 | Evaluation { root } |
| 213 | } |
| 214 | /// Returns the flag output format. |
| 215 | /// |
| 216 | /// This is the simplest output format, containing only a boolean indicating |
| 217 | /// whether the instance is valid according to the schema. |
| 218 | /// |
| 219 | /// # Examples |
| 220 | /// |
| 221 | /// ```rust |
| 222 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 223 | /// use serde_json::json; |
| 224 | /// |
| 225 | /// let schema = json!({"type": "number"}); |
| 226 | /// let validator = jsonschema::validator_for(&schema)?; |
| 227 | /// |
| 228 | /// let evaluation = validator.evaluate(&json!(42)); |
| 229 | /// let flag = evaluation.flag(); |
| 230 | /// assert!(flag.valid); |
| 231 | /// |
| 232 | /// let evaluation = validator.evaluate(&json!("not a number")); |
| 233 | /// let flag = evaluation.flag(); |
| 234 | /// assert!(!flag.valid); |
| 235 | /// # Ok(()) |
| 236 | /// # } |
| 237 | /// ``` |
| 238 | #[must_use] |
| 239 | pub fn flag(&self) -> FlagOutput { |
| 240 | FlagOutput { |
| 241 | valid: self.root.valid, |
| 242 | } |
| 243 | } |
| 244 | /// Returns the list output format. |
| 245 | /// |
| 246 | /// This format provides a flat list of all evaluation units, where each unit |
| 247 | /// contains information about a specific validation step including its location, |
| 248 | /// validity, annotations, and errors. |
| 249 | /// |
| 250 | /// # Examples |
| 251 | /// |
| 252 | /// ```rust |
| 253 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 254 | /// use serde_json::json; |
| 255 | /// |
| 256 | /// let schema = json!({ |
| 257 | /// "type": "array", |
| 258 | /// "prefixItems": [{"type": "string"}], |
| 259 | /// "items": {"type": "integer"} |
| 260 | /// }); |
| 261 | /// let validator = jsonschema::validator_for(&schema)?; |
| 262 | /// let evaluation = validator.evaluate(&json!(["hello", "oops"])); |
| 263 | /// |
| 264 | /// assert_eq!( |
| 265 | /// serde_json::to_value(evaluation.list())?, |
| 266 | /// json!({ |
| 267 | /// "valid": false, |
| 268 | /// "details": [ |
| 269 | /// {"evaluationPath": "", "instanceLocation": "", "schemaLocation": "", "valid": false}, |
| 270 | /// { |
| 271 | /// "valid": false, |
| 272 | /// "evaluationPath": "/items", |
| 273 | /// "instanceLocation": "", |
| 274 | /// "schemaLocation": "/items", |
| 275 | /// "droppedAnnotations": true |
| 276 | /// }, |
| 277 | /// { |
| 278 | /// "valid": false, |
| 279 | /// "evaluationPath": "/items", |
| 280 | /// "instanceLocation": "/1", |
| 281 | /// "schemaLocation": "/items" |
| 282 | /// }, |
| 283 | /// { |
| 284 | /// "valid": false, |
| 285 | /// "evaluationPath": "/items/type", |
| 286 | /// "instanceLocation": "/1", |
| 287 | /// "schemaLocation": "/items/type", |
| 288 | /// "errors": {"type": "\"oops\" is not of type \"integer\""} |
| 289 | /// }, |
| 290 | /// { |
| 291 | /// "valid": true, |
| 292 | /// "evaluationPath": "/prefixItems", |
| 293 | /// "instanceLocation": "", |
| 294 | /// "schemaLocation": "/prefixItems", |
| 295 | /// "annotations": 0 |
| 296 | /// }, |
| 297 | /// { |
| 298 | /// "valid": true, |
| 299 | /// "evaluationPath": "/prefixItems/0", |
| 300 | /// "instanceLocation": "/0", |
| 301 | /// "schemaLocation": "/prefixItems/0" |
| 302 | /// }, |
| 303 | /// { |
| 304 | /// "valid": true, |
| 305 | /// "evaluationPath": "/prefixItems/0/type", |
| 306 | /// "instanceLocation": "/0", |
| 307 | /// "schemaLocation": "/prefixItems/0/type" |
| 308 | /// }, |
| 309 | /// { |
| 310 | /// "valid": true, |
| 311 | /// "evaluationPath": "/type", |
| 312 | /// "instanceLocation": "", |
| 313 | /// "schemaLocation": "/type" |
| 314 | /// } |
| 315 | /// ] |
| 316 | /// }) |
| 317 | /// ); |
| 318 | /// # Ok(()) |
| 319 | /// # } |
| 320 | /// ``` |
| 321 | #[must_use] |
| 322 | pub fn list(&self) -> ListOutput<'_> { |
| 323 | ListOutput { root: &self.root } |
| 324 | } |
| 325 | /// Returns the hierarchical output format. |
| 326 | /// |
| 327 | /// This format represents the evaluation as a tree structure that mirrors the |
| 328 | /// schema's logical structure. Each node contains its validation result along |
| 329 | /// with nested child nodes representing sub-schema evaluations. |
| 330 | /// |
| 331 | /// # Examples |
| 332 | /// |
| 333 | /// ```rust |
| 334 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 335 | /// use serde_json::json; |
| 336 | /// |
| 337 | /// let schema = json!({ |
| 338 | /// "type": "array", |
| 339 | /// "prefixItems": [{"type": "string"}], |
| 340 | /// "items": {"type": "integer"} |
| 341 | /// }); |
| 342 | /// let validator = jsonschema::validator_for(&schema)?; |
| 343 | /// let evaluation = validator.evaluate(&json!(["hello", "oops"])); |
| 344 | /// |
| 345 | /// assert_eq!( |
| 346 | /// serde_json::to_value(evaluation.hierarchical())?, |
| 347 | /// json!({ |
| 348 | /// "valid": false, |
| 349 | /// "evaluationPath": "", |
| 350 | /// "schemaLocation": "", |
| 351 | /// "instanceLocation": "", |
| 352 | /// "details": [ |
| 353 | /// { |
| 354 | /// "valid": false, |
| 355 | /// "evaluationPath": "/items", |
| 356 | /// "instanceLocation": "", |
| 357 | /// "schemaLocation": "/items", |
| 358 | /// "droppedAnnotations": true, |
| 359 | /// "details": [ |
| 360 | /// { |
| 361 | /// "valid": false, |
| 362 | /// "evaluationPath": "/items", |
| 363 | /// "instanceLocation": "/1", |
| 364 | /// "schemaLocation": "/items", |
| 365 | /// "details": [ |
| 366 | /// { |
| 367 | /// "valid": false, |
| 368 | /// "evaluationPath": "/items/type", |
| 369 | /// "instanceLocation": "/1", |
| 370 | /// "schemaLocation": "/items/type", |
| 371 | /// "errors": {"type": "\"oops\" is not of type \"integer\""} |
| 372 | /// } |
| 373 | /// ] |
| 374 | /// } |
| 375 | /// ] |
| 376 | /// }, |
| 377 | /// { |
| 378 | /// "valid": true, |
| 379 | /// "evaluationPath": "/prefixItems", |
| 380 | /// "instanceLocation": "", |
| 381 | /// "schemaLocation": "/prefixItems", |
| 382 | /// "annotations": 0, |
| 383 | /// "details": [ |
| 384 | /// { |
| 385 | /// "valid": true, |
| 386 | /// "evaluationPath": "/prefixItems/0", |
| 387 | /// "instanceLocation": "/0", |
| 388 | /// "schemaLocation": "/prefixItems/0", |
| 389 | /// "details": [ |
| 390 | /// { |
| 391 | /// "valid": true, |
| 392 | /// "evaluationPath": "/prefixItems/0/type", |
| 393 | /// "instanceLocation": "/0", |
| 394 | /// "schemaLocation": "/prefixItems/0/type" |
| 395 | /// } |
| 396 | /// ] |
| 397 | /// } |
| 398 | /// ] |
| 399 | /// }, |
| 400 | /// { |
| 401 | /// "valid": true, |
| 402 | /// "evaluationPath": "/type", |
| 403 | /// "instanceLocation": "", |
| 404 | /// "schemaLocation": "/type" |
| 405 | /// } |
| 406 | /// ] |
| 407 | /// }) |
| 408 | /// ); |
| 409 | /// # Ok(()) |
| 410 | /// # } |
| 411 | /// ``` |
| 412 | #[must_use] |
| 413 | pub fn hierarchical(&self) -> HierarchicalOutput<'_> { |
| 414 | HierarchicalOutput { root: &self.root } |
| 415 | } |
| 416 | /// Returns an iterator over all annotations produced during evaluation. |
| 417 | /// |
| 418 | /// Annotations are metadata emitted by keywords during successful validation. |
| 419 | /// They can be used to collect information about which parts of a schema |
| 420 | /// matched the instance. |
| 421 | /// |
| 422 | /// # Examples |
| 423 | /// |
| 424 | /// ```rust |
| 425 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 426 | /// use serde_json::json; |
| 427 | /// |
| 428 | /// let schema = json!({ |
| 429 | /// "type": "object", |
| 430 | /// "properties": {"name": {"type": "string"}, "age": {"type": "number", "minimum": 0}}, |
| 431 | /// "required": ["name"] |
| 432 | /// }); |
| 433 | /// let validator = jsonschema::validator_for(&schema)?; |
| 434 | /// let evaluation = validator.evaluate(&json!({"name": "Alice", "age": 30})); |
| 435 | /// |
| 436 | /// let entries: Vec<_> = evaluation.iter_annotations().collect(); |
| 437 | /// assert_eq!(entries.len(), 1); |
| 438 | /// assert_eq!(entries[0].schema_location, "/properties"); |
| 439 | /// assert_eq!(entries[0].instance_location.as_str(), ""); |
| 440 | /// assert_eq!(entries[0].annotations.value(), &json!(["age", "name"])); |
| 441 | /// # Ok(()) |
| 442 | /// # } |
| 443 | /// ``` |
| 444 | #[must_use] |
| 445 | pub fn iter_annotations(&self) -> AnnotationIter<'_> { |
| 446 | AnnotationIter::new(&self.root) |
| 447 | } |
| 448 | /// Returns an iterator over all errors produced during evaluation. |
| 449 | /// |
| 450 | /// Each error entry contains information about a validation failure, |
| 451 | /// including its location in both the schema and instance. |
| 452 | /// |
| 453 | /// # Examples |
| 454 | /// |
| 455 | /// ```rust |
| 456 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 457 | /// use serde_json::json; |
| 458 | /// |
| 459 | /// let schema = json!({ |
| 460 | /// "type": "object", |
| 461 | /// "required": ["name"], |
| 462 | /// "properties": { |
| 463 | /// "age": {"type": "number"} |
| 464 | /// } |
| 465 | /// }); |
| 466 | /// let validator = jsonschema::validator_for(&schema)?; |
| 467 | /// let evaluation = validator.evaluate(&json!({"name": "Bob", "age": "oops"})); |
| 468 | /// |
| 469 | /// let errors: Vec<_> = evaluation.iter_errors().collect(); |
| 470 | /// assert_eq!(errors.len(), 1); |
| 471 | /// assert_eq!(errors[0].schema_location, "/properties/age/type"); |
| 472 | /// assert_eq!(errors[0].instance_location.as_str(), "/age"); |
| 473 | /// assert_eq!(errors[0].error.to_string(), "\"oops\" is not of type \"number\""); |
| 474 | /// # Ok(()) |
| 475 | /// # } |
| 476 | /// ``` |
| 477 | #[must_use] |
| 478 | pub fn iter_errors(&self) -> ErrorIter<'_> { |
| 479 | ErrorIter::new(&self.root) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// Flag output format containing only a validity indicator. |
| 484 | /// |
| 485 | /// This is the simplest output format defined in the JSON Schema specification. |
| 486 | /// It contains only a single boolean field indicating whether validation succeeded. |
| 487 | /// |
| 488 | /// # JSON Structure |
| 489 | /// |
| 490 | /// ```json |
| 491 | /// { |
| 492 | /// "valid": true |
| 493 | /// } |
| 494 | /// ``` |
| 495 | /// |
| 496 | /// # Examples |
| 497 | /// |
| 498 | /// ```rust |
| 499 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 500 | /// use serde_json::json; |
| 501 | /// |
| 502 | /// let schema = json!({"type": "string"}); |
| 503 | /// let validator = jsonschema::validator_for(&schema)?; |
| 504 | /// let evaluation = validator.evaluate(&json!("hello")); |
| 505 | /// |
| 506 | /// let flag = evaluation.flag(); |
| 507 | /// assert_eq!(flag.valid, true); |
| 508 | /// |
| 509 | /// let output = serde_json::to_value(flag)?; |
| 510 | /// assert_eq!(output, json!({"valid": true})); |
| 511 | /// # Ok(()) |
| 512 | /// # } |
| 513 | /// ``` |
| 514 | #[derive(Clone, Copy, Debug, Serialize)] |
| 515 | pub struct FlagOutput { |
| 516 | /// Whether the instance is valid according to the schema. |
| 517 | pub valid: bool, |
| 518 | } |
| 519 | |
| 520 | /// List output format providing a flat list of evaluation units. |
| 521 | /// |
| 522 | /// This format represents the evaluation result as a flat sequence where each |
| 523 | /// entry corresponds to a validation step. Each unit includes its evaluation path, |
| 524 | /// schema location, instance location, validity, and any annotations or errors. |
| 525 | /// |
| 526 | /// See [`Evaluation::list`] for an example JSON payload produced by this type. |
| 527 | #[derive(Debug)] |
| 528 | pub struct ListOutput<'a> { |
| 529 | root: &'a EvaluationNode, |
| 530 | } |
| 531 | |
| 532 | /// Hierarchical output format providing a tree structure of evaluation results. |
| 533 | /// |
| 534 | /// This format represents the evaluation as a nested tree that mirrors the logical |
| 535 | /// structure of the schema. Each node contains validation results and child nodes |
| 536 | /// representing nested sub-schema evaluations. |
| 537 | /// |
| 538 | /// See [`Evaluation::hierarchical`] for an example JSON payload produced by this type. |
| 539 | #[derive(Debug)] |
| 540 | pub struct HierarchicalOutput<'a> { |
| 541 | root: &'a EvaluationNode, |
| 542 | } |
| 543 | |
| 544 | impl Serialize for ListOutput<'_> { |
| 545 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 546 | where |
| 547 | S: serde::Serializer, |
| 548 | { |
| 549 | serialize_list(self.root, serializer) |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | impl Serialize for HierarchicalOutput<'_> { |
| 554 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 555 | where |
| 556 | S: serde::Serializer, |
| 557 | { |
| 558 | serialize_hierarchical(self.root, serializer) |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | fn serialize_list<S>(root: &EvaluationNode, serializer: S) -> Result<S::Ok, S::Error> |
| 563 | where |
| 564 | S: serde::Serializer, |
| 565 | { |
| 566 | let mut state = serializer.serialize_struct("ListOutput", 2)?; |
| 567 | state.serialize_field("valid", &root.valid)?; |
| 568 | let mut entries = Vec::new(); |
| 569 | collect_list_entries(root, &mut entries); |
| 570 | state.serialize_field("details", &entries)?; |
| 571 | state.end() |
| 572 | } |
| 573 | |
| 574 | fn serialize_hierarchical<S>(root: &EvaluationNode, serializer: S) -> Result<S::Ok, S::Error> |
| 575 | where |
| 576 | S: serde::Serializer, |
| 577 | { |
| 578 | serialize_unit(root, serializer, true) |
| 579 | } |
| 580 | |
| 581 | fn collect_list_entries<'a>(node: &'a EvaluationNode, out: &mut Vec<ListEntry<'a>>) { |
| 582 | // Note: The spec says "Output units which do not contain errors or annotations SHOULD be |
| 583 | // excluded" but the official test suite includes all nodes. We include all nodes to match |
| 584 | // the reference implementation and test suite expectations. |
| 585 | out.push(ListEntry::new(node)); |
| 586 | for child in &node.children { |
| 587 | collect_list_entries(child, out); |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | fn serialize_unit<S>( |
| 592 | node: &EvaluationNode, |
| 593 | serializer: S, |
| 594 | include_children: bool, |
| 595 | ) -> Result<S::Ok, S::Error> |
| 596 | where |
| 597 | S: serde::Serializer, |
| 598 | { |
| 599 | let mut state = serializer.serialize_struct("OutputUnit", 7)?; |
| 600 | state.serialize_field("valid", &node.valid)?; |
| 601 | state.serialize_field("evaluationPath", node.keyword_location.as_str())?; |
| 602 | state.serialize_field("schemaLocation", node.schema_location.as_ref())?; |
| 603 | state.serialize_field("instanceLocation", node.instance_location.as_str())?; |
| 604 | if let Some(annotations) = &node.annotations { |
| 605 | state.serialize_field("annotations", annotations)?; |
| 606 | } |
| 607 | if let Some(annotations) = &node.dropped_annotations { |
| 608 | state.serialize_field("droppedAnnotations", annotations)?; |
| 609 | } |
| 610 | if !node.errors.is_empty() { |
| 611 | state.serialize_field("errors", &ErrorEntriesSerializer(&node.errors))?; |
| 612 | } |
| 613 | if include_children && !node.children.is_empty() { |
| 614 | state.serialize_field( |
| 615 | "details", |
| 616 | &DetailsSerializer { |
| 617 | children: &node.children, |
| 618 | }, |
| 619 | )?; |
| 620 | } |
| 621 | state.end() |
| 622 | } |
| 623 | |
| 624 | pub(crate) fn format_schema_location( |
| 625 | location: &Location, |
| 626 | absolute: Option<&Arc<Uri<String>>>, |
| 627 | ) -> Arc<str> { |
| 628 | if let Some(uri) = absolute { |
| 629 | let base = uri.as_str(); |
| 630 | if base.contains('#') { |
| 631 | Arc::from(base) |
| 632 | } else if location.as_str().is_empty() { |
| 633 | Arc::from(format!("{base}#")) |
| 634 | } else { |
| 635 | Arc::from(format!("{base}#{}", location.as_str())) |
| 636 | } |
| 637 | } else { |
| 638 | location.as_arc() |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | struct ListEntry<'a> { |
| 643 | node: &'a EvaluationNode, |
| 644 | } |
| 645 | |
| 646 | impl<'a> ListEntry<'a> { |
| 647 | fn new(node: &'a EvaluationNode) -> Self { |
| 648 | ListEntry { node } |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | impl Serialize for ListEntry<'_> { |
| 653 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 654 | where |
| 655 | S: serde::Serializer, |
| 656 | { |
| 657 | serialize_unit(self.node, serializer, false) |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | struct DetailsSerializer<'a> { |
| 662 | children: &'a [EvaluationNode], |
| 663 | } |
| 664 | |
| 665 | impl Serialize for DetailsSerializer<'_> { |
| 666 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 667 | where |
| 668 | S: serde::Serializer, |
| 669 | { |
| 670 | let mut seq = serializer.serialize_seq(Some(self.children.len()))?; |
| 671 | for child in self.children { |
| 672 | seq.serialize_element(&SeqEntry { node: child })?; |
| 673 | } |
| 674 | seq.end() |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | struct SeqEntry<'a> { |
| 679 | node: &'a EvaluationNode, |
| 680 | } |
| 681 | |
| 682 | impl Serialize for SeqEntry<'_> { |
| 683 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 684 | where |
| 685 | S: serde::Serializer, |
| 686 | { |
| 687 | serialize_unit(self.node, serializer, true) |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | /// Entry describing annotations emitted by a keyword during evaluation. |
| 692 | /// |
| 693 | /// Annotations are metadata produced by keywords during successful validation. |
| 694 | /// They provide additional information about which schema keywords matched |
| 695 | /// and what values they produced. |
| 696 | /// |
| 697 | /// # Examples |
| 698 | /// |
| 699 | /// ```rust |
| 700 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 701 | /// use serde_json::json; |
| 702 | /// |
| 703 | /// let schema = json!({ |
| 704 | /// "type": "object", |
| 705 | /// "properties": { |
| 706 | /// "name": {"type": "string"}, |
| 707 | /// "age": {"type": "number"} |
| 708 | /// } |
| 709 | /// }); |
| 710 | /// let validator = jsonschema::validator_for(&schema)?; |
| 711 | /// let instance = json!({"name": "Alice", "age": 30}); |
| 712 | /// let evaluation = validator.evaluate(&instance); |
| 713 | /// let entry = evaluation.iter_annotations().next().unwrap(); |
| 714 | /// assert_eq!(entry.schema_location, "/properties"); |
| 715 | /// assert_eq!(entry.instance_location.as_str(), ""); |
| 716 | /// assert_eq!(entry.annotations.value(), &json!(["age", "name"])); |
| 717 | /// # Ok(()) |
| 718 | /// # } |
| 719 | /// ``` |
| 720 | #[derive(Clone, Copy, Debug)] |
| 721 | pub struct AnnotationEntry<'a> { |
| 722 | /// The JSON Pointer to the schema keyword that produced the annotation. |
| 723 | pub schema_location: &'a str, |
| 724 | /// The absolute URI of the keyword location, if available. |
| 725 | pub absolute_keyword_location: Option<&'a Uri<String>>, |
| 726 | /// The JSON Pointer to the instance location being validated. |
| 727 | pub instance_location: &'a Location, |
| 728 | /// The annotations produced by the keyword. |
| 729 | pub annotations: &'a Annotations, |
| 730 | } |
| 731 | |
| 732 | /// Entry describing errors emitted by a keyword during evaluation. |
| 733 | /// |
| 734 | /// Error entries contain information about validation failures, including |
| 735 | /// the locations in both the schema and instance where the error occurred. |
| 736 | /// |
| 737 | /// # Examples |
| 738 | /// |
| 739 | /// ```rust |
| 740 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 741 | /// use serde_json::json; |
| 742 | /// |
| 743 | /// let schema = json!({ |
| 744 | /// "type": "object", |
| 745 | /// "required": ["name"], |
| 746 | /// "properties": { |
| 747 | /// "age": {"type": "number"} |
| 748 | /// } |
| 749 | /// }); |
| 750 | /// let validator = jsonschema::validator_for(&schema)?; |
| 751 | /// let instance = json!({"age": "oops"}); |
| 752 | /// let evaluation = validator.evaluate(&instance); |
| 753 | /// let entry = evaluation.iter_errors().next().unwrap(); |
| 754 | /// assert_eq!(entry.schema_location, "/properties/age/type"); |
| 755 | /// assert_eq!(entry.instance_location.as_str(), "/age"); |
| 756 | /// assert_eq!(entry.error.to_string(), "\"oops\" is not of type \"number\""); |
| 757 | /// # Ok(()) |
| 758 | /// # } |
| 759 | /// ``` |
| 760 | #[derive(Clone, Copy, Debug)] |
| 761 | pub struct ErrorEntry<'a> { |
| 762 | /// The JSON Pointer to the schema keyword that produced the error. |
| 763 | pub schema_location: &'a str, |
| 764 | /// The absolute URI of the keyword location, if available. |
| 765 | pub absolute_keyword_location: Option<&'a Uri<String>>, |
| 766 | /// The JSON Pointer to the instance location that failed validation. |
| 767 | pub instance_location: &'a Location, |
| 768 | /// The error description. |
| 769 | pub error: &'a ErrorDescription, |
| 770 | } |
| 771 | |
| 772 | struct NodeIter<'a> { |
| 773 | stack: Vec<&'a EvaluationNode>, |
| 774 | } |
| 775 | |
| 776 | impl<'a> NodeIter<'a> { |
| 777 | fn new(root: &'a EvaluationNode) -> Self { |
| 778 | NodeIter { stack: vec![root] } |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | impl<'a> Iterator for NodeIter<'a> { |
| 783 | type Item = &'a EvaluationNode; |
| 784 | |
| 785 | fn next(&mut self) -> Option<Self::Item> { |
| 786 | let node = self.stack.pop()?; |
| 787 | for child in node.children.iter().rev() { |
| 788 | self.stack.push(child); |
| 789 | } |
| 790 | Some(node) |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | /// Iterator over annotations produced during evaluation. |
| 795 | /// |
| 796 | /// This iterator traverses the evaluation tree and yields [`AnnotationEntry`] |
| 797 | /// for each node that produced annotations during validation. |
| 798 | /// |
| 799 | /// Annotations are only present for nodes where validation succeeded. |
| 800 | /// |
| 801 | /// # Examples |
| 802 | /// |
| 803 | /// ```rust |
| 804 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 805 | /// use serde_json::json; |
| 806 | /// |
| 807 | /// let schema = json!({ |
| 808 | /// "type": "object", |
| 809 | /// "properties": { |
| 810 | /// "name": {"type": "string"}, |
| 811 | /// "age": {"type": "number"} |
| 812 | /// } |
| 813 | /// }); |
| 814 | /// let validator = jsonschema::validator_for(&schema)?; |
| 815 | /// let evaluation = validator.evaluate(&json!({"name": "Alice", "age": 30})); |
| 816 | /// |
| 817 | /// let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 818 | /// assert_eq!(annotations.len(), 1); |
| 819 | /// assert_eq!(annotations[0].instance_location.as_str(), ""); |
| 820 | /// assert_eq!(annotations[0].annotations.value(), &json!(["age", "name"])); |
| 821 | /// # Ok(()) |
| 822 | /// # } |
| 823 | /// ``` |
| 824 | pub struct AnnotationIter<'a> { |
| 825 | nodes: NodeIter<'a>, |
| 826 | } |
| 827 | |
| 828 | impl<'a> AnnotationIter<'a> { |
| 829 | fn new(root: &'a EvaluationNode) -> Self { |
| 830 | AnnotationIter { |
| 831 | nodes: NodeIter::new(root), |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | impl<'a> Iterator for AnnotationIter<'a> { |
| 837 | type Item = AnnotationEntry<'a>; |
| 838 | |
| 839 | fn next(&mut self) -> Option<Self::Item> { |
| 840 | for node in self.nodes.by_ref() { |
| 841 | if let Some(annotations) = node.annotations.as_ref() { |
| 842 | return Some(AnnotationEntry { |
| 843 | schema_location: &node.schema_location, |
| 844 | absolute_keyword_location: node.absolute_keyword_location.as_deref(), |
| 845 | instance_location: &node.instance_location, |
| 846 | annotations, |
| 847 | }); |
| 848 | } |
| 849 | } |
| 850 | None |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | /// Iterator over errors produced during evaluation. |
| 855 | /// |
| 856 | /// This iterator traverses the evaluation tree and yields [`ErrorEntry`] |
| 857 | /// for each error encountered during validation. |
| 858 | /// |
| 859 | /// Nodes can have multiple errors, and this iterator will yield all of them |
| 860 | /// in depth-first order. |
| 861 | /// |
| 862 | /// # Examples |
| 863 | /// |
| 864 | /// ```rust |
| 865 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 866 | /// use serde_json::json; |
| 867 | /// |
| 868 | /// let schema = json!({ |
| 869 | /// "type": "object", |
| 870 | /// "required": ["name"], |
| 871 | /// "properties": { |
| 872 | /// "name": {"type": "string"}, |
| 873 | /// "age": {"type": "number", "minimum": 0} |
| 874 | /// } |
| 875 | /// }); |
| 876 | /// let validator = jsonschema::validator_for(&schema)?; |
| 877 | /// let evaluation = validator.evaluate(&json!({"age": -5})); |
| 878 | /// |
| 879 | /// let errors: Vec<_> = evaluation.iter_errors().collect(); |
| 880 | /// assert_eq!(errors.len(), 2); |
| 881 | /// assert_eq!(errors[0].instance_location.as_str(), "/age"); |
| 882 | /// assert_eq!(errors[0].schema_location, "/properties/age/minimum"); |
| 883 | /// assert_eq!(errors[1].schema_location, "/required"); |
| 884 | /// # Ok(()) |
| 885 | /// # } |
| 886 | /// ``` |
| 887 | pub struct ErrorIter<'a> { |
| 888 | nodes: NodeIter<'a>, |
| 889 | current: Option<(&'a EvaluationNode, usize)>, |
| 890 | } |
| 891 | |
| 892 | impl<'a> ErrorIter<'a> { |
| 893 | fn new(root: &'a EvaluationNode) -> Self { |
| 894 | ErrorIter { |
| 895 | nodes: NodeIter::new(root), |
| 896 | current: None, |
| 897 | } |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | impl<'a> Iterator for ErrorIter<'a> { |
| 902 | type Item = ErrorEntry<'a>; |
| 903 | |
| 904 | fn next(&mut self) -> Option<Self::Item> { |
| 905 | loop { |
| 906 | if let Some((node, idx)) = self.current { |
| 907 | if idx < node.errors.len() { |
| 908 | let entry = ErrorEntry { |
| 909 | schema_location: &node.schema_location, |
| 910 | absolute_keyword_location: node.absolute_keyword_location.as_deref(), |
| 911 | instance_location: &node.instance_location, |
| 912 | error: &node.errors[idx], |
| 913 | }; |
| 914 | self.current = Some((node, idx + 1)); |
| 915 | return Some(entry); |
| 916 | } |
| 917 | self.current = None; |
| 918 | } |
| 919 | |
| 920 | match self.nodes.next() { |
| 921 | Some(node) => { |
| 922 | if node.errors.is_empty() { |
| 923 | continue; |
| 924 | } |
| 925 | self.current = Some((node, 0)); |
| 926 | } |
| 927 | None => return None, |
| 928 | } |
| 929 | } |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | struct ErrorEntriesSerializer<'a>(&'a [ErrorDescription]); |
| 934 | |
| 935 | impl Serialize for ErrorEntriesSerializer<'_> { |
| 936 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 937 | where |
| 938 | S: serde::Serializer, |
| 939 | { |
| 940 | let mut grouped: Vec<(&'static str, Vec<&str>)> = Vec::new(); |
| 941 | let mut indexes: AHashMap<&'static str, usize> = AHashMap::new(); |
| 942 | |
| 943 | for error in self.0 { |
| 944 | let keyword = error.keyword(); |
| 945 | let msg = error.message(); |
| 946 | if let Some(&idx) = indexes.get(keyword) { |
| 947 | grouped[idx].1.push(msg); |
| 948 | } else { |
| 949 | indexes.insert(keyword, grouped.len()); |
| 950 | grouped.push((keyword, vec![msg])); |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | let mut map = serializer.serialize_map(Some(grouped.len()))?; |
| 955 | for (keyword, messages) in grouped { |
| 956 | if messages.len() == 1 { |
| 957 | map.serialize_entry(keyword, messages[0])?; |
| 958 | } else { |
| 959 | map.serialize_entry(keyword, &messages)?; |
| 960 | } |
| 961 | } |
| 962 | map.end() |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | #[cfg(test)] |
| 967 | mod tests { |
| 968 | use super::*; |
| 969 | use serde_json::json; |
| 970 | use std::sync::Arc; |
| 971 | |
| 972 | fn loc() -> Location { |
| 973 | Location::new() |
| 974 | } |
| 975 | |
| 976 | fn annotation(value: serde_json::Value) -> Annotations { |
| 977 | Annotations::new(value) |
| 978 | } |
| 979 | |
| 980 | impl ErrorDescription { |
| 981 | fn from_string(s: &str) -> Self { |
| 982 | ErrorDescription { |
| 983 | keyword: "error", |
| 984 | message: s.to_string(), |
| 985 | } |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | fn leaf_with_annotation(schema: &str, ann: serde_json::Value) -> EvaluationNode { |
| 990 | EvaluationNode::valid( |
| 991 | loc(), |
| 992 | None, |
| 993 | schema.to_string(), |
| 994 | loc(), |
| 995 | Some(annotation(ann)), |
| 996 | Vec::new(), |
| 997 | ) |
| 998 | } |
| 999 | |
| 1000 | fn leaf_with_error(schema: &str, msg: &str) -> EvaluationNode { |
| 1001 | EvaluationNode::invalid( |
| 1002 | loc(), |
| 1003 | None, |
| 1004 | schema.to_string(), |
| 1005 | loc(), |
| 1006 | None, |
| 1007 | vec![ErrorDescription::from_string(msg)], |
| 1008 | Vec::new(), |
| 1009 | ) |
| 1010 | } |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn iter_annotations_visits_all_nodes() { |
| 1014 | let child = leaf_with_annotation("/child", json!({"k": "v"})); |
| 1015 | let root = EvaluationNode::valid( |
| 1016 | loc(), |
| 1017 | None, |
| 1018 | "/root".to_string(), |
| 1019 | loc(), |
| 1020 | Some(annotation(json!({"root": true}))), |
| 1021 | vec![child], |
| 1022 | ); |
| 1023 | let evaluation = Evaluation::new(root); |
| 1024 | let entries: Vec<_> = evaluation.iter_annotations().collect(); |
| 1025 | assert_eq!(entries.len(), 2); |
| 1026 | assert_eq!(entries[0].schema_location, "/root"); |
| 1027 | assert_eq!(entries[1].schema_location, "/child"); |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn iter_errors_visits_all_nodes() { |
| 1032 | let child = leaf_with_error("/child", "boom"); |
| 1033 | let root = EvaluationNode::invalid( |
| 1034 | loc(), |
| 1035 | None, |
| 1036 | "/root".to_string(), |
| 1037 | loc(), |
| 1038 | None, |
| 1039 | vec![ErrorDescription::from_string("root error")], |
| 1040 | vec![child], |
| 1041 | ); |
| 1042 | let evaluation = Evaluation::new(root); |
| 1043 | let entries: Vec<_> = evaluation.iter_errors().collect(); |
| 1044 | assert_eq!(entries.len(), 2); |
| 1045 | assert_eq!(entries[0].error.to_string(), "root error"); |
| 1046 | assert_eq!(entries[1].error.to_string(), "boom"); |
| 1047 | } |
| 1048 | |
| 1049 | #[test] |
| 1050 | fn flag_output_valid() { |
| 1051 | let root = EvaluationNode::valid(loc(), None, "/root".to_string(), loc(), None, Vec::new()); |
| 1052 | let evaluation = Evaluation::new(root); |
| 1053 | let flag = evaluation.flag(); |
| 1054 | assert!(flag.valid); |
| 1055 | } |
| 1056 | |
| 1057 | #[test] |
| 1058 | fn flag_output_invalid() { |
| 1059 | let root = EvaluationNode::invalid( |
| 1060 | loc(), |
| 1061 | None, |
| 1062 | "/root".to_string(), |
| 1063 | loc(), |
| 1064 | None, |
| 1065 | vec![ErrorDescription::from_string("error")], |
| 1066 | Vec::new(), |
| 1067 | ); |
| 1068 | let evaluation = Evaluation::new(root); |
| 1069 | let flag = evaluation.flag(); |
| 1070 | assert!(!flag.valid); |
| 1071 | } |
| 1072 | |
| 1073 | #[test] |
| 1074 | fn flag_output_serialization() { |
| 1075 | let root = EvaluationNode::valid(loc(), None, "/root".to_string(), loc(), None, Vec::new()); |
| 1076 | let evaluation = Evaluation::new(root); |
| 1077 | let flag = evaluation.flag(); |
| 1078 | let serialized = serde_json::to_value(flag).expect("serialization succeeds"); |
| 1079 | assert_eq!(serialized, json!({"valid": true})); |
| 1080 | } |
| 1081 | |
| 1082 | #[test] |
| 1083 | fn list_output_serialization_valid() { |
| 1084 | let root = EvaluationNode::valid(loc(), None, "#".to_string(), loc(), None, Vec::new()); |
| 1085 | let evaluation = Evaluation::new(root); |
| 1086 | let list = evaluation.list(); |
| 1087 | let serialized = serde_json::to_value(list).expect("serialization succeeds"); |
| 1088 | assert_eq!( |
| 1089 | serialized, |
| 1090 | json!({ |
| 1091 | "valid": true, |
| 1092 | "details": [ |
| 1093 | { |
| 1094 | "valid": true, |
| 1095 | "evaluationPath": "", |
| 1096 | "schemaLocation": "#", |
| 1097 | "instanceLocation": "" |
| 1098 | } |
| 1099 | ] |
| 1100 | }) |
| 1101 | ); |
| 1102 | } |
| 1103 | |
| 1104 | #[test] |
| 1105 | fn list_output_serialization_with_children() { |
| 1106 | let child1 = leaf_with_annotation("/child1", json!({"key": "value"})); |
| 1107 | let child2 = leaf_with_error("/child2", "child error"); |
| 1108 | let root = EvaluationNode::valid( |
| 1109 | loc(), |
| 1110 | None, |
| 1111 | "/root".to_string(), |
| 1112 | loc(), |
| 1113 | Some(annotation(json!({"root": true}))), |
| 1114 | vec![child1, child2], |
| 1115 | ); |
| 1116 | let evaluation = Evaluation::new(root); |
| 1117 | let list = evaluation.list(); |
| 1118 | let serialized = serde_json::to_value(list).expect("serialization succeeds"); |
| 1119 | assert_eq!( |
| 1120 | serialized, |
| 1121 | json!({ |
| 1122 | "valid": true, |
| 1123 | "details": [ |
| 1124 | { |
| 1125 | "valid": true, |
| 1126 | "evaluationPath": "", |
| 1127 | "schemaLocation": "/root", |
| 1128 | "instanceLocation": "", |
| 1129 | "annotations": {"root": true} |
| 1130 | }, |
| 1131 | { |
| 1132 | "valid": true, |
| 1133 | "evaluationPath": "", |
| 1134 | "schemaLocation": "/child1", |
| 1135 | "instanceLocation": "", |
| 1136 | "annotations": {"key": "value"} |
| 1137 | }, |
| 1138 | { |
| 1139 | "valid": false, |
| 1140 | "evaluationPath": "", |
| 1141 | "schemaLocation": "/child2", |
| 1142 | "instanceLocation": "", |
| 1143 | "errors": {"error": "child error"} |
| 1144 | } |
| 1145 | ] |
| 1146 | }) |
| 1147 | ); |
| 1148 | } |
| 1149 | |
| 1150 | #[test] |
| 1151 | fn hierarchical_output_serialization() { |
| 1152 | let child = leaf_with_annotation("/child", json!({"nested": "data"})); |
| 1153 | let root = EvaluationNode::valid( |
| 1154 | loc(), |
| 1155 | None, |
| 1156 | "/root".to_string(), |
| 1157 | loc(), |
| 1158 | Some(annotation(json!({"root": "annotation"}))), |
| 1159 | vec![child], |
| 1160 | ); |
| 1161 | let evaluation = Evaluation::new(root); |
| 1162 | let hierarchical = evaluation.hierarchical(); |
| 1163 | let serialized = serde_json::to_value(hierarchical).expect("serialization succeeds"); |
| 1164 | assert_eq!( |
| 1165 | serialized, |
| 1166 | json!({ |
| 1167 | "valid": true, |
| 1168 | "evaluationPath": "", |
| 1169 | "schemaLocation": "/root", |
| 1170 | "instanceLocation": "", |
| 1171 | "annotations": {"root": "annotation"}, |
| 1172 | "details": [ |
| 1173 | { |
| 1174 | "valid": true, |
| 1175 | "evaluationPath": "", |
| 1176 | "schemaLocation": "/child", |
| 1177 | "instanceLocation": "", |
| 1178 | "annotations": {"nested": "data"} |
| 1179 | } |
| 1180 | ] |
| 1181 | }) |
| 1182 | ); |
| 1183 | } |
| 1184 | |
| 1185 | #[test] |
| 1186 | fn outputs_include_errors_and_dropped_annotations() { |
| 1187 | let invalid_child = EvaluationNode::invalid( |
| 1188 | loc(), |
| 1189 | None, |
| 1190 | "/items/type".to_string(), |
| 1191 | Location::new().join(1usize), |
| 1192 | None, |
| 1193 | vec![ErrorDescription::from_string("child error")], |
| 1194 | Vec::new(), |
| 1195 | ); |
| 1196 | let prefix_child = leaf_with_annotation("/prefix", json!(0)); |
| 1197 | let root = EvaluationNode::invalid( |
| 1198 | loc(), |
| 1199 | None, |
| 1200 | "/root".to_string(), |
| 1201 | loc(), |
| 1202 | Some(annotation(json!({"dropped": true}))), |
| 1203 | vec![ErrorDescription::from_string("root failure")], |
| 1204 | vec![invalid_child, prefix_child], |
| 1205 | ); |
| 1206 | let evaluation = Evaluation::new(root); |
| 1207 | let list = serde_json::to_value(evaluation.list()).expect("serialization succeeds"); |
| 1208 | assert_eq!( |
| 1209 | list, |
| 1210 | json!({ |
| 1211 | "valid": false, |
| 1212 | "details": [ |
| 1213 | { |
| 1214 | "valid": false, |
| 1215 | "evaluationPath": "", |
| 1216 | "schemaLocation": "/root", |
| 1217 | "instanceLocation": "", |
| 1218 | "droppedAnnotations": {"dropped": true}, |
| 1219 | "errors": {"error": "root failure"} |
| 1220 | }, |
| 1221 | { |
| 1222 | "valid": false, |
| 1223 | "evaluationPath": "", |
| 1224 | "schemaLocation": "/items/type", |
| 1225 | "instanceLocation": "/1", |
| 1226 | "errors": {"error": "child error"} |
| 1227 | }, |
| 1228 | { |
| 1229 | "valid": true, |
| 1230 | "evaluationPath": "", |
| 1231 | "schemaLocation": "/prefix", |
| 1232 | "instanceLocation": "", |
| 1233 | "annotations": 0 |
| 1234 | } |
| 1235 | ] |
| 1236 | }) |
| 1237 | ); |
| 1238 | let hierarchical = |
| 1239 | serde_json::to_value(evaluation.hierarchical()).expect("serialization succeeds"); |
| 1240 | assert_eq!( |
| 1241 | hierarchical, |
| 1242 | json!({ |
| 1243 | "valid": false, |
| 1244 | "evaluationPath": "", |
| 1245 | "schemaLocation": "/root", |
| 1246 | "instanceLocation": "", |
| 1247 | "droppedAnnotations": {"dropped": true}, |
| 1248 | "errors": {"error": "root failure"}, |
| 1249 | "details": [ |
| 1250 | { |
| 1251 | "valid": false, |
| 1252 | "evaluationPath": "", |
| 1253 | "schemaLocation": "/items/type", |
| 1254 | "instanceLocation": "/1", |
| 1255 | "errors": {"error": "child error"} |
| 1256 | }, |
| 1257 | { |
| 1258 | "valid": true, |
| 1259 | "evaluationPath": "", |
| 1260 | "schemaLocation": "/prefix", |
| 1261 | "instanceLocation": "", |
| 1262 | "annotations": 0 |
| 1263 | } |
| 1264 | ] |
| 1265 | }) |
| 1266 | ); |
| 1267 | } |
| 1268 | |
| 1269 | #[test] |
| 1270 | fn empty_evaluation_tree() { |
| 1271 | let root = EvaluationNode::valid(loc(), None, "/root".to_string(), loc(), None, Vec::new()); |
| 1272 | let evaluation = Evaluation::new(root); |
| 1273 | |
| 1274 | // No annotations |
| 1275 | assert_eq!(evaluation.iter_annotations().count(), 0); |
| 1276 | // No errors |
| 1277 | assert_eq!(evaluation.iter_errors().count(), 0); |
| 1278 | |
| 1279 | let flag = evaluation.flag(); |
| 1280 | assert!(flag.valid); |
| 1281 | } |
| 1282 | |
| 1283 | #[test] |
| 1284 | fn deep_nesting() { |
| 1285 | // Create a deeply nested tree: root -> level1 -> level2 -> level3 |
| 1286 | let level3 = leaf_with_annotation("/level3", json!({"level": 3})); |
| 1287 | let level2 = EvaluationNode::valid( |
| 1288 | loc(), |
| 1289 | None, |
| 1290 | "/level2".to_string(), |
| 1291 | loc(), |
| 1292 | Some(annotation(json!({"level": 2}))), |
| 1293 | vec![level3], |
| 1294 | ); |
| 1295 | let level1 = EvaluationNode::valid( |
| 1296 | loc(), |
| 1297 | None, |
| 1298 | "/level1".to_string(), |
| 1299 | loc(), |
| 1300 | Some(annotation(json!({"level": 1}))), |
| 1301 | vec![level2], |
| 1302 | ); |
| 1303 | let root = EvaluationNode::valid( |
| 1304 | loc(), |
| 1305 | None, |
| 1306 | "/root".to_string(), |
| 1307 | loc(), |
| 1308 | Some(annotation(json!({"level": 0}))), |
| 1309 | vec![level1], |
| 1310 | ); |
| 1311 | |
| 1312 | let evaluation = Evaluation::new(root); |
| 1313 | let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 1314 | assert_eq!(annotations.len(), 4); |
| 1315 | |
| 1316 | // Check depth-first order |
| 1317 | assert_eq!(annotations[0].schema_location, "/root"); |
| 1318 | assert_eq!(annotations[1].schema_location, "/level1"); |
| 1319 | assert_eq!(annotations[2].schema_location, "/level2"); |
| 1320 | assert_eq!(annotations[3].schema_location, "/level3"); |
| 1321 | } |
| 1322 | |
| 1323 | #[test] |
| 1324 | fn wide_tree() { |
| 1325 | // Create a wide tree with many siblings |
| 1326 | let children: Vec<_> = (0..10) |
| 1327 | .map(|i| leaf_with_annotation(&format!("/child{i}"), json!({"index": i}))) |
| 1328 | .collect(); |
| 1329 | |
| 1330 | let root = EvaluationNode::valid( |
| 1331 | loc(), |
| 1332 | None, |
| 1333 | "/root".to_string(), |
| 1334 | loc(), |
| 1335 | Some(annotation(json!({"root": true}))), |
| 1336 | children, |
| 1337 | ); |
| 1338 | |
| 1339 | let evaluation = Evaluation::new(root); |
| 1340 | let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 1341 | assert_eq!(annotations.len(), 11); // root + 10 children |
| 1342 | } |
| 1343 | |
| 1344 | #[test] |
| 1345 | fn multiple_errors_per_node() { |
| 1346 | let errors = vec![ |
| 1347 | ErrorDescription::from_string("error 1"), |
| 1348 | ErrorDescription::from_string("error 2"), |
| 1349 | ErrorDescription::from_string("error 3"), |
| 1350 | ]; |
| 1351 | let root = EvaluationNode::invalid( |
| 1352 | loc(), |
| 1353 | None, |
| 1354 | "/root".to_string(), |
| 1355 | loc(), |
| 1356 | None, |
| 1357 | errors, |
| 1358 | Vec::new(), |
| 1359 | ); |
| 1360 | |
| 1361 | let evaluation = Evaluation::new(root); |
| 1362 | let error_entries: Vec<_> = evaluation.iter_errors().collect(); |
| 1363 | assert_eq!(error_entries.len(), 3); |
| 1364 | assert_eq!(error_entries[0].error.to_string(), "error 1"); |
| 1365 | assert_eq!(error_entries[1].error.to_string(), "error 2"); |
| 1366 | assert_eq!(error_entries[2].error.to_string(), "error 3"); |
| 1367 | } |
| 1368 | |
| 1369 | #[test] |
| 1370 | fn mixed_valid_and_invalid_nodes() { |
| 1371 | let valid_child = leaf_with_annotation("/valid", json!({"ok": true})); |
| 1372 | let invalid_child = leaf_with_error("/invalid", "failed"); |
| 1373 | |
| 1374 | let root = EvaluationNode::invalid( |
| 1375 | loc(), |
| 1376 | None, |
| 1377 | "/root".to_string(), |
| 1378 | loc(), |
| 1379 | Some(annotation(json!({"attempted": true}))), |
| 1380 | vec![ErrorDescription::from_string("root failed")], |
| 1381 | vec![valid_child, invalid_child], |
| 1382 | ); |
| 1383 | |
| 1384 | let evaluation = Evaluation::new(root); |
| 1385 | |
| 1386 | // Should have 1 annotation (from valid child only; root has dropped annotations) |
| 1387 | let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 1388 | assert_eq!(annotations.len(), 1); |
| 1389 | assert_eq!(annotations[0].schema_location, "/valid"); |
| 1390 | |
| 1391 | // Should have 2 errors (root + invalid child) |
| 1392 | let errors: Vec<_> = evaluation.iter_errors().collect(); |
| 1393 | assert_eq!(errors.len(), 2); |
| 1394 | } |
| 1395 | |
| 1396 | #[test] |
| 1397 | fn annotations_iterator_skips_nodes_without_annotations() { |
| 1398 | let no_annotation = |
| 1399 | EvaluationNode::valid(loc(), None, "/no_ann".to_string(), loc(), None, Vec::new()); |
| 1400 | let with_annotation = leaf_with_annotation("/with_ann", json!({"present": true})); |
| 1401 | |
| 1402 | let root = EvaluationNode::valid( |
| 1403 | loc(), |
| 1404 | None, |
| 1405 | "/root".to_string(), |
| 1406 | loc(), |
| 1407 | None, |
| 1408 | vec![no_annotation, with_annotation], |
| 1409 | ); |
| 1410 | |
| 1411 | let evaluation = Evaluation::new(root); |
| 1412 | let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 1413 | assert_eq!(annotations.len(), 1); |
| 1414 | assert_eq!(annotations[0].schema_location, "/with_ann"); |
| 1415 | } |
| 1416 | |
| 1417 | #[test] |
| 1418 | fn errors_iterator_skips_nodes_without_errors() { |
| 1419 | let no_error = EvaluationNode::valid( |
| 1420 | loc(), |
| 1421 | None, |
| 1422 | "/no_error".to_string(), |
| 1423 | loc(), |
| 1424 | Some(annotation(json!({"ok": true}))), |
| 1425 | Vec::new(), |
| 1426 | ); |
| 1427 | let with_error = leaf_with_error("/with_error", "failed"); |
| 1428 | |
| 1429 | let root = EvaluationNode::valid( |
| 1430 | loc(), |
| 1431 | None, |
| 1432 | "/root".to_string(), |
| 1433 | loc(), |
| 1434 | None, |
| 1435 | vec![no_error, with_error], |
| 1436 | ); |
| 1437 | |
| 1438 | let evaluation = Evaluation::new(root); |
| 1439 | let errors: Vec<_> = evaluation.iter_errors().collect(); |
| 1440 | assert_eq!(errors.len(), 1); |
| 1441 | assert_eq!(errors[0].schema_location, "/with_error"); |
| 1442 | } |
| 1443 | |
| 1444 | #[test] |
| 1445 | fn error_entries_serialization_empty() { |
| 1446 | let entries = ErrorEntriesSerializer(&[]); |
| 1447 | let serialized = serde_json::to_value(&entries).expect("serialization succeeds"); |
| 1448 | assert!(serialized.is_object()); |
| 1449 | assert_eq!(serialized.as_object().unwrap().len(), 0); |
| 1450 | } |
| 1451 | |
| 1452 | #[test] |
| 1453 | fn error_entries_serialization_single() { |
| 1454 | let errors = vec![ErrorDescription::from_string("test error")]; |
| 1455 | let entries = ErrorEntriesSerializer(&errors); |
| 1456 | let serialized = serde_json::to_value(&entries).expect("serialization succeeds"); |
| 1457 | assert!(serialized.is_object()); |
| 1458 | assert_eq!(serialized.as_object().unwrap().len(), 1); |
| 1459 | assert!(serialized.get("error").is_some()); |
| 1460 | } |
| 1461 | |
| 1462 | #[test] |
| 1463 | fn error_entries_serialization_multiple() { |
| 1464 | let errors = vec![ |
| 1465 | ErrorDescription::new("alpha", "error 1".to_string()), |
| 1466 | ErrorDescription::new("beta", "error 2".to_string()), |
| 1467 | ErrorDescription::new("gamma", "error 3".to_string()), |
| 1468 | ]; |
| 1469 | let entries = ErrorEntriesSerializer(&errors); |
| 1470 | let serialized = serde_json::to_value(&entries).expect("serialization succeeds"); |
| 1471 | assert_eq!(serialized.as_object().unwrap().len(), 3); |
| 1472 | assert!(serialized.get("alpha").is_some()); |
| 1473 | assert!(serialized.get("beta").is_some()); |
| 1474 | assert!(serialized.get("gamma").is_some()); |
| 1475 | } |
| 1476 | |
| 1477 | #[test] |
| 1478 | fn error_entries_serialization_preserves_duplicates() { |
| 1479 | let errors = vec![ |
| 1480 | ErrorDescription::new("required", "\"foo\" is required".to_string()), |
| 1481 | ErrorDescription::new("required", "\"bar\" is required".to_string()), |
| 1482 | ]; |
| 1483 | let entries = ErrorEntriesSerializer(&errors); |
| 1484 | let serialized = serde_json::to_value(&entries).expect("serialization succeeds"); |
| 1485 | let value = serialized |
| 1486 | .get("required") |
| 1487 | .expect("required keyword present") |
| 1488 | .as_array() |
| 1489 | .expect("multiple errors serialized as array"); |
| 1490 | assert_eq!(value.len(), 2); |
| 1491 | assert_eq!(value[0], "\"foo\" is required"); |
| 1492 | assert_eq!(value[1], "\"bar\" is required"); |
| 1493 | } |
| 1494 | |
| 1495 | #[test] |
| 1496 | fn list_output_preserves_multiple_errors_per_keyword() { |
| 1497 | let errors = vec![ |
| 1498 | ErrorDescription::new("required", "\"foo\" is required".to_string()), |
| 1499 | ErrorDescription::new("required", "\"bar\" is required".to_string()), |
| 1500 | ]; |
| 1501 | let root = EvaluationNode::invalid( |
| 1502 | loc(), |
| 1503 | None, |
| 1504 | "/required".to_string(), |
| 1505 | loc(), |
| 1506 | None, |
| 1507 | errors, |
| 1508 | Vec::new(), |
| 1509 | ); |
| 1510 | |
| 1511 | let evaluation = Evaluation::new(root); |
| 1512 | let list = serde_json::to_value(evaluation.list()).expect("serialization succeeds"); |
| 1513 | let root_unit = list |
| 1514 | .get("details") |
| 1515 | .and_then(|value| value.as_array()) |
| 1516 | .and_then(|details| details.first()) |
| 1517 | .expect("list output contains root unit"); |
| 1518 | let errors = root_unit |
| 1519 | .get("errors") |
| 1520 | .and_then(|errors| errors.get("required")) |
| 1521 | .and_then(|value| value.as_array()) |
| 1522 | .expect("errors serialized as array"); |
| 1523 | assert_eq!(errors.len(), 2); |
| 1524 | assert_eq!(errors[0], "\"foo\" is required"); |
| 1525 | assert_eq!(errors[1], "\"bar\" is required"); |
| 1526 | } |
| 1527 | |
| 1528 | #[test] |
| 1529 | fn format_schema_location_without_absolute() { |
| 1530 | let location = Location::new().join("properties").join("name"); |
| 1531 | let formatted = format_schema_location(&location, None); |
| 1532 | assert_eq!(formatted.as_ref(), "/properties/name"); |
| 1533 | } |
| 1534 | |
| 1535 | #[test] |
| 1536 | fn format_schema_location_with_absolute_no_fragment() { |
| 1537 | let location = Location::new().join("properties"); |
| 1538 | let uri = Arc::new( |
| 1539 | Uri::parse("http://example.com/schema.json") |
| 1540 | .unwrap() |
| 1541 | .to_owned(), |
| 1542 | ); |
| 1543 | let formatted = format_schema_location(&location, Some(&uri)); |
| 1544 | assert_eq!( |
| 1545 | formatted.as_ref(), |
| 1546 | "http://example.com/schema.json#/properties" |
| 1547 | ); |
| 1548 | } |
| 1549 | |
| 1550 | #[test] |
| 1551 | fn format_schema_location_with_absolute_empty_location() { |
| 1552 | let location = Location::new(); |
| 1553 | let uri = Arc::new( |
| 1554 | Uri::parse("http://example.com/schema.json") |
| 1555 | .unwrap() |
| 1556 | .to_owned(), |
| 1557 | ); |
| 1558 | let formatted = format_schema_location(&location, Some(&uri)); |
| 1559 | assert_eq!(formatted.as_ref(), "http://example.com/schema.json#"); |
| 1560 | } |
| 1561 | |
| 1562 | #[test] |
| 1563 | fn format_schema_location_with_absolute_existing_fragment() { |
| 1564 | let location = Location::new().join("properties"); |
| 1565 | let uri = Arc::new( |
| 1566 | Uri::parse("http://example.com/schema.json#/defs/myDef") |
| 1567 | .unwrap() |
| 1568 | .to_owned(), |
| 1569 | ); |
| 1570 | let formatted = format_schema_location(&location, Some(&uri)); |
| 1571 | // When URI already contains a fragment, use it as-is |
| 1572 | assert_eq!( |
| 1573 | formatted.as_ref(), |
| 1574 | "http://example.com/schema.json#/defs/myDef" |
| 1575 | ); |
| 1576 | } |
| 1577 | |
| 1578 | #[test] |
| 1579 | fn dropped_annotations_on_invalid_node() { |
| 1580 | let annotations = Some(annotation(json!({"dropped": true}))); |
| 1581 | let root = EvaluationNode::invalid( |
| 1582 | loc(), |
| 1583 | None, |
| 1584 | "/root".to_string(), |
| 1585 | loc(), |
| 1586 | annotations.clone(), |
| 1587 | vec![ErrorDescription::from_string("failed")], |
| 1588 | Vec::new(), |
| 1589 | ); |
| 1590 | |
| 1591 | assert!(!root.valid); |
| 1592 | assert!(root.annotations.is_none()); |
| 1593 | assert!(root.dropped_annotations.is_some()); |
| 1594 | assert_eq!( |
| 1595 | root.dropped_annotations.as_ref().unwrap(), |
| 1596 | annotations.as_ref().unwrap() |
| 1597 | ); |
| 1598 | } |
| 1599 | |
| 1600 | #[test] |
| 1601 | fn valid_node_has_no_dropped_annotations() { |
| 1602 | let annotations = Some(annotation(json!({"kept": true}))); |
| 1603 | let root = EvaluationNode::valid( |
| 1604 | loc(), |
| 1605 | None, |
| 1606 | "/root".to_string(), |
| 1607 | loc(), |
| 1608 | annotations.clone(), |
| 1609 | Vec::new(), |
| 1610 | ); |
| 1611 | |
| 1612 | assert!(root.valid); |
| 1613 | assert!(root.annotations.is_some()); |
| 1614 | assert!(root.dropped_annotations.is_none()); |
| 1615 | assert_eq!( |
| 1616 | root.annotations.as_ref().unwrap(), |
| 1617 | annotations.as_ref().unwrap() |
| 1618 | ); |
| 1619 | } |
| 1620 | |
| 1621 | #[test] |
| 1622 | fn absolute_keyword_location_populated_with_id() { |
| 1623 | use serde_json::json; |
| 1624 | |
| 1625 | // Schema with $id should populate absoluteKeywordLocation |
| 1626 | let schema = json!({ |
| 1627 | "$id": "https://example.com/schema", |
| 1628 | "type": "object", |
| 1629 | "properties": { |
| 1630 | "name": {"type": "string"} |
| 1631 | } |
| 1632 | }); |
| 1633 | |
| 1634 | let validator = crate::validator_for(&schema).expect("schema compiles"); |
| 1635 | let evaluation = validator.evaluate(&json!({"name": "test"})); |
| 1636 | |
| 1637 | // Verify that absoluteKeywordLocation is populated for nodes |
| 1638 | let annotations: Vec<_> = evaluation.iter_annotations().collect(); |
| 1639 | assert!(!annotations.is_empty()); |
| 1640 | |
| 1641 | // At least one annotation should have an absolute keyword location |
| 1642 | let with_absolute = annotations |
| 1643 | .iter() |
| 1644 | .filter(|a| a.absolute_keyword_location.is_some()) |
| 1645 | .count(); |
| 1646 | |
| 1647 | assert!(with_absolute > 0); |
| 1648 | |
| 1649 | // Verify the absolute locations start with the schema's $id |
| 1650 | for annotation in annotations |
| 1651 | .iter() |
| 1652 | .filter(|a| a.absolute_keyword_location.is_some()) |
| 1653 | { |
| 1654 | let uri_str = annotation.absolute_keyword_location.unwrap().as_str(); |
| 1655 | assert!(uri_str.starts_with("https://example.com/schema")); |
| 1656 | } |
| 1657 | } |
| 1658 | |
| 1659 | #[test] |
| 1660 | fn annotations_value_returns_reference() { |
| 1661 | let expected = json!({"key": "value"}); |
| 1662 | let annotations = Annotations::new(expected.clone()); |
| 1663 | |
| 1664 | // value() should return a reference to the inner value |
| 1665 | assert_eq!(annotations.value(), &expected); |
| 1666 | } |
| 1667 | |
| 1668 | #[test] |
| 1669 | fn annotations_into_inner_consumes_and_returns_value() { |
| 1670 | let expected = json!({"key": "value", "nested": {"array": [1, 2, 3]}}); |
| 1671 | let annotations = Annotations::new(expected.clone()); |
| 1672 | |
| 1673 | // into_inner() should consume self and return the owned value |
| 1674 | let inner = annotations.into_inner(); |
| 1675 | assert_eq!(inner, expected); |
| 1676 | } |
| 1677 | |
| 1678 | #[test] |
| 1679 | fn error_description_into_inner_consumes_and_returns_message() { |
| 1680 | let expected_message = "test error message"; |
| 1681 | let error = ErrorDescription::from_string(expected_message); |
| 1682 | |
| 1683 | // into_inner() should consume self and return the owned message |
| 1684 | let message = error.into_inner(); |
| 1685 | assert_eq!(message, expected_message); |
| 1686 | } |
| 1687 | } |