Debian Codegraph @

src/error.rs

raw symbols SCIP
1 //! # Error Handling
2 //!
3 //! ## Masking Sensitive Data
4 //!
5 //! When working with sensitive data, you might want to hide actual values from error messages.
6 //! The `ValidationError` type provides methods to mask instance values while preserving the error context:
7 //!
8 //! ```rust
9 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
10 //! use serde_json::json;
11 //!
12 //! let schema = json!({"maxLength": 5});
13 //! let instance = json!("sensitive data");
14 //! let validator = jsonschema::validator_for(&schema)?;
15 //!
16 //! if let Err(error) = validator.validate(&instance) {
17 //! // Use default masking (replaces values with "value")
18 //! println!("Masked error: {}", error.masked());
19 //! // Or provide custom placeholder
20 //! println!("Custom masked: {}", error.masked_with("[REDACTED]"));
21 //! }
22 //! # Ok(())
23 //! # }
24 //! ```
25 //!
26 //! The masked error messages will replace instance values with placeholders while maintaining
27 //! schema-related information like property names, limits, and types.
28 //!
29 //! Original error:
30 //! ```text
31 //! "sensitive data" is longer than 5 characters
32 //! ```
33 //!
34 //! Masked error:
35 //! ```text
36 //! value is longer than 5 characters
37 //! ```
38 use crate::{
39 paths::Location,
40 thread::ThreadBound,
41 types::{JsonType, JsonTypeSet},
42 };
43 use serde_json::{Map, Number, Value};
44 use std::{
45 borrow::Cow,
46 error,
47 fmt::{self, Formatter, Write},
48 iter::{empty, once},
49 slice,
50 string::FromUtf8Error,
51 vec,
52 };
53
54 /// An error that can occur during validation.
55 #[derive(Debug)]
56 pub struct ValidationError<'a> {
57 repr: Box<ValidationErrorRepr<'a>>,
58 }
59
60 #[derive(Debug)]
61 struct ValidationErrorRepr<'a> {
62 instance: Cow<'a, Value>,
63 kind: ValidationErrorKind,
64 instance_path: Location,
65 schema_path: Location,
66 }
67
68 /// An iterator over instances of [`ValidationError`] that represent validation error for the
69 /// input instance.
70 ///
71 /// # Examples
72 ///
73 /// ```rust
74 /// use serde_json::json;
75 ///
76 /// let schema = json!({"maxLength": 5});
77 /// let instance = json!("foo");
78 /// if let Ok(validator) = jsonschema::validator_for(&schema) {
79 /// let errors = validator.iter_errors(&instance);
80 /// for error in errors {
81 /// println!("Validation error: {}", error)
82 /// }
83 /// }
84 /// ```
85 #[doc(hidden)]
86 pub trait ValidationErrorIterator<'a>: Iterator<Item = ValidationError<'a>> + ThreadBound {}
87
88 impl<'a, T> ValidationErrorIterator<'a> for T where
89 T: Iterator<Item = ValidationError<'a>> + ThreadBound
90 {
91 }
92
93 /// A lazily-evaluated iterator over validation errors.
94 ///
95 /// Use [`into_errors()`](Self::into_errors) to convert into [`ValidationErrors`],
96 /// which implements [`std::error::Error`] for integration with error handling libraries.
97 pub struct ErrorIterator<'a> {
98 iter: Box<dyn ValidationErrorIterator<'a> + 'a>,
99 }
100
101 impl<'a> ErrorIterator<'a> {
102 #[inline]
103 pub(crate) fn from_iterator<T>(iterator: T) -> Self
104 where
105 T: ValidationErrorIterator<'a> + 'a,
106 {
107 Self {
108 iter: Box::new(iterator),
109 }
110 }
111
112 /// Collects all errors into [`ValidationErrors`], which implements [`std::error::Error`].
113 #[inline]
114 #[must_use]
115 pub fn into_errors(self) -> ValidationErrors<'a> {
116 ValidationErrors {
117 errors: self.collect(),
118 }
119 }
120 }
121
122 /// An owned collection of validation errors that implements [`std::error::Error`].
123 ///
124 /// Obtain this by calling [`ErrorIterator::into_errors()`].
125 pub struct ValidationErrors<'a> {
126 errors: Vec<ValidationError<'a>>,
127 }
128
129 impl<'a> ValidationErrors<'a> {
130 #[inline]
131 #[must_use]
132 pub fn len(&self) -> usize {
133 self.errors.len()
134 }
135
136 #[inline]
137 #[must_use]
138 pub fn is_empty(&self) -> bool {
139 self.errors.is_empty()
140 }
141
142 /// Returns the errors as a slice.
143 #[inline]
144 #[must_use]
145 pub fn as_slice(&self) -> &[ValidationError<'a>] {
146 &self.errors
147 }
148
149 #[inline]
150 pub fn iter(&self) -> slice::Iter<'_, ValidationError<'a>> {
151 self.errors.iter()
152 }
153
154 #[inline]
155 pub fn iter_mut(&mut self) -> slice::IterMut<'_, ValidationError<'a>> {
156 self.errors.iter_mut()
157 }
158 }
159
160 impl fmt::Display for ValidationErrors<'_> {
161 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
162 if self.errors.is_empty() {
163 f.write_str("Validation succeeded")
164 } else {
165 writeln!(f, "Validation errors:")?;
166 for (idx, error) in self.errors.iter().enumerate() {
167 writeln!(f, "{:02}: {error}", idx + 1)?;
168 }
169 Ok(())
170 }
171 }
172 }
173
174 impl fmt::Debug for ValidationErrors<'_> {
175 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
176 f.debug_struct("ValidationErrors")
177 .field("errors", &self.errors)
178 .finish()
179 }
180 }
181
182 impl error::Error for ValidationErrors<'_> {}
183
184 impl<'a> Iterator for ErrorIterator<'a> {
185 type Item = ValidationError<'a>;
186
187 #[inline]
188 fn next(&mut self) -> Option<Self::Item> {
189 self.iter.as_mut().next()
190 }
191
192 #[inline]
193 fn size_hint(&self) -> (usize, Option<usize>) {
194 self.iter.size_hint()
195 }
196 }
197
198 impl<'a> IntoIterator for ValidationErrors<'a> {
199 type Item = ValidationError<'a>;
200 type IntoIter = vec::IntoIter<ValidationError<'a>>;
201
202 fn into_iter(self) -> Self::IntoIter {
203 self.errors.into_iter()
204 }
205 }
206
207 impl<'a, 'b> IntoIterator for &'b ValidationErrors<'a> {
208 type Item = &'b ValidationError<'a>;
209 type IntoIter = slice::Iter<'b, ValidationError<'a>>;
210
211 fn into_iter(self) -> Self::IntoIter {
212 self.errors.iter()
213 }
214 }
215
216 impl<'a, 'b> IntoIterator for &'b mut ValidationErrors<'a> {
217 type Item = &'b mut ValidationError<'a>;
218 type IntoIter = slice::IterMut<'b, ValidationError<'a>>;
219
220 fn into_iter(self) -> Self::IntoIter {
221 self.errors.iter_mut()
222 }
223 }
224
225 // Empty iterator means no error happened
226 pub(crate) fn no_error<'a>() -> ErrorIterator<'a> {
227 ErrorIterator::from_iterator(empty())
228 }
229 // A wrapper for one error
230 pub(crate) fn error(instance: ValidationError) -> ErrorIterator {
231 ErrorIterator::from_iterator(once(instance))
232 }
233
234 /// Kinds of errors that may happen during validation
235 #[derive(Debug)]
236 #[allow(missing_docs)]
237 pub enum ValidationErrorKind {
238 /// The input array contain more items than expected.
239 AdditionalItems { limit: usize },
240 /// Unexpected properties.
241 AdditionalProperties { unexpected: Vec<String> },
242 /// The input value is not valid under any of the schemas listed in the 'anyOf' keyword.
243 AnyOf {
244 context: Vec<Vec<ValidationError<'static>>>,
245 },
246 /// Results from a [`fancy_regex::RuntimeError::BacktrackLimitExceeded`] variant when matching
247 BacktrackLimitExceeded { error: fancy_regex::Error },
248 /// The input value doesn't match expected constant.
249 Constant { expected_value: Value },
250 /// The input array doesn't contain items conforming to the specified schema.
251 Contains,
252 /// The input value does not respect the defined contentEncoding
253 ContentEncoding { content_encoding: String },
254 /// The input value does not respect the defined contentMediaType
255 ContentMediaType { content_media_type: String },
256 /// Custom error message for user-defined validation.
257 Custom { message: String },
258 /// The input value doesn't match any of specified options.
259 Enum { options: Value },
260 /// Value is too large.
261 ExclusiveMaximum { limit: Value },
262 /// Value is too small.
263 ExclusiveMinimum { limit: Value },
264 /// Everything is invalid for `false` schema.
265 FalseSchema,
266 /// When the input doesn't match to the specified format.
267 Format { format: String },
268 /// May happen in `contentEncoding` validation if `base64` encoded data is invalid.
269 FromUtf8 { error: FromUtf8Error },
270 /// Too many items in an array.
271 MaxItems { limit: u64 },
272 /// Value is too large.
273 Maximum { limit: Value },
274 /// String is too long.
275 MaxLength { limit: u64 },
276 /// Too many properties in an object.
277 MaxProperties { limit: u64 },
278 /// Too few items in an array.
279 MinItems { limit: u64 },
280 /// Value is too small.
281 Minimum { limit: Value },
282 /// String is too short.
283 MinLength { limit: u64 },
284 /// Not enough properties in an object.
285 MinProperties { limit: u64 },
286 /// When some number is not a multiple of another number.
287 MultipleOf {
288 #[cfg(feature = "arbitrary-precision")]
289 multiple_of: Value,
290 #[cfg(not(feature = "arbitrary-precision"))]
291 multiple_of: f64,
292 },
293 /// Negated schema failed validation.
294 Not { schema: Value },
295 /// The given schema is valid under more than one of the schemas listed in the 'oneOf' keyword.
296 OneOfMultipleValid {
297 context: Vec<Vec<ValidationError<'static>>>,
298 },
299 /// The given schema is not valid under any of the schemas listed in the 'oneOf' keyword.
300 OneOfNotValid {
301 context: Vec<Vec<ValidationError<'static>>>,
302 },
303 /// When the input doesn't match to a pattern.
304 Pattern { pattern: String },
305 /// Object property names are invalid.
306 PropertyNames {
307 error: Box<ValidationError<'static>>,
308 },
309 /// When a required property is missing.
310 Required { property: Value },
311 /// When the input value doesn't match one or multiple required types.
312 Type { kind: TypeKind },
313 /// Unexpected items.
314 UnevaluatedItems { unexpected: Vec<String> },
315 /// Unexpected properties.
316 UnevaluatedProperties { unexpected: Vec<String> },
317 /// When the input array has non-unique elements.
318 UniqueItems,
319 /// Error during schema ref resolution.
320 Referencing(referencing::Error),
321 }
322
323 impl ValidationErrorKind {
324 pub(crate) fn keyword(&self) -> &'static str {
325 match self {
326 ValidationErrorKind::AdditionalItems { .. } => "additionalItems",
327 ValidationErrorKind::AdditionalProperties { .. } => "additionalProperties",
328 ValidationErrorKind::AnyOf { .. } => "anyOf",
329 ValidationErrorKind::BacktrackLimitExceeded { .. }
330 | ValidationErrorKind::Pattern { .. } => "pattern",
331 ValidationErrorKind::Constant { .. } => "const",
332 ValidationErrorKind::Contains => "contains",
333 ValidationErrorKind::ContentEncoding { .. } | ValidationErrorKind::FromUtf8 { .. } => {
334 "contentEncoding"
335 }
336 ValidationErrorKind::ContentMediaType { .. } => "contentMediaType",
337 ValidationErrorKind::Custom { .. } => "custom",
338 ValidationErrorKind::Enum { .. } => "enum",
339 ValidationErrorKind::ExclusiveMaximum { .. } => "exclusiveMaximum",
340 ValidationErrorKind::ExclusiveMinimum { .. } => "exclusiveMinimum",
341 ValidationErrorKind::FalseSchema => "falseSchema",
342 ValidationErrorKind::Format { .. } => "format",
343 ValidationErrorKind::MaxItems { .. } => "maxItems",
344 ValidationErrorKind::Maximum { .. } => "maximum",
345 ValidationErrorKind::MaxLength { .. } => "maxLength",
346 ValidationErrorKind::MaxProperties { .. } => "maxProperties",
347 ValidationErrorKind::MinItems { .. } => "minItems",
348 ValidationErrorKind::Minimum { .. } => "minimum",
349 ValidationErrorKind::MinLength { .. } => "minLength",
350 ValidationErrorKind::MinProperties { .. } => "minProperties",
351 ValidationErrorKind::MultipleOf { .. } => "multipleOf",
352 ValidationErrorKind::Not { .. } => "not",
353 ValidationErrorKind::OneOfMultipleValid { .. }
354 | ValidationErrorKind::OneOfNotValid { .. } => "oneOf",
355 ValidationErrorKind::PropertyNames { .. } => "propertyNames",
356 ValidationErrorKind::Required { .. } => "required",
357 ValidationErrorKind::Type { .. } => "type",
358 ValidationErrorKind::UnevaluatedItems { .. } => "unevaluatedItems",
359 ValidationErrorKind::UnevaluatedProperties { .. } => "unevaluatedProperties",
360 ValidationErrorKind::UniqueItems => "uniqueItems",
361 ValidationErrorKind::Referencing(_) => "$ref",
362 }
363 }
364 }
365
366 #[derive(Debug)]
367 #[allow(missing_docs)]
368 pub enum TypeKind {
369 Single(JsonType),
370 Multiple(JsonTypeSet),
371 }
372
373 /// Shortcuts for creation of specific error kinds.
374 impl<'a> ValidationError<'a> {
375 /// Creates a new validation error from parts.
376 #[inline]
377 #[must_use]
378 pub(crate) fn new(
379 instance: Cow<'a, Value>,
380 kind: ValidationErrorKind,
381 instance_path: Location,
382 schema_path: Location,
383 ) -> Self {
384 Self {
385 repr: Box::new(ValidationErrorRepr {
386 instance,
387 kind,
388 instance_path,
389 schema_path,
390 }),
391 }
392 }
393
394 /// Returns a reference to the instance that failed validation.
395 #[inline]
396 #[must_use]
397 pub fn instance(&self) -> &Cow<'a, Value> {
398 &self.repr.instance
399 }
400
401 /// Returns the kind of validation error.
402 #[inline]
403 #[must_use]
404 pub fn kind(&self) -> &ValidationErrorKind {
405 &self.repr.kind
406 }
407
408 /// Returns the JSON Pointer to the instance location that failed validation.
409 #[inline]
410 #[must_use]
411 pub fn instance_path(&self) -> &Location {
412 &self.repr.instance_path
413 }
414
415 /// Returns the JSON Pointer to the schema keyword that failed validation.
416 #[inline]
417 #[must_use]
418 pub fn schema_path(&self) -> &Location {
419 &self.repr.schema_path
420 }
421
422 /// Decomposes the error into owned parts.
423 #[inline]
424 #[must_use]
425 pub fn into_parts(self) -> (Cow<'a, Value>, ValidationErrorKind, Location, Location) {
426 let repr = *self.repr;
427 (
428 repr.instance,
429 repr.kind,
430 repr.instance_path,
431 repr.schema_path,
432 )
433 }
434
435 #[inline]
436 fn borrowed(
437 instance: &'a Value,
438 kind: ValidationErrorKind,
439 instance_path: Location,
440 schema_path: Location,
441 ) -> Self {
442 Self::new(Cow::Borrowed(instance), kind, instance_path, schema_path)
443 }
444
445 /// Returns a wrapper that masks instance values in error messages.
446 /// Uses "value" as a default placeholder.
447 #[must_use]
448 pub fn masked<'b>(&'b self) -> MaskedValidationError<'a, 'b, 'static> {
449 self.masked_with("value")
450 }
451
452 /// Returns a wrapper that masks instance values in error messages with a custom placeholder.
453 pub fn masked_with<'b, 'c>(
454 &'b self,
455 placeholder: impl Into<Cow<'c, str>>,
456 ) -> MaskedValidationError<'a, 'b, 'c> {
457 MaskedValidationError {
458 error: self,
459 placeholder: placeholder.into(),
460 }
461 }
462 /// Converts the `ValidationError` into an owned version with `'static` lifetime.
463 #[must_use]
464 pub fn to_owned(self) -> ValidationError<'static> {
465 let (instance, kind, instance_path, schema_path) = self.into_parts();
466 ValidationError::new(
467 Cow::Owned(instance.into_owned()),
468 kind,
469 instance_path,
470 schema_path,
471 )
472 }
473
474 pub(crate) fn additional_items(
475 location: Location,
476 instance_path: Location,
477 instance: &'a Value,
478 limit: usize,
479 ) -> ValidationError<'a> {
480 Self::borrowed(
481 instance,
482 ValidationErrorKind::AdditionalItems { limit },
483 instance_path,
484 location,
485 )
486 }
487 pub(crate) fn additional_properties(
488 location: Location,
489 instance_path: Location,
490 instance: &'a Value,
491 unexpected: Vec<String>,
492 ) -> ValidationError<'a> {
493 Self::borrowed(
494 instance,
495 ValidationErrorKind::AdditionalProperties { unexpected },
496 instance_path,
497 location,
498 )
499 }
500 pub(crate) fn any_of(
501 location: Location,
502 instance_path: Location,
503 instance: &'a Value,
504 context: Vec<Vec<ValidationError<'a>>>,
505 ) -> ValidationError<'a> {
506 let context = context
507 .into_iter()
508 .map(|errors| errors.into_iter().map(ValidationError::to_owned).collect())
509 .collect::<Vec<_>>();
510
511 Self::borrowed(
512 instance,
513 ValidationErrorKind::AnyOf { context },
514 instance_path,
515 location,
516 )
517 }
518 pub(crate) fn backtrack_limit(
519 location: Location,
520 instance_path: Location,
521 instance: &'a Value,
522 error: fancy_regex::Error,
523 ) -> ValidationError<'a> {
524 Self::borrowed(
525 instance,
526 ValidationErrorKind::BacktrackLimitExceeded { error },
527 instance_path,
528 location,
529 )
530 }
531 pub(crate) fn constant_array(
532 location: Location,
533 instance_path: Location,
534 instance: &'a Value,
535 expected_value: &[Value],
536 ) -> ValidationError<'a> {
537 Self::borrowed(
538 instance,
539 ValidationErrorKind::Constant {
540 expected_value: Value::Array(expected_value.to_vec()),
541 },
542 instance_path,
543 location,
544 )
545 }
546 pub(crate) fn constant_boolean(
547 location: Location,
548 instance_path: Location,
549 instance: &'a Value,
550 expected_value: bool,
551 ) -> ValidationError<'a> {
552 Self::borrowed(
553 instance,
554 ValidationErrorKind::Constant {
555 expected_value: Value::Bool(expected_value),
556 },
557 instance_path,
558 location,
559 )
560 }
561 pub(crate) fn constant_null(
562 location: Location,
563 instance_path: Location,
564 instance: &'a Value,
565 ) -> ValidationError<'a> {
566 Self::borrowed(
567 instance,
568 ValidationErrorKind::Constant {
569 expected_value: Value::Null,
570 },
571 instance_path,
572 location,
573 )
574 }
575 pub(crate) fn constant_number(
576 location: Location,
577 instance_path: Location,
578 instance: &'a Value,
579 expected_value: &Number,
580 ) -> ValidationError<'a> {
581 Self::borrowed(
582 instance,
583 ValidationErrorKind::Constant {
584 expected_value: Value::Number(expected_value.clone()),
585 },
586 instance_path,
587 location,
588 )
589 }
590 pub(crate) fn constant_object(
591 location: Location,
592 instance_path: Location,
593 instance: &'a Value,
594 expected_value: &Map<String, Value>,
595 ) -> ValidationError<'a> {
596 Self::borrowed(
597 instance,
598 ValidationErrorKind::Constant {
599 expected_value: Value::Object(expected_value.clone()),
600 },
601 instance_path,
602 location,
603 )
604 }
605 pub(crate) fn constant_string(
606 location: Location,
607 instance_path: Location,
608 instance: &'a Value,
609 expected_value: &str,
610 ) -> ValidationError<'a> {
611 Self::borrowed(
612 instance,
613 ValidationErrorKind::Constant {
614 expected_value: Value::String(expected_value.to_string()),
615 },
616 instance_path,
617 location,
618 )
619 }
620 pub(crate) fn contains(
621 location: Location,
622 instance_path: Location,
623 instance: &'a Value,
624 ) -> ValidationError<'a> {
625 Self::borrowed(
626 instance,
627 ValidationErrorKind::Contains,
628 instance_path,
629 location,
630 )
631 }
632 pub(crate) fn content_encoding(
633 location: Location,
634 instance_path: Location,
635 instance: &'a Value,
636 encoding: &str,
637 ) -> ValidationError<'a> {
638 Self::borrowed(
639 instance,
640 ValidationErrorKind::ContentEncoding {
641 content_encoding: encoding.to_string(),
642 },
643 instance_path,
644 location,
645 )
646 }
647 pub(crate) fn content_media_type(
648 location: Location,
649 instance_path: Location,
650 instance: &'a Value,
651 media_type: &str,
652 ) -> ValidationError<'a> {
653 Self::borrowed(
654 instance,
655 ValidationErrorKind::ContentMediaType {
656 content_media_type: media_type.to_string(),
657 },
658 instance_path,
659 location,
660 )
661 }
662 pub(crate) fn enumeration(
663 location: Location,
664 instance_path: Location,
665 instance: &'a Value,
666 options: &Value,
667 ) -> ValidationError<'a> {
668 Self::borrowed(
669 instance,
670 ValidationErrorKind::Enum {
671 options: options.clone(),
672 },
673 instance_path,
674 location,
675 )
676 }
677 pub(crate) fn exclusive_maximum(
678 location: Location,
679 instance_path: Location,
680 instance: &'a Value,
681 limit: Value,
682 ) -> ValidationError<'a> {
683 Self::borrowed(
684 instance,
685 ValidationErrorKind::ExclusiveMaximum { limit },
686 instance_path,
687 location,
688 )
689 }
690 pub(crate) fn exclusive_minimum(
691 location: Location,
692 instance_path: Location,
693 instance: &'a Value,
694 limit: Value,
695 ) -> ValidationError<'a> {
696 Self::borrowed(
697 instance,
698 ValidationErrorKind::ExclusiveMinimum { limit },
699 instance_path,
700 location,
701 )
702 }
703 pub(crate) fn false_schema(
704 location: Location,
705 instance_path: Location,
706 instance: &'a Value,
707 ) -> ValidationError<'a> {
708 Self::borrowed(
709 instance,
710 ValidationErrorKind::FalseSchema,
711 instance_path,
712 location,
713 )
714 }
715 pub(crate) fn format(
716 location: Location,
717 instance_path: Location,
718 instance: &'a Value,
719 format: impl Into<String>,
720 ) -> ValidationError<'a> {
721 Self::borrowed(
722 instance,
723 ValidationErrorKind::Format {
724 format: format.into(),
725 },
726 instance_path,
727 location,
728 )
729 }
730 pub(crate) fn from_utf8(error: FromUtf8Error) -> ValidationError<'a> {
731 ValidationError::new(
732 Cow::Owned(Value::Null),
733 ValidationErrorKind::FromUtf8 { error },
734 Location::new(),
735 Location::new(),
736 )
737 }
738 pub(crate) fn max_items(
739 location: Location,
740 instance_path: Location,
741 instance: &'a Value,
742 limit: u64,
743 ) -> ValidationError<'a> {
744 Self::borrowed(
745 instance,
746 ValidationErrorKind::MaxItems { limit },
747 instance_path,
748 location,
749 )
750 }
751 pub(crate) fn maximum(
752 location: Location,
753 instance_path: Location,
754 instance: &'a Value,
755 limit: Value,
756 ) -> ValidationError<'a> {
757 Self::borrowed(
758 instance,
759 ValidationErrorKind::Maximum { limit },
760 instance_path,
761 location,
762 )
763 }
764 pub(crate) fn max_length(
765 location: Location,
766 instance_path: Location,
767 instance: &'a Value,
768 limit: u64,
769 ) -> ValidationError<'a> {
770 Self::borrowed(
771 instance,
772 ValidationErrorKind::MaxLength { limit },
773 instance_path,
774 location,
775 )
776 }
777 pub(crate) fn max_properties(
778 location: Location,
779 instance_path: Location,
780 instance: &'a Value,
781 limit: u64,
782 ) -> ValidationError<'a> {
783 Self::borrowed(
784 instance,
785 ValidationErrorKind::MaxProperties { limit },
786 instance_path,
787 location,
788 )
789 }
790 pub(crate) fn min_items(
791 location: Location,
792 instance_path: Location,
793 instance: &'a Value,
794 limit: u64,
795 ) -> ValidationError<'a> {
796 Self::borrowed(
797 instance,
798 ValidationErrorKind::MinItems { limit },
799 instance_path,
800 location,
801 )
802 }
803 pub(crate) fn minimum(
804 location: Location,
805 instance_path: Location,
806 instance: &'a Value,
807 limit: Value,
808 ) -> ValidationError<'a> {
809 Self::borrowed(
810 instance,
811 ValidationErrorKind::Minimum { limit },
812 instance_path,
813 location,
814 )
815 }
816 pub(crate) fn min_length(
817 location: Location,
818 instance_path: Location,
819 instance: &'a Value,
820 limit: u64,
821 ) -> ValidationError<'a> {
822 Self::borrowed(
823 instance,
824 ValidationErrorKind::MinLength { limit },
825 instance_path,
826 location,
827 )
828 }
829 pub(crate) fn min_properties(
830 location: Location,
831 instance_path: Location,
832 instance: &'a Value,
833 limit: u64,
834 ) -> ValidationError<'a> {
835 Self::borrowed(
836 instance,
837 ValidationErrorKind::MinProperties { limit },
838 instance_path,
839 location,
840 )
841 }
842 #[cfg(feature = "arbitrary-precision")]
843 pub(crate) fn multiple_of(
844 location: Location,
845 instance_path: Location,
846 instance: &'a Value,
847 multiple_of: Value,
848 ) -> ValidationError<'a> {
849 Self::borrowed(
850 instance,
851 ValidationErrorKind::MultipleOf { multiple_of },
852 instance_path,
853 location,
854 )
855 }
856
857 #[cfg(not(feature = "arbitrary-precision"))]
858 pub(crate) fn multiple_of(
859 location: Location,
860 instance_path: Location,
861 instance: &'a Value,
862 multiple_of: f64,
863 ) -> ValidationError<'a> {
864 Self::borrowed(
865 instance,
866 ValidationErrorKind::MultipleOf { multiple_of },
867 instance_path,
868 location,
869 )
870 }
871 pub(crate) fn not(
872 location: Location,
873 instance_path: Location,
874 instance: &'a Value,
875 schema: Value,
876 ) -> ValidationError<'a> {
877 Self::borrowed(
878 instance,
879 ValidationErrorKind::Not { schema },
880 instance_path,
881 location,
882 )
883 }
884 pub(crate) fn one_of_multiple_valid(
885 location: Location,
886 instance_path: Location,
887 instance: &'a Value,
888 context: Vec<Vec<ValidationError<'a>>>,
889 ) -> ValidationError<'a> {
890 let context = context
891 .into_iter()
892 .map(|errors| errors.into_iter().map(ValidationError::to_owned).collect())
893 .collect::<Vec<_>>();
894
895 Self::borrowed(
896 instance,
897 ValidationErrorKind::OneOfMultipleValid { context },
898 instance_path,
899 location,
900 )
901 }
902 pub(crate) fn one_of_not_valid(
903 location: Location,
904 instance_path: Location,
905 instance: &'a Value,
906 context: Vec<Vec<ValidationError<'a>>>,
907 ) -> ValidationError<'a> {
908 let context = context
909 .into_iter()
910 .map(|errors| errors.into_iter().map(ValidationError::to_owned).collect())
911 .collect::<Vec<_>>();
912
913 Self::borrowed(
914 instance,
915 ValidationErrorKind::OneOfNotValid { context },
916 instance_path,
917 location,
918 )
919 }
920 pub(crate) fn pattern(
921 location: Location,
922 instance_path: Location,
923 instance: &'a Value,
924 pattern: String,
925 ) -> ValidationError<'a> {
926 Self::borrowed(
927 instance,
928 ValidationErrorKind::Pattern { pattern },
929 instance_path,
930 location,
931 )
932 }
933 pub(crate) fn property_names(
934 location: Location,
935 instance_path: Location,
936 instance: &'a Value,
937 error: ValidationError<'a>,
938 ) -> ValidationError<'a> {
939 Self::borrowed(
940 instance,
941 ValidationErrorKind::PropertyNames {
942 error: Box::new(error.to_owned()),
943 },
944 instance_path,
945 location,
946 )
947 }
948 pub(crate) fn required(
949 location: Location,
950 instance_path: Location,
951 instance: &'a Value,
952 property: Value,
953 ) -> ValidationError<'a> {
954 Self::borrowed(
955 instance,
956 ValidationErrorKind::Required { property },
957 instance_path,
958 location,
959 )
960 }
961
962 pub(crate) fn single_type_error(
963 location: Location,
964 instance_path: Location,
965 instance: &'a Value,
966 type_name: JsonType,
967 ) -> ValidationError<'a> {
968 Self::borrowed(
969 instance,
970 ValidationErrorKind::Type {
971 kind: TypeKind::Single(type_name),
972 },
973 instance_path,
974 location,
975 )
976 }
977 pub(crate) fn multiple_type_error(
978 location: Location,
979 instance_path: Location,
980 instance: &'a Value,
981 types: JsonTypeSet,
982 ) -> ValidationError<'a> {
983 Self::borrowed(
984 instance,
985 ValidationErrorKind::Type {
986 kind: TypeKind::Multiple(types),
987 },
988 instance_path,
989 location,
990 )
991 }
992 pub(crate) fn unevaluated_items(
993 location: Location,
994 instance_path: Location,
995 instance: &'a Value,
996 unexpected: Vec<String>,
997 ) -> ValidationError<'a> {
998 Self::borrowed(
999 instance,
1000 ValidationErrorKind::UnevaluatedItems { unexpected },
1001 instance_path,
1002 location,
1003 )
1004 }
1005 pub(crate) fn unevaluated_properties(
1006 location: Location,
1007 instance_path: Location,
1008 instance: &'a Value,
1009 unexpected: Vec<String>,
1010 ) -> ValidationError<'a> {
1011 Self::borrowed(
1012 instance,
1013 ValidationErrorKind::UnevaluatedProperties { unexpected },
1014 instance_path,
1015 location,
1016 )
1017 }
1018 pub(crate) fn unique_items(
1019 location: Location,
1020 instance_path: Location,
1021 instance: &'a Value,
1022 ) -> ValidationError<'a> {
1023 Self::borrowed(
1024 instance,
1025 ValidationErrorKind::UniqueItems,
1026 instance_path,
1027 location,
1028 )
1029 }
1030 /// Create a new custom validation error.
1031 pub fn custom(
1032 location: Location,
1033 instance_path: Location,
1034 instance: &'a Value,
1035 message: impl Into<String>,
1036 ) -> ValidationError<'a> {
1037 Self::borrowed(
1038 instance,
1039 ValidationErrorKind::Custom {
1040 message: message.into(),
1041 },
1042 instance_path,
1043 location,
1044 )
1045 }
1046 }
1047
1048 impl error::Error for ValidationError<'_> {}
1049 impl From<referencing::Error> for ValidationError<'_> {
1050 #[inline]
1051 fn from(err: referencing::Error) -> Self {
1052 ValidationError::new(
1053 Cow::Owned(Value::Null),
1054 ValidationErrorKind::Referencing(err),
1055 Location::new(),
1056 Location::new(),
1057 )
1058 }
1059 }
1060 impl From<FromUtf8Error> for ValidationError<'_> {
1061 #[inline]
1062 fn from(err: FromUtf8Error) -> Self {
1063 ValidationError::from_utf8(err)
1064 }
1065 }
1066
1067 fn write_quoted_list(f: &mut Formatter<'_>, items: &[impl fmt::Display]) -> fmt::Result {
1068 let mut iter = items.iter();
1069 if let Some(item) = iter.next() {
1070 f.write_char('\'')?;
1071 write!(f, "{item}")?;
1072 f.write_char('\'')?;
1073 }
1074 for item in iter {
1075 f.write_str(", ")?;
1076 f.write_char('\'')?;
1077 write!(f, "{item}")?;
1078 f.write_char('\'')?;
1079 }
1080 Ok(())
1081 }
1082
1083 fn write_unexpected_suffix(f: &mut Formatter<'_>, len: usize) -> fmt::Result {
1084 f.write_str(if len == 1 {
1085 " was unexpected)"
1086 } else {
1087 " were unexpected)"
1088 })
1089 }
1090
1091 const MAX_DISPLAYED_ENUM_VARIANTS: usize = 3;
1092
1093 fn write_enum_message(
1094 f: &mut Formatter<'_>,
1095 value: impl fmt::Display,
1096 options: &Value,
1097 ) -> fmt::Result {
1098 let array = options
1099 .as_array()
1100 .expect("Enum options must be a JSON array");
1101
1102 write!(f, "{value} is not one of ")?;
1103
1104 let total_count = array.len();
1105
1106 if total_count <= MAX_DISPLAYED_ENUM_VARIANTS {
1107 // Show all options with proper "a, b or c" formatting
1108 for (i, option) in array.iter().enumerate() {
1109 if i == 0 {
1110 write!(f, "{option}")?;
1111 } else if i == total_count - 1 {
1112 write!(f, " or {option}")?;
1113 } else {
1114 write!(f, ", {option}")?;
1115 }
1116 }
1117 } else {
1118 // Show first few, then "or X other candidates"
1119 let show_count = MAX_DISPLAYED_ENUM_VARIANTS - 1;
1120 for (i, option) in array.iter().take(show_count).enumerate() {
1121 if i == 0 {
1122 write!(f, "{option}")?;
1123 } else {
1124 write!(f, ", {option}")?;
1125 }
1126 }
1127 let remaining = total_count - show_count;
1128 write!(f, " or {remaining} other candidates")?;
1129 }
1130 Ok(())
1131 }
1132
1133 /// Textual representation of various validation errors.
1134 impl fmt::Display for ValidationError<'_> {
1135 #[allow(clippy::too_many_lines)] // The function is long but it does formatting only
1136 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1137 match self.kind() {
1138 ValidationErrorKind::Referencing(error) => error.fmt(f),
1139 ValidationErrorKind::BacktrackLimitExceeded { error } => error.fmt(f),
1140 ValidationErrorKind::Format { format } => {
1141 write!(f, r#"{} is not a "{}""#, self.instance(), format)
1142 }
1143 ValidationErrorKind::AdditionalItems { limit } => {
1144 f.write_str("Additional items are not allowed (")?;
1145 let array = self.instance().as_array().expect("Always valid");
1146 let mut iter = array.iter().skip(*limit);
1147
1148 if let Some(item) = iter.next() {
1149 write!(f, "{item}")?;
1150 }
1151 for item in iter {
1152 f.write_str(", ")?;
1153 write!(f, "{item}")?;
1154 }
1155
1156 write_unexpected_suffix(f, array.len() - limit)
1157 }
1158 ValidationErrorKind::AdditionalProperties { unexpected } => {
1159 f.write_str("Additional properties are not allowed (")?;
1160 write_quoted_list(f, unexpected)?;
1161 write_unexpected_suffix(f, unexpected.len())
1162 }
1163 ValidationErrorKind::AnyOf { context: _ } => write!(
1164 f,
1165 "{} is not valid under any of the schemas listed in the 'anyOf' keyword",
1166 self.instance()
1167 ),
1168 ValidationErrorKind::OneOfNotValid { context: _ } => write!(
1169 f,
1170 "{} is not valid under any of the schemas listed in the 'oneOf' keyword",
1171 self.instance()
1172 ),
1173 ValidationErrorKind::Contains => write!(
1174 f,
1175 "None of {} are valid under the given schema",
1176 self.instance()
1177 ),
1178 ValidationErrorKind::Constant { expected_value } => {
1179 write!(f, "{expected_value} was expected")
1180 }
1181 ValidationErrorKind::ContentEncoding { content_encoding } => {
1182 write!(
1183 f,
1184 r#"{} is not compliant with "{}" content encoding"#,
1185 self.instance(),
1186 content_encoding
1187 )
1188 }
1189 ValidationErrorKind::ContentMediaType { content_media_type } => {
1190 write!(
1191 f,
1192 r#"{} is not compliant with "{}" media type"#,
1193 self.instance(),
1194 content_media_type
1195 )
1196 }
1197 ValidationErrorKind::FromUtf8 { error } => error.fmt(f),
1198 ValidationErrorKind::Enum { options } => {
1199 write_enum_message(f, self.instance(), options)
1200 }
1201 ValidationErrorKind::ExclusiveMaximum { limit } => write!(
1202 f,
1203 "{} is greater than or equal to the maximum of {}",
1204 self.instance(),
1205 limit
1206 ),
1207 ValidationErrorKind::ExclusiveMinimum { limit } => write!(
1208 f,
1209 "{} is less than or equal to the minimum of {}",
1210 self.instance(),
1211 limit
1212 ),
1213 ValidationErrorKind::FalseSchema => {
1214 write!(f, "False schema does not allow {}", self.instance())
1215 }
1216 ValidationErrorKind::Maximum { limit } => write!(
1217 f,
1218 "{} is greater than the maximum of {}",
1219 self.instance(),
1220 limit
1221 ),
1222 ValidationErrorKind::Minimum { limit } => {
1223 write!(
1224 f,
1225 "{} is less than the minimum of {}",
1226 self.instance(),
1227 limit
1228 )
1229 }
1230 ValidationErrorKind::MaxLength { limit } => write!(
1231 f,
1232 "{} is longer than {} character{}",
1233 self.instance(),
1234 limit,
1235 if *limit == 1 { "" } else { "s" }
1236 ),
1237 ValidationErrorKind::MinLength { limit } => write!(
1238 f,
1239 "{} is shorter than {} character{}",
1240 self.instance(),
1241 limit,
1242 if *limit == 1 { "" } else { "s" }
1243 ),
1244 ValidationErrorKind::MaxItems { limit } => write!(
1245 f,
1246 "{} has more than {} item{}",
1247 self.instance(),
1248 limit,
1249 if *limit == 1 { "" } else { "s" }
1250 ),
1251 ValidationErrorKind::MinItems { limit } => write!(
1252 f,
1253 "{} has less than {} item{}",
1254 self.instance(),
1255 limit,
1256 if *limit == 1 { "" } else { "s" }
1257 ),
1258 ValidationErrorKind::MaxProperties { limit } => write!(
1259 f,
1260 "{} has more than {} propert{}",
1261 self.instance(),
1262 limit,
1263 if *limit == 1 { "y" } else { "ies" }
1264 ),
1265 ValidationErrorKind::MinProperties { limit } => write!(
1266 f,
1267 "{} has less than {} propert{}",
1268 self.instance(),
1269 limit,
1270 if *limit == 1 { "y" } else { "ies" }
1271 ),
1272 ValidationErrorKind::Not { schema } => {
1273 write!(f, "{} is not allowed for {}", schema, self.instance())
1274 }
1275 ValidationErrorKind::OneOfMultipleValid { .. } => write!(
1276 f,
1277 "{} is valid under more than one of the schemas listed in the 'oneOf' keyword",
1278 self.instance()
1279 ),
1280 ValidationErrorKind::Pattern { pattern } => {
1281 write!(f, r#"{} does not match "{}""#, self.instance(), pattern)
1282 }
1283 ValidationErrorKind::PropertyNames { error } => error.fmt(f),
1284 ValidationErrorKind::Required { property } => {
1285 write!(f, "{property} is a required property")
1286 }
1287 ValidationErrorKind::MultipleOf { multiple_of } => {
1288 write!(
1289 f,
1290 "{} is not a multiple of {}",
1291 self.instance(),
1292 multiple_of
1293 )
1294 }
1295 ValidationErrorKind::UnevaluatedItems { unexpected } => {
1296 f.write_str("Unevaluated items are not allowed (")?;
1297 write_quoted_list(f, unexpected)?;
1298 write_unexpected_suffix(f, unexpected.len())
1299 }
1300 ValidationErrorKind::UnevaluatedProperties { unexpected } => {
1301 f.write_str("Unevaluated properties are not allowed (")?;
1302 write_quoted_list(f, unexpected)?;
1303 write_unexpected_suffix(f, unexpected.len())
1304 }
1305 ValidationErrorKind::UniqueItems => {
1306 write!(f, "{} has non-unique elements", self.instance())
1307 }
1308 ValidationErrorKind::Type {
1309 kind: TypeKind::Single(type_),
1310 } => write!(f, r#"{} is not of type "{}""#, self.instance(), type_),
1311 ValidationErrorKind::Type {
1312 kind: TypeKind::Multiple(types),
1313 } => {
1314 write!(f, "{} is not of types ", self.instance())?;
1315 let mut iter = types.iter();
1316 if let Some(t) = iter.next() {
1317 f.write_char('"')?;
1318 write!(f, "{t}")?;
1319 f.write_char('"')?;
1320 }
1321 for t in iter {
1322 f.write_str(", ")?;
1323 f.write_char('"')?;
1324 write!(f, "{t}")?;
1325 f.write_char('"')?;
1326 }
1327 Ok(())
1328 }
1329 ValidationErrorKind::Custom { message } => f.write_str(message),
1330 }
1331 }
1332 }
1333
1334 /// A wrapper that provides a masked display of validation errors.
1335 pub struct MaskedValidationError<'a, 'b, 'c> {
1336 error: &'b ValidationError<'a>,
1337 placeholder: Cow<'c, str>,
1338 }
1339
1340 impl fmt::Display for MaskedValidationError<'_, '_, '_> {
1341 #[allow(clippy::too_many_lines)]
1342 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1343 match self.error.kind() {
1344 ValidationErrorKind::Referencing(error) => error.fmt(f),
1345 ValidationErrorKind::BacktrackLimitExceeded { error } => error.fmt(f),
1346 ValidationErrorKind::Format { format } => {
1347 write!(f, r#"{} is not a "{format}""#, self.placeholder)
1348 }
1349 ValidationErrorKind::AdditionalItems { limit } => {
1350 write!(f, "Additional items are not allowed ({limit} items)")
1351 }
1352 ValidationErrorKind::AdditionalProperties { unexpected } => {
1353 f.write_str("Additional properties are not allowed (")?;
1354 write_quoted_list(f, unexpected)?;
1355 write_unexpected_suffix(f, unexpected.len())
1356 }
1357 ValidationErrorKind::AnyOf { .. } => write!(
1358 f,
1359 "{} is not valid under any of the schemas listed in the 'anyOf' keyword",
1360 self.placeholder
1361 ),
1362 ValidationErrorKind::OneOfNotValid { context: _ } => write!(
1363 f,
1364 "{} is not valid under any of the schemas listed in the 'oneOf' keyword",
1365 self.placeholder
1366 ),
1367 ValidationErrorKind::Contains => write!(
1368 f,
1369 "None of {} are valid under the given schema",
1370 self.placeholder
1371 ),
1372 ValidationErrorKind::Constant { expected_value } => {
1373 write!(f, "{expected_value} was expected")
1374 }
1375 ValidationErrorKind::ContentEncoding { content_encoding } => {
1376 write!(
1377 f,
1378 r#"{} is not compliant with "{}" content encoding"#,
1379 self.placeholder, content_encoding
1380 )
1381 }
1382 ValidationErrorKind::ContentMediaType { content_media_type } => {
1383 write!(
1384 f,
1385 r#"{} is not compliant with "{}" media type"#,
1386 self.placeholder, content_media_type
1387 )
1388 }
1389 ValidationErrorKind::FromUtf8 { error } => error.fmt(f),
1390 ValidationErrorKind::Enum { options } => {
1391 write_enum_message(f, &self.placeholder, options)
1392 }
1393 ValidationErrorKind::ExclusiveMaximum { limit } => write!(
1394 f,
1395 "{} is greater than or equal to the maximum of {}",
1396 self.placeholder, limit
1397 ),
1398 ValidationErrorKind::ExclusiveMinimum { limit } => write!(
1399 f,
1400 "{} is less than or equal to the minimum of {}",
1401 self.placeholder, limit
1402 ),
1403 ValidationErrorKind::FalseSchema => {
1404 write!(f, "False schema does not allow {}", self.placeholder)
1405 }
1406 ValidationErrorKind::Maximum { limit } => write!(
1407 f,
1408 "{} is greater than the maximum of {}",
1409 self.placeholder, limit
1410 ),
1411 ValidationErrorKind::Minimum { limit } => {
1412 write!(
1413 f,
1414 "{} is less than the minimum of {}",
1415 self.placeholder, limit
1416 )
1417 }
1418 ValidationErrorKind::MaxLength { limit } => write!(
1419 f,
1420 "{} is longer than {} character{}",
1421 self.placeholder,
1422 limit,
1423 if *limit == 1 { "" } else { "s" }
1424 ),
1425 ValidationErrorKind::MinLength { limit } => write!(
1426 f,
1427 "{} is shorter than {} character{}",
1428 self.placeholder,
1429 limit,
1430 if *limit == 1 { "" } else { "s" }
1431 ),
1432 ValidationErrorKind::MaxItems { limit } => write!(
1433 f,
1434 "{} has more than {} item{}",
1435 self.placeholder,
1436 limit,
1437 if *limit == 1 { "" } else { "s" }
1438 ),
1439 ValidationErrorKind::MinItems { limit } => write!(
1440 f,
1441 "{} has less than {} item{}",
1442 self.placeholder,
1443 limit,
1444 if *limit == 1 { "" } else { "s" }
1445 ),
1446 ValidationErrorKind::MaxProperties { limit } => write!(
1447 f,
1448 "{} has more than {} propert{}",
1449 self.placeholder,
1450 limit,
1451 if *limit == 1 { "y" } else { "ies" }
1452 ),
1453 ValidationErrorKind::MinProperties { limit } => write!(
1454 f,
1455 "{} has less than {} propert{}",
1456 self.placeholder,
1457 limit,
1458 if *limit == 1 { "y" } else { "ies" }
1459 ),
1460 ValidationErrorKind::Not { schema } => {
1461 write!(f, "{} is not allowed for {}", schema, self.placeholder)
1462 }
1463 ValidationErrorKind::OneOfMultipleValid { .. } => write!(
1464 f,
1465 "{} is valid under more than one of the schemas listed in the 'oneOf' keyword",
1466 self.placeholder
1467 ),
1468 ValidationErrorKind::Pattern { pattern } => {
1469 write!(f, r#"{} does not match "{}""#, self.placeholder, pattern)
1470 }
1471 ValidationErrorKind::PropertyNames { error } => error.fmt(f),
1472 ValidationErrorKind::Required { property } => {
1473 write!(f, "{property} is a required property")
1474 }
1475 ValidationErrorKind::MultipleOf { multiple_of } => {
1476 write!(
1477 f,
1478 "{} is not a multiple of {}",
1479 self.placeholder, multiple_of
1480 )
1481 }
1482 ValidationErrorKind::UnevaluatedItems { unexpected } => {
1483 write!(
1484 f,
1485 "Unevaluated items are not allowed ({} items)",
1486 unexpected.len()
1487 )
1488 }
1489 ValidationErrorKind::UnevaluatedProperties { unexpected } => {
1490 f.write_str("Unevaluated properties are not allowed (")?;
1491 write_quoted_list(f, unexpected)?;
1492 write_unexpected_suffix(f, unexpected.len())
1493 }
1494 ValidationErrorKind::UniqueItems => {
1495 write!(f, "{} has non-unique elements", self.placeholder)
1496 }
1497 ValidationErrorKind::Type {
1498 kind: TypeKind::Single(type_),
1499 } => write!(f, r#"{} is not of type "{}""#, self.placeholder, type_),
1500 ValidationErrorKind::Type {
1501 kind: TypeKind::Multiple(types),
1502 } => {
1503 write!(f, "{} is not of types ", self.placeholder)?;
1504 let mut iter = types.iter();
1505 if let Some(t) = iter.next() {
1506 f.write_char('"')?;
1507 write!(f, "{t}")?;
1508 f.write_char('"')?;
1509 }
1510 for t in iter {
1511 f.write_str(", ")?;
1512 f.write_char('"')?;
1513 write!(f, "{t}")?;
1514 f.write_char('"')?;
1515 }
1516 Ok(())
1517 }
1518 ValidationErrorKind::Custom { message } => f.write_str(message),
1519 }
1520 }
1521 }
1522
1523 #[cfg(test)]
1524 mod tests {
1525 use super::*;
1526 use serde_json::json;
1527
1528 use test_case::test_case;
1529
1530 fn owned_error(instance: Value, kind: ValidationErrorKind) -> ValidationError<'static> {
1531 ValidationError::new(Cow::Owned(instance), kind, Location::new(), Location::new())
1532 }
1533
1534 #[test]
1535 fn error_iterator_into_errors_collects_all_errors() {
1536 let iterator = ErrorIterator::from_iterator(
1537 vec![
1538 owned_error(json!(1), ValidationErrorKind::Minimum { limit: json!(2) }),
1539 owned_error(json!(3), ValidationErrorKind::Maximum { limit: json!(2) }),
1540 ]
1541 .into_iter(),
1542 );
1543 let validation_errors = iterator.into_errors();
1544 let collected: Vec<_> = validation_errors.into_iter().collect();
1545 assert_eq!(collected.len(), 2);
1546 assert_eq!(collected[0].to_string(), "1 is less than the minimum of 2");
1547 assert_eq!(
1548 collected[1].to_string(),
1549 "3 is greater than the maximum of 2"
1550 );
1551 }
1552
1553 #[test]
1554 fn validation_errors_display_reports_success() {
1555 let errors = ValidationErrors { errors: Vec::new() };
1556 assert_eq!(format!("{errors}"), "Validation succeeded");
1557 }
1558
1559 #[test]
1560 fn validation_errors_display_lists_messages() {
1561 let errors = ValidationErrors {
1562 errors: vec![
1563 owned_error(json!(1), ValidationErrorKind::Minimum { limit: json!(2) }),
1564 owned_error(json!(3), ValidationErrorKind::Maximum { limit: json!(2) }),
1565 ],
1566 };
1567 let rendered = format!("{errors}");
1568 assert!(rendered.contains("Validation errors:"));
1569 assert!(rendered.contains("01: 1 is less than the minimum of 2"));
1570 assert!(rendered.contains("02: 3 is greater than the maximum of 2"));
1571 }
1572
1573 #[test]
1574 fn validation_errors_len_and_is_empty() {
1575 let empty = ValidationErrors { errors: vec![] };
1576 assert_eq!(empty.len(), 0);
1577 assert!(empty.is_empty());
1578
1579 let errors = ValidationErrors {
1580 errors: vec![owned_error(
1581 json!(1),
1582 ValidationErrorKind::Minimum { limit: json!(2) },
1583 )],
1584 };
1585 assert_eq!(errors.len(), 1);
1586 assert!(!errors.is_empty());
1587 }
1588
1589 #[test]
1590 fn validation_errors_as_slice() {
1591 let errors = ValidationErrors {
1592 errors: vec![
1593 owned_error(json!(1), ValidationErrorKind::Minimum { limit: json!(2) }),
1594 owned_error(json!(3), ValidationErrorKind::Maximum { limit: json!(2) }),
1595 ],
1596 };
1597
1598 let slice = errors.as_slice();
1599 assert_eq!(slice.len(), 2);
1600 assert_eq!(slice[0].to_string(), "1 is less than the minimum of 2");
1601 assert_eq!(slice[1].to_string(), "3 is greater than the maximum of 2");
1602 }
1603
1604 #[test]
1605 fn validation_errors_iter() {
1606 let errors = ValidationErrors {
1607 errors: vec![
1608 owned_error(json!(1), ValidationErrorKind::Minimum { limit: json!(2) }),
1609 owned_error(json!(3), ValidationErrorKind::Maximum { limit: json!(2) }),
1610 ],
1611 };
1612
1613 let collected: Vec<_> = errors.iter().map(ValidationError::to_string).collect();
1614 assert_eq!(collected.len(), 2);
1615 assert_eq!(collected[0], "1 is less than the minimum of 2");
1616 assert_eq!(collected[1], "3 is greater than the maximum of 2");
1617 }
1618
1619 #[test]
1620 #[allow(clippy::explicit_iter_loop)]
1621 fn validation_errors_iter_mut() {
1622 let mut errors = ValidationErrors {
1623 errors: vec![owned_error(
1624 json!(1),
1625 ValidationErrorKind::Minimum { limit: json!(2) },
1626 )],
1627 };
1628
1629 // Verify we can get mutable references via iter_mut()
1630 for error in errors.iter_mut() {
1631 let _ = error.to_string();
1632 }
1633 }
1634
1635 #[test]
1636 fn validation_errors_into_iterator_by_ref() {
1637 let errors = ValidationErrors {
1638 errors: vec![owned_error(
1639 json!(1),
1640 ValidationErrorKind::Minimum { limit: json!(2) },
1641 )],
1642 };
1643
1644 let collected: Vec<_> = (&errors).into_iter().collect();
1645 assert_eq!(collected.len(), 1);
1646 // Verify errors is still usable
1647 assert_eq!(errors.len(), 1);
1648 }
1649
1650 #[test]
1651 fn validation_errors_into_iterator_by_mut_ref() {
1652 let mut errors = ValidationErrors {
1653 errors: vec![owned_error(
1654 json!(1),
1655 ValidationErrorKind::Minimum { limit: json!(2) },
1656 )],
1657 };
1658
1659 let collected: Vec<_> = (&mut errors).into_iter().collect();
1660 assert_eq!(collected.len(), 1);
1661 // Verify errors is still usable
1662 assert_eq!(errors.len(), 1);
1663 }
1664
1665 #[test]
1666 fn error_iterator_size_hint() {
1667 let vec = vec![
1668 owned_error(json!(1), ValidationErrorKind::Minimum { limit: json!(2) }),
1669 owned_error(json!(3), ValidationErrorKind::Maximum { limit: json!(2) }),
1670 ];
1671 let iterator = ErrorIterator::from_iterator(vec.into_iter());
1672 let (lower, upper) = iterator.size_hint();
1673 assert_eq!(lower, 2);
1674 assert_eq!(upper, Some(2));
1675 }
1676
1677 #[test]
1678 fn validation_errors_debug() {
1679 let errors = ValidationErrors {
1680 errors: vec![owned_error(
1681 json!(1),
1682 ValidationErrorKind::Minimum { limit: json!(2) },
1683 )],
1684 };
1685 let debug_output = format!("{errors:?}");
1686 assert!(debug_output.contains("ValidationErrors"));
1687 assert!(debug_output.contains("errors"));
1688 }
1689
1690 #[test]
1691 fn single_type_error() {
1692 let instance = json!(42);
1693 let err = ValidationError::single_type_error(
1694 Location::new(),
1695 Location::new(),
1696 &instance,
1697 JsonType::String,
1698 );
1699 assert_eq!(err.to_string(), r#"42 is not of type "string""#);
1700 }
1701
1702 #[test]
1703 fn multiple_types_error() {
1704 let instance = json!(42);
1705 let types = JsonTypeSet::empty()
1706 .insert(JsonType::String)
1707 .insert(JsonType::Number);
1708 let err = ValidationError::multiple_type_error(
1709 Location::new(),
1710 Location::new(),
1711 &instance,
1712 types,
1713 );
1714 assert_eq!(err.to_string(), r#"42 is not of types "number", "string""#);
1715 }
1716
1717 #[test_case(true, &json!({"foo": {"bar": 42}}), "/foo/bar")]
1718 #[test_case(true, &json!({"foo": "a"}), "/foo")]
1719 #[test_case(false, &json!({"foo": {"bar": 42}}), "/foo/bar")]
1720 #[test_case(false, &json!({"foo": "a"}), "/foo")]
1721 fn instance_path_properties(additional_properties: bool, instance: &Value, expected: &str) {
1722 let schema = json!(
1723 {
1724 "additionalProperties": additional_properties,
1725 "type":"object",
1726 "properties":{
1727 "foo":{
1728 "type":"object",
1729 "properties":{
1730 "bar":{
1731 "type":"string"
1732 }
1733 }
1734 }
1735 }
1736 }
1737 );
1738 let validator = crate::validator_for(&schema).unwrap();
1739 let mut result = validator.iter_errors(instance);
1740 let error = result.next().expect("validation error");
1741
1742 assert!(result.next().is_none());
1743 assert_eq!(error.instance_path().as_str(), expected);
1744 }
1745
1746 #[test_case(true, &json!([1, {"foo": ["42"]}]), "/0")]
1747 #[test_case(true, &json!(["a", {"foo": [42]}]), "/1/foo/0")]
1748 #[test_case(false, &json!([1, {"foo": ["42"]}]), "/0")]
1749 #[test_case(false, &json!(["a", {"foo": [42]}]), "/1/foo/0")]
1750 fn instance_path_properties_and_arrays(
1751 additional_items: bool,
1752 instance: &Value,
1753 expected: &str,
1754 ) {
1755 let schema = json!(
1756 {
1757 "items": additional_items,
1758 "type": "array",
1759 "prefixItems": [
1760 {
1761 "type": "string"
1762 },
1763 {
1764 "type": "object",
1765 "properties": {
1766 "foo": {
1767 "type": "array",
1768 "prefixItems": [
1769 {
1770 "type": "string"
1771 }
1772 ]
1773 }
1774 }
1775 }
1776 ]
1777 }
1778 );
1779 let validator = crate::validator_for(&schema).unwrap();
1780 let mut result = validator.iter_errors(instance);
1781 let error = result.next().expect("validation error");
1782
1783 assert!(result.next().is_none());
1784 assert_eq!(error.instance_path().as_str(), expected);
1785 }
1786
1787 #[test_case(true, &json!([[1, 2, 3], [4, "5", 6], [7, 8, 9]]), "/1/1")]
1788 #[test_case(false, &json!([[1, 2, 3], [4, "5", 6], [7, 8, 9]]), "/1/1")]
1789 #[test_case(true, &json!([[1, 2, 3], [4, 5, 6], 42]), "/2")]
1790 #[test_case(false, &json!([[1, 2, 3], [4, 5, 6], 42]), "/2")]
1791 fn instance_path_nested_arrays(additional_items: bool, instance: &Value, expected: &str) {
1792 let schema = json!(
1793 {
1794 "additionalItems": additional_items,
1795 "type": "array",
1796 "items": {
1797 "type": "array",
1798 "items": {
1799 "type": "integer"
1800 }
1801 }
1802 }
1803 );
1804 let validator = crate::validator_for(&schema).unwrap();
1805 let mut result = validator.iter_errors(instance);
1806 let error = result.next().expect("validation error");
1807
1808 assert!(result.next().is_none());
1809 assert_eq!(error.instance_path().as_str(), expected);
1810 }
1811
1812 #[test_case(true, &json!([1, "a"]), "/1")]
1813 #[test_case(false, &json!([1, "a"]), "/1")]
1814 #[test_case(true, &json!(123), "")]
1815 #[test_case(false, &json!(123), "")]
1816 fn instance_path_arrays(additional_items: bool, instance: &Value, expected: &str) {
1817 let schema = json!(
1818 {
1819 "additionalItems": additional_items,
1820 "type": "array",
1821 "items": {
1822 "type": "integer"
1823 }
1824 }
1825 );
1826 let validator = crate::validator_for(&schema).unwrap();
1827 let mut result = validator.iter_errors(instance);
1828 let error = result.next().expect("validation error");
1829
1830 assert!(result.next().is_none());
1831 assert_eq!(error.instance_path().as_str(), expected);
1832 }
1833
1834 #[test_case(
1835 json!("2023-13-45"),
1836 ValidationErrorKind::Format {
1837 format: "date".to_string(),
1838 },
1839 "value is not a \"date\""
1840 )]
1841 #[test_case(
1842 json!("sensitive data"),
1843 ValidationErrorKind::MaxLength { limit: 5 },
1844 "value is longer than 5 characters"
1845 )]
1846 #[test_case(
1847 json!({"secret": "data", "key": "value"}),
1848 ValidationErrorKind::AdditionalProperties {
1849 unexpected: vec!["secret".to_string(), "key".to_string()]
1850 },
1851 "Additional properties are not allowed ('secret', 'key' were unexpected)"
1852 )]
1853 #[test_case(
1854 json!(123),
1855 ValidationErrorKind::Minimum { limit: json!(456) },
1856 "value is less than the minimum of 456"
1857 )]
1858 #[test_case(
1859 json!("secret_key_123"),
1860 ValidationErrorKind::Pattern {
1861 pattern: "^[A-Z0-9]{32}$".to_string(),
1862 },
1863 "value does not match \"^[A-Z0-9]{32}$\""
1864 )]
1865 #[test_case(
1866 json!([1, 2, 2, 3]),
1867 ValidationErrorKind::UniqueItems,
1868 "value has non-unique elements"
1869 )]
1870 #[test_case(
1871 json!(123),
1872 ValidationErrorKind::Type { kind: TypeKind::Single(JsonType::String) },
1873 "value is not of type \"string\""
1874 )]
1875 fn test_masked_error_messages(instance: Value, kind: ValidationErrorKind, expected: &str) {
1876 let error =
1877 ValidationError::new(Cow::Owned(instance), kind, Location::new(), Location::new());
1878 assert_eq!(error.masked().to_string(), expected);
1879 }
1880
1881 #[test_case(
1882 json!("sensitive data"),
1883 ValidationErrorKind::MaxLength { limit: 5 },
1884 "[REDACTED]",
1885 "[REDACTED] is longer than 5 characters"
1886 )]
1887 #[test_case(
1888 json!({"password": "secret123"}),
1889 ValidationErrorKind::Type {
1890 kind: TypeKind::Single(JsonType::String)
1891 },
1892 "***",
1893 "*** is not of type \"string\""
1894 )]
1895 fn test_custom_masked_error_messages(
1896 instance: Value,
1897 kind: ValidationErrorKind,
1898 placeholder: &str,
1899 expected: &str,
1900 ) {
1901 let error =
1902 ValidationError::new(Cow::Owned(instance), kind, Location::new(), Location::new());
1903 assert_eq!(error.masked_with(placeholder).to_string(), expected);
1904 }
1905 }