Spaces:
Build error
Build error
File size: 8,458 Bytes
84d2a97 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
use actix_web_validator::error::flatten_errors;
use serde_json::Value;
use validator::{ValidationError, ValidationErrors};
/// Warn about validation errors in the log.
///
/// Validation errors are pretty printed field-by-field.
pub fn warn_validation_errors(description: &str, errs: &ValidationErrors) {
log::warn!("{description} has validation errors:");
describe_errors(errs)
.into_iter()
.for_each(|(key, msg)| log::warn!("- {key}: {}", msg));
}
/// Label the given validation errors in a single string.
pub fn label_errors(label: impl AsRef<str>, errs: &ValidationErrors) -> String {
format!(
"{}: [{}]",
label.as_ref(),
describe_errors(errs)
.into_iter()
.map(|(field, err)| format!("{field}: {err}"))
.collect::<Vec<_>>()
.join("; ")
)
}
/// Describe the given validation errors.
///
/// Returns a list of error messages for fields: `(field, message)`
fn describe_errors(errs: &ValidationErrors) -> Vec<(String, String)> {
flatten_errors(errs)
.into_iter()
.map(|(_, name, err)| (name, describe_error(err)))
.collect()
}
/// Describe a specific validation error.
fn describe_error(
err @ ValidationError {
code,
message,
params,
}: &ValidationError,
) -> String {
// Prefer to return message if set
if let Some(message) = message {
return message.to_string();
} else if let Some(Value::String(message)) = params.get("message") {
return message.to_string();
}
// Generate messages based on codes
match code.as_ref() {
"range" => {
let msg = match (params.get("min"), params.get("max")) {
(Some(min), None) => format!("must be {min} or larger"),
(Some(min), Some(max)) => format!("must be from {min} to {max}"),
(None, Some(max)) => format!("must be {max} or smaller"),
// Should be unreachable
_ => err.to_string(),
};
match params.get("value") {
Some(value) => format!("value {value} invalid, {msg}"),
None => msg,
}
}
"length" => {
let msg = match (params.get("equal"), params.get("min"), params.get("max")) {
(Some(equal), _, _) => format!("must be exactly {equal} characters"),
(None, Some(min), None) => format!("must be at least {min} characters"),
(None, Some(min), Some(max)) => {
format!("must be from {min} to {max} characters")
}
(None, None, Some(max)) => format!("must be at most {max} characters"),
// Should be unreachable
_ => err.to_string(),
};
match params.get("value") {
Some(value) => format!("value {value} invalid, {msg}"),
None => msg,
}
}
"must_not_match" => {
match (
params.get("value"),
params.get("other_field"),
params.get("other_value"),
) {
(Some(value), Some(other_field), Some(other_value)) => {
format!("value {value} must not match {other_value} in {other_field}")
}
(Some(value), Some(other_field), None) => {
format!("value {value} must not match value in {other_field}")
}
(None, Some(other_field), Some(other_value)) => {
format!("must not match {other_value} in {other_field}")
}
(None, Some(other_field), None) => {
format!("must not match value in {other_field}")
}
// Should be unreachable
_ => err.to_string(),
}
}
"does_not_contain" => match params.get("pattern") {
Some(pattern) => format!("cannot contain {pattern}"),
None => err.to_string(),
},
"not_empty" => "value invalid, must not be empty".to_string(),
"closed_line" => {
"value invalid, the first and the last points should be same to form a closed line"
.to_string()
}
"min_line_length" => match (params.get("min_length"), params.get("length")) {
(Some(min_length), Some(length)) => {
format!("value invalid, the size must be at least {min_length}, got {length}")
}
_ => err.to_string(),
},
// Undescribed error codes
_ => err.to_string(),
}
}
#[cfg(test)]
mod tests {
use api::grpc::qdrant::{GeoLineString, GeoPoint, GeoPolygon};
use validator::Validate;
use super::*;
#[derive(Validate, Debug)]
struct SomeThing {
#[validate(range(min = 1))]
pub idx: usize,
}
#[derive(Validate, Debug)]
struct OtherThing {
#[validate(nested)]
pub things: Vec<SomeThing>,
}
fn build_polygon(
exterior_points: Vec<(f64, f64)>,
interiors_points: Vec<Vec<(f64, f64)>>,
) -> GeoPolygon {
let exterior_line = GeoLineString {
points: exterior_points
.into_iter()
.map(|(lon, lat)| GeoPoint { lon, lat })
.collect(),
};
let interior_lines = interiors_points
.into_iter()
.map(|points| GeoLineString {
points: points
.into_iter()
.map(|(lon, lat)| GeoPoint { lon, lat })
.collect(),
})
.collect();
GeoPolygon {
exterior: Some(exterior_line),
interiors: interior_lines,
}
}
#[test]
fn test_validation() {
let bad_config = OtherThing {
things: vec![SomeThing { idx: 0 }],
};
assert!(
bad_config.validate().is_err(),
"validation of bad config should fail"
);
}
#[test]
fn test_config_validation_render() {
let bad_config = OtherThing {
things: vec![
SomeThing { idx: 0 },
SomeThing { idx: 1 },
SomeThing { idx: 2 },
],
};
let errors = bad_config
.validate()
.expect_err("validation of bad config should fail");
assert_eq!(
describe_errors(&errors),
vec![(
"things[0].idx".into(),
"value 0 invalid, must be 1 or larger".into()
)]
);
}
#[test]
fn test_polygon_validation_render() {
let test_cases = vec![
(
build_polygon(vec![], vec![]),
vec![("exterior".into(), "value invalid, must not be empty".into())],
),
(
build_polygon(vec![(1., 1.),(2., 2.),(1., 1.)], vec![]),
vec![("exterior".into(), "value invalid, the size must be at least 4, got 3".into())],
),
(
build_polygon(vec![(1., 1.),(2., 2.),(3., 3.),(4., 4.)], vec![]),
vec![(
"exterior".into(),
"value invalid, the first and the last points should be same to form a closed line".into(),
)],
),
(
build_polygon(
vec![(1., 1.),(2., 2.),(3., 3.),(1., 1.)],
vec![vec![(1., 1.),(2., 2.),(1., 1.)]],
),
vec![("interiors".into(), "value invalid, the size must be at least 4, got 3".into())],
),
(
build_polygon(
vec![(1., 1.),(2., 2.),(3., 3.),(1., 1.)],
vec![vec![(1., 1.),(2., 2.),(3., 3.),(4., 4.)]],
),
vec![(
"interiors".into(),
"value invalid, the first and the last points should be same to form a closed line".into(),
)],
),
];
for (polygon, expected_errors) in test_cases {
let errors = polygon
.validate()
.expect_err("validation of bad polygon should fail");
assert_eq!(describe_errors(&errors), expected_errors);
}
}
}
|