serde_valid/validation/object/
max_properties.rs1use crate::{traits::Size, MaxPropertiesError};
2
3pub trait ValidateMaxProperties {
51 fn validate_max_properties(&self, max_properties: usize) -> Result<(), MaxPropertiesError>;
52}
53
54impl<T> ValidateMaxProperties for T
55where
56 T: Size,
57{
58 fn validate_max_properties(&self, max_properties: usize) -> Result<(), MaxPropertiesError> {
59 if max_properties >= self.size() {
60 Ok(())
61 } else {
62 Err(MaxPropertiesError::new(max_properties))
63 }
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70 use serde_json::json;
71 use std::collections::BTreeMap;
72 use std::collections::HashMap;
73
74 #[test]
75 fn test_validate_object_max_properties_hash_map_type() {
76 let mut map = HashMap::new();
77 map.insert("key1".to_string(), "value1".to_string());
78 map.insert("key2".to_string(), "value2".to_string());
79 map.insert("key3".to_string(), "value3".to_string());
80 assert!(ValidateMaxProperties::validate_max_properties(&map, 3).is_ok());
81 }
82
83 #[test]
84 fn test_validate_object_max_properties_btree_map_type() {
85 let mut map = BTreeMap::new();
86 map.insert("key1".to_string(), "value1".to_string());
87 map.insert("key2".to_string(), "value2".to_string());
88 map.insert("key3".to_string(), "value3".to_string());
89 assert!(ValidateMaxProperties::validate_max_properties(&map, 3).is_ok());
90 }
91
92 #[test]
93 fn test_validate_object_max_properties_json_map_type() {
94 let value = json!({
95 "key1": "value1",
96 "key2": "value2",
97 "key3": "value3",
98 });
99 let map = value.as_object().unwrap();
100
101 assert!(ValidateMaxProperties::validate_max_properties(map, 4).is_ok());
102 assert!(ValidateMaxProperties::validate_max_properties(map, 3).is_ok());
103 }
104
105 #[test]
106 fn test_validate_object_max_properties_is_false() {
107 let value = json!({
108 "key1": "value1",
109 "key2": "value2",
110 "key3": "value3",
111 });
112 let map = value.as_object().unwrap();
113
114 assert!(ValidateMaxProperties::validate_max_properties(map, 2).is_err());
115 }
116}