1use std::cell::RefCell;
38use std::collections::HashMap;
39
40use stillwater::Validation;
41
42use crate::error::{ConfigError, ConfigErrors, ConfigValidation, SourceLocation};
43
44pub type SourceLocationMap = HashMap<String, SourceLocation>;
50
51#[derive(Debug, Default)]
58pub struct ValidationContext {
59 locations: SourceLocationMap,
60}
61
62impl ValidationContext {
63 pub fn new(locations: SourceLocationMap) -> Self {
65 Self { locations }
66 }
67
68 pub fn location_for(&self, path: &str) -> Option<&SourceLocation> {
70 self.locations.get(path)
71 }
72}
73
74thread_local! {
78 static VALIDATION_CONTEXT: RefCell<Option<ValidationContext>> = const { RefCell::new(None) };
79 static PATH_PREFIX: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
80}
81
82pub fn with_validation_context<F, R>(ctx: ValidationContext, f: F) -> R
87where
88 F: FnOnce() -> R,
89{
90 VALIDATION_CONTEXT.with(|cell| {
91 *cell.borrow_mut() = Some(ctx);
92 });
93 let result = f();
94 VALIDATION_CONTEXT.with(|cell| {
95 *cell.borrow_mut() = None;
96 });
97 result
98}
99
100pub fn current_source_location(path: &str) -> Option<SourceLocation> {
108 let full_path = PATH_PREFIX.with(|cell| {
110 let prefixes = cell.borrow();
111 if prefixes.is_empty() {
112 path.to_string()
113 } else {
114 format!("{}.{}", prefixes.join("."), path)
115 }
116 });
117
118 VALIDATION_CONTEXT.with(|cell| {
119 cell.borrow()
120 .as_ref()
121 .and_then(|ctx| ctx.location_for(&full_path).cloned())
122 })
123}
124
125pub fn push_path_prefix(prefix: &str) {
129 PATH_PREFIX.with(|cell| {
130 cell.borrow_mut().push(prefix.to_string());
131 });
132}
133
134pub fn pop_path_prefix() {
136 PATH_PREFIX.with(|cell| {
137 cell.borrow_mut().pop();
138 });
139}
140
141pub trait Validate {
153 fn validate(&self) -> ConfigValidation<()>;
158
159 fn validate_at(&self, path: &str) -> ConfigValidation<()> {
176 push_path_prefix(path);
178 let result = self.validate();
179 pop_path_prefix();
180
181 result.map_err(|errors| errors.with_path_prefix(path))
182 }
183}
184
185impl Validate for () {
190 fn validate(&self) -> ConfigValidation<()> {
191 Validation::Success(())
192 }
193}
194
195impl<T: Validate> Validate for Option<T> {
199 fn validate(&self) -> ConfigValidation<()> {
200 match self {
201 Some(inner) => inner.validate(),
202 None => Validation::Success(()),
203 }
204 }
205}
206
207impl<T: Validate> Validate for Vec<T> {
211 fn validate(&self) -> ConfigValidation<()> {
212 if self.is_empty() {
213 return Validation::Success(());
214 }
215
216 let validations: Vec<ConfigValidation<()>> = self
218 .iter()
219 .enumerate()
220 .map(|(i, item)| item.validate_at(&format!("[{}]", i)))
221 .collect();
222 Validation::all_vec(validations).map(|_| ())
223 }
224}
225
226macro_rules! impl_validate_noop {
228 ($($t:ty),*) => {
229 $(
230 impl Validate for $t {
231 fn validate(&self) -> ConfigValidation<()> {
232 Validation::Success(())
233 }
234 }
235 )*
236 };
237}
238
239impl_validate_noop!(
240 bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, char, String
241);
242
243impl Validate for &str {
244 fn validate(&self) -> ConfigValidation<()> {
245 Validation::Success(())
246 }
247}
248
249impl Validate for std::path::PathBuf {
250 fn validate(&self) -> ConfigValidation<()> {
251 Validation::Success(())
252 }
253}
254
255pub trait Validator<T: ?Sized> {
268 fn validate(&self, value: &T, path: &str) -> ConfigValidation<()>;
273}
274
275fn fail(error: ConfigError) -> ConfigValidation<()> {
277 Validation::Failure(ConfigErrors::single(error))
278}
279
280use stillwater::predicate::Predicate;
285
286pub fn from_predicate<T>(predicate: impl Predicate<T>) -> impl Validator<T>
305where
306 T: ?Sized,
307{
308 PredicateValidator(predicate)
309}
310
311struct PredicateValidator<P>(P);
313
314impl<T, P> Validator<T> for PredicateValidator<P>
315where
316 T: ?Sized,
317 P: Predicate<T>,
318{
319 fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
320 if self.0.check(value) {
321 Validation::Success(())
322 } else {
323 let source_location = current_source_location(path);
325
326 Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
327 path: path.to_string(),
328 source_location,
329 value: None, message: "validation failed".to_string(),
331 }))
332 }
333 }
334}
335
336pub fn validate_with_predicate<T>(
355 value: &T,
356 path: &str,
357 predicate: impl Predicate<T>,
358 message: impl Into<String>,
359) -> ConfigValidation<()>
360where
361 T: ?Sized,
362{
363 if predicate.check(value) {
364 Validation::Success(())
365 } else {
366 let source_location = current_source_location(path);
367
368 Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
369 path: path.to_string(),
370 source_location,
371 value: None,
372 message: message.into(),
373 }))
374 }
375}
376
377pub fn validate_field<T>(
394 value: &T,
395 path: &str,
396 validators: &[&dyn Validator<T>],
397) -> ConfigValidation<()>
398where
399 T: ?Sized,
400{
401 if validators.is_empty() {
402 return Validation::Success(());
403 }
404
405 let results: Vec<ConfigValidation<()>> =
406 validators.iter().map(|v| v.validate(value, path)).collect();
407
408 Validation::all_vec(results).map(|_| ())
409}
410
411pub fn validate_nested<T: Validate>(value: &T, path: &str) -> ConfigValidation<()> {
415 value.validate_at(path)
416}
417
418pub fn validate_optional_nested<T: Validate>(
422 value: &Option<T>,
423 path: &str,
424) -> ConfigValidation<()> {
425 match value {
426 Some(v) => v.validate_at(path),
427 None => Validation::Success(()),
428 }
429}
430
431pub mod validators {
440 use super::*;
441 use std::fmt::Display;
442 use std::ops::RangeInclusive;
443 use std::path::Path;
444
445 #[derive(Debug, Clone, Copy)]
451 pub struct NonEmpty;
452
453 impl Validator<str> for NonEmpty {
454 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
455 if value.is_empty() {
456 fail(ConfigError::ValidationError {
457 path: path.to_string(),
458 source_location: None,
459 value: Some(String::new()),
460 message: "value cannot be empty".to_string(),
461 })
462 } else {
463 Validation::Success(())
464 }
465 }
466 }
467
468 impl Validator<String> for NonEmpty {
469 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
470 <NonEmpty as Validator<str>>::validate(self, value.as_str(), path)
471 }
472 }
473
474 #[derive(Debug, Clone, Copy)]
476 pub struct MinLength(pub usize);
477
478 impl Validator<str> for MinLength {
479 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
480 if value.len() < self.0 {
481 fail(ConfigError::ValidationError {
482 path: path.to_string(),
483 source_location: None,
484 value: Some(value.to_string()),
485 message: format!("length {} is less than minimum {}", value.len(), self.0),
486 })
487 } else {
488 Validation::Success(())
489 }
490 }
491 }
492
493 impl Validator<String> for MinLength {
494 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
495 <MinLength as Validator<str>>::validate(self, value.as_str(), path)
496 }
497 }
498
499 #[derive(Debug, Clone, Copy)]
501 pub struct MaxLength(pub usize);
502
503 impl Validator<str> for MaxLength {
504 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
505 if value.len() > self.0 {
506 fail(ConfigError::ValidationError {
507 path: path.to_string(),
508 source_location: None,
509 value: Some(value.to_string()),
510 message: format!("length {} exceeds maximum {}", value.len(), self.0),
511 })
512 } else {
513 Validation::Success(())
514 }
515 }
516 }
517
518 impl Validator<String> for MaxLength {
519 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
520 <MaxLength as Validator<str>>::validate(self, value.as_str(), path)
521 }
522 }
523
524 #[derive(Debug, Clone)]
526 pub struct Length(pub RangeInclusive<usize>);
527
528 impl Validator<str> for Length {
529 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
530 let len = value.len();
531 if !self.0.contains(&len) {
532 fail(ConfigError::ValidationError {
533 path: path.to_string(),
534 source_location: None,
535 value: Some(value.to_string()),
536 message: format!(
537 "length {} is not in range {}..={}",
538 len,
539 self.0.start(),
540 self.0.end()
541 ),
542 })
543 } else {
544 Validation::Success(())
545 }
546 }
547 }
548
549 impl Validator<String> for Length {
550 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
551 <Length as Validator<str>>::validate(self, value.as_str(), path)
552 }
553 }
554
555 #[derive(Debug, Clone)]
560 pub struct Pattern(pub String);
561
562 impl Pattern {
563 pub fn new(pattern: impl Into<String>) -> Self {
565 Self(pattern.into())
566 }
567 }
568
569 impl Validator<str> for Pattern {
570 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
571 match regex::Regex::new(&self.0) {
573 Ok(re) => {
574 if re.is_match(value) {
575 Validation::Success(())
576 } else {
577 fail(ConfigError::ValidationError {
578 path: path.to_string(),
579 source_location: None,
580 value: Some(value.to_string()),
581 message: format!("value does not match pattern '{}'", self.0),
582 })
583 }
584 }
585 Err(e) => fail(ConfigError::ValidationError {
586 path: path.to_string(),
587 source_location: None,
588 value: Some(value.to_string()),
589 message: format!("invalid pattern '{}': {}", self.0, e),
590 }),
591 }
592 }
593 }
594
595 impl Validator<String> for Pattern {
596 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
597 <Pattern as Validator<str>>::validate(self, value.as_str(), path)
598 }
599 }
600
601 #[derive(Debug, Clone, Copy)]
606 pub struct Email;
607
608 impl Validator<str> for Email {
609 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
610 let email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
613 let re = regex::Regex::new(email_pattern).expect("valid email regex");
614
615 if re.is_match(value) {
616 Validation::Success(())
617 } else {
618 fail(ConfigError::ValidationError {
619 path: path.to_string(),
620 source_location: None,
621 value: Some(value.to_string()),
622 message: "value is not a valid email address".to_string(),
623 })
624 }
625 }
626 }
627
628 impl Validator<String> for Email {
629 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
630 <Email as Validator<str>>::validate(self, value.as_str(), path)
631 }
632 }
633
634 #[derive(Debug, Clone, Copy)]
636 pub struct Url;
637
638 impl Validator<str> for Url {
639 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
640 let url_pattern = r"^(https?|ftp)://[^\s/$.?#].[^\s]*$";
642 let re = regex::Regex::new(url_pattern).expect("valid url regex");
643
644 if re.is_match(value) {
645 Validation::Success(())
646 } else {
647 fail(ConfigError::ValidationError {
648 path: path.to_string(),
649 source_location: None,
650 value: Some(value.to_string()),
651 message: "value is not a valid URL".to_string(),
652 })
653 }
654 }
655 }
656
657 impl Validator<String> for Url {
658 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
659 <Url as Validator<str>>::validate(self, value.as_str(), path)
660 }
661 }
662
663 #[derive(Debug, Clone)]
669 pub struct Range<T>(pub RangeInclusive<T>);
670
671 impl<T> Validator<T> for Range<T>
672 where
673 T: PartialOrd + Display + Clone,
674 {
675 fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
676 if !self.0.contains(value) {
677 fail(ConfigError::ValidationError {
678 path: path.to_string(),
679 source_location: None,
680 value: Some(value.to_string()),
681 message: format!(
682 "value {} is not in range {}..={}",
683 value,
684 self.0.start(),
685 self.0.end()
686 ),
687 })
688 } else {
689 Validation::Success(())
690 }
691 }
692 }
693
694 #[derive(Debug, Clone, Copy)]
696 pub struct Positive;
697
698 macro_rules! impl_positive_for_signed {
699 ($($t:ty),*) => {
700 $(
701 impl Validator<$t> for Positive {
702 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
703 if *value > 0 {
704 Validation::Success(())
705 } else {
706 fail(ConfigError::ValidationError {
707 path: path.to_string(),
708 source_location: None,
709 value: Some(value.to_string()),
710 message: "value must be positive".to_string(),
711 })
712 }
713 }
714 }
715 )*
716 };
717 }
718
719 macro_rules! impl_positive_for_unsigned {
720 ($($t:ty),*) => {
721 $(
722 impl Validator<$t> for Positive {
723 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
724 if *value > 0 {
725 Validation::Success(())
726 } else {
727 fail(ConfigError::ValidationError {
728 path: path.to_string(),
729 source_location: None,
730 value: Some(value.to_string()),
731 message: "value must be positive".to_string(),
732 })
733 }
734 }
735 }
736 )*
737 };
738 }
739
740 macro_rules! impl_positive_for_float {
741 ($($t:ty),*) => {
742 $(
743 impl Validator<$t> for Positive {
744 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
745 if *value > 0.0 {
746 Validation::Success(())
747 } else {
748 fail(ConfigError::ValidationError {
749 path: path.to_string(),
750 source_location: None,
751 value: Some(value.to_string()),
752 message: "value must be positive".to_string(),
753 })
754 }
755 }
756 }
757 )*
758 };
759 }
760
761 impl_positive_for_signed!(i8, i16, i32, i64, i128, isize);
762 impl_positive_for_unsigned!(u8, u16, u32, u64, u128, usize);
763 impl_positive_for_float!(f32, f64);
764
765 #[derive(Debug, Clone, Copy)]
767 pub struct Negative;
768
769 macro_rules! impl_negative_for_signed {
770 ($($t:ty),*) => {
771 $(
772 impl Validator<$t> for Negative {
773 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
774 if *value < 0 {
775 Validation::Success(())
776 } else {
777 fail(ConfigError::ValidationError {
778 path: path.to_string(),
779 source_location: None,
780 value: Some(value.to_string()),
781 message: "value must be negative".to_string(),
782 })
783 }
784 }
785 }
786 )*
787 };
788 }
789
790 macro_rules! impl_negative_for_float {
791 ($($t:ty),*) => {
792 $(
793 impl Validator<$t> for Negative {
794 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
795 if *value < 0.0 {
796 Validation::Success(())
797 } else {
798 fail(ConfigError::ValidationError {
799 path: path.to_string(),
800 source_location: None,
801 value: Some(value.to_string()),
802 message: "value must be negative".to_string(),
803 })
804 }
805 }
806 }
807 )*
808 };
809 }
810
811 impl_negative_for_signed!(i8, i16, i32, i64, i128, isize);
812 impl_negative_for_float!(f32, f64);
813
814 #[derive(Debug, Clone, Copy)]
816 pub struct NonZero;
817
818 macro_rules! impl_nonzero_for_int {
819 ($($t:ty),*) => {
820 $(
821 impl Validator<$t> for NonZero {
822 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
823 if *value != 0 {
824 Validation::Success(())
825 } else {
826 fail(ConfigError::ValidationError {
827 path: path.to_string(),
828 source_location: None,
829 value: Some(value.to_string()),
830 message: "value cannot be zero".to_string(),
831 })
832 }
833 }
834 }
835 )*
836 };
837 }
838
839 macro_rules! impl_nonzero_for_float {
840 ($($t:ty),*) => {
841 $(
842 impl Validator<$t> for NonZero {
843 fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
844 #[allow(clippy::float_cmp)]
845 if *value != 0.0 {
846 Validation::Success(())
847 } else {
848 fail(ConfigError::ValidationError {
849 path: path.to_string(),
850 source_location: None,
851 value: Some(value.to_string()),
852 message: "value cannot be zero".to_string(),
853 })
854 }
855 }
856 }
857 )*
858 };
859 }
860
861 impl_nonzero_for_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
862 impl_nonzero_for_float!(f32, f64);
863
864 #[derive(Debug, Clone, Copy)]
870 pub struct NonEmptyCollection;
871
872 impl<T> Validator<Vec<T>> for NonEmptyCollection {
873 fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
874 if value.is_empty() {
875 fail(ConfigError::ValidationError {
876 path: path.to_string(),
877 source_location: None,
878 value: Some("[]".to_string()),
879 message: "collection cannot be empty".to_string(),
880 })
881 } else {
882 Validation::Success(())
883 }
884 }
885 }
886
887 impl<T> Validator<[T]> for NonEmptyCollection {
888 fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
889 if value.is_empty() {
890 fail(ConfigError::ValidationError {
891 path: path.to_string(),
892 source_location: None,
893 value: Some("[]".to_string()),
894 message: "collection cannot be empty".to_string(),
895 })
896 } else {
897 Validation::Success(())
898 }
899 }
900 }
901
902 #[derive(Debug, Clone, Copy)]
904 pub struct MinItems(pub usize);
905
906 impl<T> Validator<Vec<T>> for MinItems {
907 fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
908 if value.len() < self.0 {
909 fail(ConfigError::ValidationError {
910 path: path.to_string(),
911 source_location: None,
912 value: Some(format!("[{} items]", value.len())),
913 message: format!(
914 "collection has {} items, minimum is {}",
915 value.len(),
916 self.0
917 ),
918 })
919 } else {
920 Validation::Success(())
921 }
922 }
923 }
924
925 impl<T> Validator<[T]> for MinItems {
926 fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
927 if value.len() < self.0 {
928 fail(ConfigError::ValidationError {
929 path: path.to_string(),
930 source_location: None,
931 value: Some(format!("[{} items]", value.len())),
932 message: format!(
933 "collection has {} items, minimum is {}",
934 value.len(),
935 self.0
936 ),
937 })
938 } else {
939 Validation::Success(())
940 }
941 }
942 }
943
944 #[derive(Debug, Clone, Copy)]
946 pub struct MaxItems(pub usize);
947
948 impl<T> Validator<Vec<T>> for MaxItems {
949 fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
950 if value.len() > self.0 {
951 fail(ConfigError::ValidationError {
952 path: path.to_string(),
953 source_location: None,
954 value: Some(format!("[{} items]", value.len())),
955 message: format!(
956 "collection has {} items, maximum is {}",
957 value.len(),
958 self.0
959 ),
960 })
961 } else {
962 Validation::Success(())
963 }
964 }
965 }
966
967 impl<T> Validator<[T]> for MaxItems {
968 fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
969 if value.len() > self.0 {
970 fail(ConfigError::ValidationError {
971 path: path.to_string(),
972 source_location: None,
973 value: Some(format!("[{} items]", value.len())),
974 message: format!(
975 "collection has {} items, maximum is {}",
976 value.len(),
977 self.0
978 ),
979 })
980 } else {
981 Validation::Success(())
982 }
983 }
984 }
985
986 #[derive(Debug, Clone)]
990 pub struct Each<V>(pub V);
991
992 impl<V, T> Validator<Vec<T>> for Each<V>
993 where
994 V: Validator<T>,
995 {
996 fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
997 if value.is_empty() {
998 return Validation::Success(());
999 }
1000
1001 let results: Vec<ConfigValidation<()>> = value
1002 .iter()
1003 .enumerate()
1004 .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
1005 .collect();
1006
1007 Validation::all_vec(results).map(|_| ())
1008 }
1009 }
1010
1011 impl<V, T> Validator<[T]> for Each<V>
1012 where
1013 V: Validator<T>,
1014 {
1015 fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
1016 if value.is_empty() {
1017 return Validation::Success(());
1018 }
1019
1020 let results: Vec<ConfigValidation<()>> = value
1021 .iter()
1022 .enumerate()
1023 .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
1024 .collect();
1025
1026 Validation::all_vec(results).map(|_| ())
1027 }
1028 }
1029
1030 #[derive(Debug, Clone, Copy)]
1040 pub struct FileExists;
1041
1042 impl Validator<Path> for FileExists {
1043 fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1044 if value.is_file() {
1045 Validation::Success(())
1046 } else {
1047 fail(ConfigError::ValidationError {
1048 path: path.to_string(),
1049 source_location: None,
1050 value: Some(value.display().to_string()),
1051 message: "file does not exist".to_string(),
1052 })
1053 }
1054 }
1055 }
1056
1057 impl Validator<std::path::PathBuf> for FileExists {
1058 fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1059 <FileExists as Validator<Path>>::validate(self, value.as_path(), path)
1060 }
1061 }
1062
1063 impl Validator<str> for FileExists {
1064 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1065 <FileExists as Validator<Path>>::validate(self, Path::new(value), path)
1066 }
1067 }
1068
1069 impl Validator<String> for FileExists {
1070 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1071 <FileExists as Validator<str>>::validate(self, value.as_str(), path)
1072 }
1073 }
1074
1075 #[derive(Debug, Clone, Copy)]
1079 pub struct DirExists;
1080
1081 impl Validator<Path> for DirExists {
1082 fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1083 if value.is_dir() {
1084 Validation::Success(())
1085 } else {
1086 fail(ConfigError::ValidationError {
1087 path: path.to_string(),
1088 source_location: None,
1089 value: Some(value.display().to_string()),
1090 message: "directory does not exist".to_string(),
1091 })
1092 }
1093 }
1094 }
1095
1096 impl Validator<std::path::PathBuf> for DirExists {
1097 fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1098 <DirExists as Validator<Path>>::validate(self, value.as_path(), path)
1099 }
1100 }
1101
1102 impl Validator<str> for DirExists {
1103 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1104 <DirExists as Validator<Path>>::validate(self, Path::new(value), path)
1105 }
1106 }
1107
1108 impl Validator<String> for DirExists {
1109 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1110 <DirExists as Validator<str>>::validate(self, value.as_str(), path)
1111 }
1112 }
1113
1114 #[derive(Debug, Clone, Copy)]
1120 pub struct ParentExists;
1121
1122 impl Validator<Path> for ParentExists {
1123 fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1124 match value.parent() {
1125 Some(parent) if parent.is_dir() || parent.as_os_str().is_empty() => {
1126 Validation::Success(())
1127 }
1128 Some(_) => fail(ConfigError::ValidationError {
1129 path: path.to_string(),
1130 source_location: None,
1131 value: Some(value.display().to_string()),
1132 message: "parent directory does not exist".to_string(),
1133 }),
1134 None => fail(ConfigError::ValidationError {
1135 path: path.to_string(),
1136 source_location: None,
1137 value: Some(value.display().to_string()),
1138 message: "path has no parent directory".to_string(),
1139 }),
1140 }
1141 }
1142 }
1143
1144 impl Validator<std::path::PathBuf> for ParentExists {
1145 fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1146 <ParentExists as Validator<Path>>::validate(self, value.as_path(), path)
1147 }
1148 }
1149
1150 impl Validator<str> for ParentExists {
1151 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1152 <ParentExists as Validator<Path>>::validate(self, Path::new(value), path)
1153 }
1154 }
1155
1156 impl Validator<String> for ParentExists {
1157 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1158 <ParentExists as Validator<str>>::validate(self, value.as_str(), path)
1159 }
1160 }
1161
1162 #[derive(Debug, Clone)]
1164 pub struct Extension(pub String);
1165
1166 impl Extension {
1167 pub fn new(ext: impl Into<String>) -> Self {
1169 Self(ext.into())
1170 }
1171 }
1172
1173 impl Validator<Path> for Extension {
1174 fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1175 match value.extension() {
1176 Some(ext) if ext == self.0.as_str() => Validation::Success(()),
1177 Some(ext) => fail(ConfigError::ValidationError {
1178 path: path.to_string(),
1179 source_location: None,
1180 value: Some(value.display().to_string()),
1181 message: format!(
1182 "expected extension '{}', found '{}'",
1183 self.0,
1184 ext.to_string_lossy()
1185 ),
1186 }),
1187 None => fail(ConfigError::ValidationError {
1188 path: path.to_string(),
1189 source_location: None,
1190 value: Some(value.display().to_string()),
1191 message: format!("expected extension '{}', found none", self.0),
1192 }),
1193 }
1194 }
1195 }
1196
1197 impl Validator<std::path::PathBuf> for Extension {
1198 fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1199 <Extension as Validator<Path>>::validate(self, value.as_path(), path)
1200 }
1201 }
1202
1203 impl Validator<str> for Extension {
1204 fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1205 <Extension as Validator<Path>>::validate(self, Path::new(value), path)
1206 }
1207 }
1208
1209 impl Validator<String> for Extension {
1210 fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1211 <Extension as Validator<str>>::validate(self, value.as_str(), path)
1212 }
1213 }
1214}
1215
1216pub fn custom<T, F>(f: F) -> impl Validator<T>
1243where
1244 F: Fn(&T, &str) -> ConfigValidation<()>,
1245{
1246 struct Custom<F>(F);
1247
1248 impl<T, F> Validator<T> for Custom<F>
1249 where
1250 F: Fn(&T, &str) -> ConfigValidation<()>,
1251 {
1252 fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
1253 (self.0)(value, path)
1254 }
1255 }
1256
1257 Custom(f)
1258}
1259
1260pub struct When<V, F> {
1277 validator: V,
1278 condition: F,
1279}
1280
1281impl<V, F> When<V, F> {
1282 pub fn new(validator: V, condition: F) -> Self {
1284 Self {
1285 validator,
1286 condition,
1287 }
1288 }
1289}
1290
1291impl<V, F, T> Validator<T> for When<V, F>
1292where
1293 V: Validator<T>,
1294 F: Fn() -> bool,
1295 T: ?Sized,
1296{
1297 fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
1298 if (self.condition)() {
1299 self.validator.validate(value, path)
1300 } else {
1301 Validation::Success(())
1302 }
1303 }
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308 use super::validators::*;
1309 use super::*;
1310 use std::path::{Path, PathBuf};
1311
1312 #[test]
1317 fn test_unit_validate() {
1318 let result = ().validate();
1319 assert!(result.is_success());
1320 }
1321
1322 #[test]
1323 fn test_option_validate_none() {
1324 let opt: Option<String> = None;
1325 let result = opt.validate();
1326 assert!(result.is_success());
1327 }
1328
1329 #[test]
1330 fn test_option_validate_some() {
1331 let opt = Some("value".to_string());
1332 let result = opt.validate();
1333 assert!(result.is_success());
1334 }
1335
1336 #[test]
1337 fn test_vec_validate_empty() {
1338 let v: Vec<String> = vec![];
1339 let result = v.validate();
1340 assert!(result.is_success());
1341 }
1342
1343 #[test]
1344 fn test_vec_validate_with_items() {
1345 let v = vec!["a".to_string(), "b".to_string()];
1346 let result = v.validate();
1347 assert!(result.is_success());
1348 }
1349
1350 #[test]
1351 fn test_primitive_validate() {
1352 assert!(42i32.validate().is_success());
1353 assert!((std::f64::consts::E).validate().is_success());
1354 assert!(true.validate().is_success());
1355 assert!("hello".to_string().validate().is_success());
1356 }
1357
1358 #[test]
1359 fn test_pathbuf_validate() {
1360 let path = PathBuf::from("/some/path");
1361 assert!(path.validate().is_success());
1362 }
1363
1364 struct FailingConfig;
1369
1370 impl Validate for FailingConfig {
1371 fn validate(&self) -> ConfigValidation<()> {
1372 fail(ConfigError::ValidationError {
1373 path: "inner".to_string(),
1374 source_location: None,
1375 value: None,
1376 message: "always fails".to_string(),
1377 })
1378 }
1379 }
1380
1381 #[test]
1382 fn test_validate_at_prefixes_path() {
1383 let config = FailingConfig;
1384 let result = config.validate_at("outer");
1385 assert!(result.is_failure());
1386
1387 if let Validation::Failure(errors) = result {
1388 assert_eq!(errors.first().path(), Some("outer.inner"));
1389 }
1390 }
1391
1392 #[test]
1397 fn test_non_empty_success() {
1398 let result = NonEmpty.validate("hello", "field");
1399 assert!(result.is_success());
1400 }
1401
1402 #[test]
1403 fn test_non_empty_failure() {
1404 let result = NonEmpty.validate("", "field");
1405 assert!(result.is_failure());
1406 }
1407
1408 #[test]
1409 fn test_min_length_success() {
1410 let result = MinLength(3).validate("hello", "field");
1411 assert!(result.is_success());
1412 }
1413
1414 #[test]
1415 fn test_min_length_failure() {
1416 let result = MinLength(10).validate("hi", "field");
1417 assert!(result.is_failure());
1418 }
1419
1420 #[test]
1421 fn test_max_length_success() {
1422 let result = MaxLength(10).validate("hello", "field");
1423 assert!(result.is_success());
1424 }
1425
1426 #[test]
1427 fn test_max_length_failure() {
1428 let result = MaxLength(3).validate("hello", "field");
1429 assert!(result.is_failure());
1430 }
1431
1432 #[test]
1433 fn test_length_success() {
1434 let result = Length(3..=10).validate("hello", "field");
1435 assert!(result.is_success());
1436 }
1437
1438 #[test]
1439 fn test_length_failure_too_short() {
1440 let result = Length(5..=10).validate("hi", "field");
1441 assert!(result.is_failure());
1442 }
1443
1444 #[test]
1445 fn test_length_failure_too_long() {
1446 let result = Length(1..=3).validate("hello", "field");
1447 assert!(result.is_failure());
1448 }
1449
1450 #[test]
1451 fn test_pattern_success() {
1452 let result = Pattern::new(r"^\d+$").validate("12345", "field");
1453 assert!(result.is_success());
1454 }
1455
1456 #[test]
1457 fn test_pattern_failure() {
1458 let result = Pattern::new(r"^\d+$").validate("abc", "field");
1459 assert!(result.is_failure());
1460 }
1461
1462 #[test]
1463 fn test_email_success() {
1464 let result = Email.validate("user@example.com", "email");
1465 assert!(result.is_success());
1466 }
1467
1468 #[test]
1469 fn test_email_failure() {
1470 let result = Email.validate("not-an-email", "email");
1471 assert!(result.is_failure());
1472 }
1473
1474 #[test]
1475 fn test_url_success() {
1476 let result = Url.validate("https://example.com", "url");
1477 assert!(result.is_success());
1478 }
1479
1480 #[test]
1481 fn test_url_failure() {
1482 let result = Url.validate("not-a-url", "url");
1483 assert!(result.is_failure());
1484 }
1485
1486 #[test]
1491 fn test_range_success() {
1492 let result = Range(1..=100).validate(&50i32, "field");
1493 assert!(result.is_success());
1494 }
1495
1496 #[test]
1497 fn test_range_failure_below() {
1498 let result = Range(10..=100).validate(&5i32, "field");
1499 assert!(result.is_failure());
1500 }
1501
1502 #[test]
1503 fn test_range_failure_above() {
1504 let result = Range(1..=10).validate(&50i32, "field");
1505 assert!(result.is_failure());
1506 }
1507
1508 #[test]
1509 fn test_positive_success() {
1510 assert!(Positive.validate(&42i32, "field").is_success());
1511 assert!(Positive.validate(&1u32, "field").is_success());
1512 assert!(Positive.validate(&0.5f64, "field").is_success());
1513 }
1514
1515 #[test]
1516 fn test_positive_failure() {
1517 assert!(Positive.validate(&-1i32, "field").is_failure());
1518 assert!(Positive.validate(&0i32, "field").is_failure());
1519 assert!(Positive.validate(&0u32, "field").is_failure());
1520 assert!(Positive.validate(&-0.5f64, "field").is_failure());
1521 }
1522
1523 #[test]
1524 fn test_negative_success() {
1525 assert!(Negative.validate(&-42i32, "field").is_success());
1526 assert!(Negative.validate(&-0.5f64, "field").is_success());
1527 }
1528
1529 #[test]
1530 fn test_negative_failure() {
1531 assert!(Negative.validate(&42i32, "field").is_failure());
1532 assert!(Negative.validate(&0i32, "field").is_failure());
1533 assert!(Negative.validate(&0.5f64, "field").is_failure());
1534 }
1535
1536 #[test]
1537 fn test_non_zero_success() {
1538 assert!(NonZero.validate(&42i32, "field").is_success());
1539 assert!(NonZero.validate(&-1i32, "field").is_success());
1540 assert!(NonZero.validate(&1u32, "field").is_success());
1541 assert!(NonZero.validate(&0.5f64, "field").is_success());
1542 }
1543
1544 #[test]
1545 fn test_non_zero_failure() {
1546 assert!(NonZero.validate(&0i32, "field").is_failure());
1547 assert!(NonZero.validate(&0u32, "field").is_failure());
1548 assert!(NonZero.validate(&0.0f64, "field").is_failure());
1549 }
1550
1551 #[test]
1556 fn test_non_empty_collection_success() {
1557 let v = vec![1, 2, 3];
1558 let result = NonEmptyCollection.validate(&v, "items");
1559 assert!(result.is_success());
1560 }
1561
1562 #[test]
1563 fn test_non_empty_collection_failure() {
1564 let v: Vec<i32> = vec![];
1565 let result = NonEmptyCollection.validate(&v, "items");
1566 assert!(result.is_failure());
1567 }
1568
1569 #[test]
1570 fn test_min_items_success() {
1571 let v = vec![1, 2, 3];
1572 let result = MinItems(2).validate(&v, "items");
1573 assert!(result.is_success());
1574 }
1575
1576 #[test]
1577 fn test_min_items_failure() {
1578 let v = vec![1];
1579 let result = MinItems(3).validate(&v, "items");
1580 assert!(result.is_failure());
1581 }
1582
1583 #[test]
1584 fn test_max_items_success() {
1585 let v = vec![1, 2, 3];
1586 let result = MaxItems(5).validate(&v, "items");
1587 assert!(result.is_success());
1588 }
1589
1590 #[test]
1591 fn test_max_items_failure() {
1592 let v = vec![1, 2, 3, 4, 5];
1593 let result = MaxItems(3).validate(&v, "items");
1594 assert!(result.is_failure());
1595 }
1596
1597 #[test]
1598 fn test_each_success() {
1599 let v = vec![1, 2, 3];
1600 let result = Each(Positive).validate(&v, "items");
1601 assert!(result.is_success());
1602 }
1603
1604 #[test]
1605 fn test_each_failure_accumulates_errors() {
1606 let v = vec![1, -2, -3, 4];
1607 let result = Each(Positive).validate(&v, "items");
1608 assert!(result.is_failure());
1609
1610 if let Validation::Failure(errors) = result {
1611 assert_eq!(errors.len(), 2);
1613 }
1614 }
1615
1616 #[test]
1617 fn test_each_empty_collection() {
1618 let v: Vec<i32> = vec![];
1619 let result = Each(Positive).validate(&v, "items");
1620 assert!(result.is_success());
1621 }
1622
1623 #[test]
1628 fn test_extension_success() {
1629 let result = Extension::new("toml").validate(Path::new("config.toml"), "file");
1630 assert!(result.is_success());
1631 }
1632
1633 #[test]
1634 fn test_extension_failure_wrong() {
1635 let result = Extension::new("toml").validate(Path::new("config.json"), "file");
1636 assert!(result.is_failure());
1637 }
1638
1639 #[test]
1640 fn test_extension_failure_none() {
1641 let result = Extension::new("toml").validate(Path::new("config"), "file");
1642 assert!(result.is_failure());
1643 }
1644
1645 #[test]
1650 fn test_validate_field_empty_validators() {
1651 let empty: &[&dyn Validator<str>] = &[];
1652 let result = validate_field("value", "field", empty);
1653 assert!(result.is_success());
1654 }
1655
1656 #[test]
1657 fn test_validate_field_single_validator() {
1658 let result = validate_field("hello", "field", &[&NonEmpty]);
1659 assert!(result.is_success());
1660 }
1661
1662 #[test]
1663 fn test_validate_field_multiple_validators_all_pass() {
1664 let result = validate_field("hello", "field", &[&NonEmpty, &MinLength(3)]);
1665 assert!(result.is_success());
1666 }
1667
1668 #[test]
1669 fn test_validate_field_accumulates_errors() {
1670 let result = validate_field("", "field", &[&NonEmpty, &MinLength(3)]);
1672 assert!(result.is_failure());
1673
1674 if let Validation::Failure(errors) = result {
1675 assert_eq!(errors.len(), 2);
1676 }
1677 }
1678
1679 struct InnerConfig {
1684 value: i32,
1685 }
1686
1687 impl Validate for InnerConfig {
1688 fn validate(&self) -> ConfigValidation<()> {
1689 if self.value > 0 {
1690 Validation::Success(())
1691 } else {
1692 fail(ConfigError::ValidationError {
1693 path: "value".to_string(),
1694 source_location: None,
1695 value: Some(self.value.to_string()),
1696 message: "must be positive".to_string(),
1697 })
1698 }
1699 }
1700 }
1701
1702 #[test]
1703 fn test_validate_nested_success() {
1704 let inner = InnerConfig { value: 42 };
1705 let result = validate_nested(&inner, "config");
1706 assert!(result.is_success());
1707 }
1708
1709 #[test]
1710 fn test_validate_nested_failure() {
1711 let inner = InnerConfig { value: -1 };
1712 let result = validate_nested(&inner, "config");
1713 assert!(result.is_failure());
1714
1715 if let Validation::Failure(errors) = result {
1716 assert_eq!(errors.first().path(), Some("config.value"));
1717 }
1718 }
1719
1720 #[test]
1721 fn test_validate_optional_nested_none() {
1722 let opt: Option<InnerConfig> = None;
1723 let result = validate_optional_nested(&opt, "config");
1724 assert!(result.is_success());
1725 }
1726
1727 #[test]
1728 fn test_validate_optional_nested_some() {
1729 let opt = Some(InnerConfig { value: -1 });
1730 let result = validate_optional_nested(&opt, "config");
1731 assert!(result.is_failure());
1732 }
1733
1734 #[test]
1739 fn test_custom_validator() {
1740 let even_validator = custom(|value: &i32, path: &str| {
1741 if value % 2 == 0 {
1742 Validation::Success(())
1743 } else {
1744 fail(ConfigError::ValidationError {
1745 path: path.to_string(),
1746 source_location: None,
1747 value: Some(value.to_string()),
1748 message: "value must be even".to_string(),
1749 })
1750 }
1751 });
1752
1753 assert!(even_validator.validate(&4, "num").is_success());
1754 assert!(even_validator.validate(&3, "num").is_failure());
1755 }
1756
1757 #[test]
1762 fn test_when_condition_true() {
1763 let validator = When::new(NonEmpty, || true);
1764 let result = validator.validate("", "field");
1765 assert!(result.is_failure());
1766 }
1767
1768 #[test]
1769 fn test_when_condition_false() {
1770 let validator = When::new(NonEmpty, || false);
1771 let result = validator.validate("", "field");
1772 assert!(result.is_success());
1773 }
1774
1775 struct DatabaseConfig {
1780 host: String,
1781 port: u16,
1782 pool_size: u32,
1783 }
1784
1785 impl Validate for DatabaseConfig {
1786 fn validate(&self) -> ConfigValidation<()> {
1787 let validations = vec![
1788 validate_field(&self.host, "host", &[&NonEmpty]),
1789 validate_field(&self.port, "port", &[&Range(1..=65535)]),
1790 validate_field(&self.pool_size, "pool_size", &[&Range(1..=100)]),
1791 ];
1792 Validation::all_vec(validations).map(|_| ())
1793 }
1794 }
1795
1796 #[test]
1797 fn test_database_config_valid() {
1798 let config = DatabaseConfig {
1799 host: "localhost".to_string(),
1800 port: 5432,
1801 pool_size: 10,
1802 };
1803 assert!(config.validate().is_success());
1804 }
1805
1806 #[test]
1807 fn test_database_config_accumulates_all_errors() {
1808 let config = DatabaseConfig {
1809 host: "".to_string(),
1810 port: 0,
1811 pool_size: 200,
1812 };
1813
1814 let result = config.validate();
1815 assert!(result.is_failure());
1816
1817 if let Validation::Failure(errors) = result {
1818 assert_eq!(errors.len(), 3);
1819 }
1820 }
1821
1822 #[test]
1824 fn test_vec_custom_validate() {
1825 let configs = vec![
1826 InnerConfig { value: 1 },
1827 InnerConfig { value: -1 },
1828 InnerConfig { value: -2 },
1829 ];
1830
1831 let result = configs.validate();
1832 assert!(result.is_failure());
1833
1834 if let Validation::Failure(errors) = result {
1836 assert_eq!(errors.len(), 2);
1837 let paths: Vec<_> = errors.iter().filter_map(|e| e.path()).collect();
1838 assert!(paths.contains(&"[1].value"));
1839 assert!(paths.contains(&"[2].value"));
1840 }
1841 }
1842
1843 #[test]
1848 fn test_validation_context_lookup() {
1849 let mut locations = SourceLocationMap::new();
1850 locations.insert(
1851 "host".to_string(),
1852 SourceLocation::new("config.toml").with_line(5),
1853 );
1854 locations.insert(
1855 "port".to_string(),
1856 SourceLocation::new("config.toml").with_line(6),
1857 );
1858
1859 let ctx = ValidationContext::new(locations);
1860
1861 let host_loc = ctx.location_for("host").unwrap();
1862 assert_eq!(host_loc.source, "config.toml");
1863 assert_eq!(host_loc.line, Some(5));
1864
1865 let port_loc = ctx.location_for("port").unwrap();
1866 assert_eq!(port_loc.line, Some(6));
1867
1868 assert!(ctx.location_for("missing").is_none());
1870 }
1871
1872 #[test]
1873 fn test_with_validation_context() {
1874 let mut locations = SourceLocationMap::new();
1875 locations.insert(
1876 "test_field".to_string(),
1877 SourceLocation::new("test.toml").with_line(10),
1878 );
1879
1880 let ctx = ValidationContext::new(locations);
1881
1882 assert!(current_source_location("test_field").is_none());
1884
1885 let result = with_validation_context(ctx, || {
1887 let loc = current_source_location("test_field");
1888 assert!(loc.is_some());
1889 let loc = loc.unwrap();
1890 assert_eq!(loc.source, "test.toml");
1891 assert_eq!(loc.line, Some(10));
1892 "success"
1893 });
1894
1895 assert_eq!(result, "success");
1896
1897 assert!(current_source_location("test_field").is_none());
1899 }
1900
1901 #[test]
1902 fn test_context_clears_on_completion() {
1903 let mut locations = SourceLocationMap::new();
1904 locations.insert("field".to_string(), SourceLocation::new("a.toml"));
1905
1906 let ctx = ValidationContext::new(locations);
1907 with_validation_context(ctx, || ());
1908
1909 assert!(current_source_location("field").is_none());
1911 }
1912
1913 #[test]
1914 fn test_path_prefix_for_nested_lookup() {
1915 let mut locations = SourceLocationMap::new();
1916 locations.insert(
1917 "server.host".to_string(),
1918 SourceLocation::new("config.toml").with_line(3),
1919 );
1920 locations.insert(
1921 "server.port".to_string(),
1922 SourceLocation::new("config.toml").with_line(4),
1923 );
1924 locations.insert(
1925 "database.host".to_string(),
1926 SourceLocation::new("config.toml").with_line(7),
1927 );
1928
1929 let ctx = ValidationContext::new(locations);
1930
1931 with_validation_context(ctx, || {
1932 assert!(current_source_location("host").is_none());
1934
1935 push_path_prefix("server");
1937 let loc = current_source_location("host");
1938 assert!(loc.is_some());
1939 let loc = loc.unwrap();
1940 assert_eq!(loc.source, "config.toml");
1941 assert_eq!(loc.line, Some(3));
1942
1943 let port_loc = current_source_location("port").unwrap();
1945 assert_eq!(port_loc.line, Some(4));
1946
1947 pop_path_prefix();
1948
1949 assert!(current_source_location("host").is_none());
1951
1952 push_path_prefix("database");
1954 let db_loc = current_source_location("host").unwrap();
1955 assert_eq!(db_loc.line, Some(7));
1956 pop_path_prefix();
1957 });
1958 }
1959
1960 #[test]
1961 fn test_nested_path_prefix_stacking() {
1962 let mut locations = SourceLocationMap::new();
1963 locations.insert(
1964 "outer.inner.field".to_string(),
1965 SourceLocation::new("config.toml").with_line(10),
1966 );
1967
1968 let ctx = ValidationContext::new(locations);
1969
1970 with_validation_context(ctx, || {
1971 assert!(current_source_location("field").is_none());
1973
1974 push_path_prefix("outer");
1976 assert!(current_source_location("field").is_none());
1977
1978 push_path_prefix("inner");
1980 let loc = current_source_location("field");
1981 assert!(loc.is_some());
1982 assert_eq!(loc.unwrap().line, Some(10));
1983
1984 pop_path_prefix();
1986 assert!(current_source_location("field").is_none());
1987
1988 pop_path_prefix();
1990 });
1991 }
1992
1993 use stillwater::predicate::prelude::*;
1998
1999 #[test]
2000 fn test_from_predicate_success() {
2001 let validator = from_predicate(not_empty());
2002 let result = validator.validate("hello", "field");
2003 assert!(result.is_success());
2004 }
2005
2006 #[test]
2007 fn test_from_predicate_failure() {
2008 let validator = from_predicate(not_empty());
2009 let result = validator.validate("", "field");
2010 assert!(result.is_failure());
2011
2012 if let Validation::Failure(errors) = result {
2013 assert_eq!(errors.len(), 1);
2014 assert_eq!(errors.first().path(), Some("field"));
2015 }
2016 }
2017
2018 #[test]
2019 fn test_validate_with_predicate_success() {
2020 let result = validate_with_predicate(
2021 &42,
2022 "port",
2023 between(1, 65535),
2024 "port must be between 1 and 65535",
2025 );
2026 assert!(result.is_success());
2027 }
2028
2029 #[test]
2030 fn test_validate_with_predicate_failure() {
2031 let result = validate_with_predicate(
2032 &0,
2033 "port",
2034 between(1, 65535),
2035 "port must be between 1 and 65535",
2036 );
2037 assert!(result.is_failure());
2038
2039 if let Validation::Failure(errors) = result {
2040 assert_eq!(errors.len(), 1);
2041 assert_eq!(errors.first().path(), Some("port"));
2042 if let ConfigError::ValidationError { message, .. } = errors.first() {
2044 assert_eq!(message, "port must be between 1 and 65535");
2045 } else {
2046 panic!("Expected ValidationError");
2047 }
2048 }
2049 }
2050
2051 #[test]
2052 fn test_validate_with_predicate_custom_message() {
2053 let result = validate_with_predicate("", "username", not_empty(), "username is required");
2054
2055 assert!(result.is_failure());
2056
2057 if let Validation::Failure(errors) = result {
2058 if let ConfigError::ValidationError { message, .. } = errors.first() {
2059 assert_eq!(message, "username is required");
2060 } else {
2061 panic!("Expected ValidationError");
2062 }
2063 }
2064 }
2065
2066 #[test]
2067 fn test_predicate_preserves_source_location() {
2068 let mut locations = SourceLocationMap::new();
2069 locations.insert(
2070 "host".to_string(),
2071 SourceLocation::new("config.toml").with_line(5),
2072 );
2073
2074 let ctx = ValidationContext::new(locations);
2075
2076 with_validation_context(ctx, || {
2077 let result = validate_with_predicate("", "host", not_empty(), "host cannot be empty");
2078
2079 assert!(result.is_failure());
2080
2081 if let Validation::Failure(errors) = result {
2082 let err = errors.first();
2083 assert_eq!(
2084 err.source_location().map(|l| l.source.as_str()),
2085 Some("config.toml")
2086 );
2087 assert_eq!(err.source_location().and_then(|l| l.line), Some(5));
2088 }
2089 });
2090 }
2091
2092 #[test]
2093 fn test_predicate_with_nested_validation() {
2094 let mut locations = SourceLocationMap::new();
2095 locations.insert(
2096 "database.host".to_string(),
2097 SourceLocation::new("config.toml").with_line(10),
2098 );
2099
2100 let ctx = ValidationContext::new(locations);
2101
2102 with_validation_context(ctx, || {
2103 push_path_prefix("database");
2104 let result = validate_with_predicate("", "host", not_empty(), "host required");
2105 pop_path_prefix();
2106
2107 assert!(result.is_failure());
2108
2109 if let Validation::Failure(errors) = result {
2110 let err = errors.first();
2111 assert_eq!(err.source_location().and_then(|l| l.line), Some(10));
2112 }
2113 });
2114 }
2115
2116 #[test]
2117 fn test_complex_string_predicate() {
2118 assert!(validate_with_predicate(
2120 "user123",
2121 "username",
2122 len_min(3),
2123 "must be at least 3 chars"
2124 )
2125 .is_success());
2126
2127 assert!(
2129 validate_with_predicate("ab", "username", len_min(3), "must be at least 3 chars")
2130 .is_failure()
2131 );
2132
2133 assert!(validate_with_predicate(
2135 "hello",
2136 "field",
2137 len_between(3, 10),
2138 "length must be 3-10 chars"
2139 )
2140 .is_success());
2141 assert!(validate_with_predicate(
2142 "hi",
2143 "field",
2144 len_between(3, 10),
2145 "length must be 3-10 chars"
2146 )
2147 .is_failure());
2148 }
2149
2150 #[test]
2151 fn test_numeric_range_predicate() {
2152 let pred = gt(0).and(le(65535));
2153 let validator = from_predicate(pred);
2154
2155 assert!(validator.validate(&1, "port").is_success());
2157 assert!(validator.validate(&8080, "port").is_success());
2158 assert!(validator.validate(&65535, "port").is_success());
2159
2160 assert!(validator.validate(&0, "port").is_failure());
2162 assert!(validator.validate(&65536, "port").is_failure());
2163 assert!(validator.validate(&-1, "port").is_failure());
2164 }
2165
2166 #[test]
2167 fn test_string_length_predicates() {
2168 assert!(validate_with_predicate("hello", "field", len_min(3), "min 3 chars").is_success());
2170 assert!(validate_with_predicate("hi", "field", len_min(3), "min 3 chars").is_failure());
2171
2172 assert!(
2174 validate_with_predicate("hello", "field", len_max(10), "max 10 chars").is_success()
2175 );
2176 assert!(
2177 validate_with_predicate("verylongstring", "field", len_max(10), "max 10 chars")
2178 .is_failure()
2179 );
2180
2181 assert!(
2183 validate_with_predicate("hello", "field", len_eq(5), "exactly 5 chars").is_success()
2184 );
2185 assert!(validate_with_predicate("hi", "field", len_eq(5), "exactly 5 chars").is_failure());
2186 }
2187
2188 #[test]
2189 fn test_predicate_and_validator_together() {
2190 let pred_validator = from_predicate(len_min(3));
2192 let trad_validator = NonEmpty;
2193
2194 let result = validate_field("hello", "field", &[&trad_validator, &pred_validator]);
2195 assert!(result.is_success());
2196
2197 let result = validate_field("", "field", &[&trad_validator, &pred_validator]);
2199 assert!(result.is_failure());
2200
2201 let result = validate_field("hi", "field", &[&trad_validator, &pred_validator]);
2203 assert!(result.is_failure());
2204 }
2205
2206 #[test]
2207 fn test_validate_field_with_predicate() {
2208 let validator = from_predicate(between(1, 100));
2209
2210 let result = validate_field(&50, "value", &[&validator]);
2212 assert!(result.is_success());
2213
2214 let result = validate_field(&150, "value", &[&validator]);
2216 assert!(result.is_failure());
2217 }
2218}