Skip to content

Commit

Permalink
count string length correctly in OpenAPI validators (#666)
Browse files Browse the repository at this point in the history
  • Loading branch information
mishmish-dev authored Nov 18, 2023
1 parent a2e8b98 commit 0a1dc1e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion poem-openapi/src/validation/max_length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl MaxLength {
impl<T: AsRef<str>> Validator<T> for MaxLength {
#[inline]
fn check(&self, value: &T) -> bool {
value.as_ref().len() <= self.len
value.as_ref().chars().nth(self.len).is_none()
}
}

Expand Down
2 changes: 1 addition & 1 deletion poem-openapi/src/validation/min_length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl MinLength {
impl<T: AsRef<str>> Validator<T> for MinLength {
#[inline]
fn check(&self, value: &T) -> bool {
value.as_ref().len() >= self.len
self.len == 0 || value.as_ref().chars().nth(self.len - 1).is_some()
}
}

Expand Down
24 changes: 24 additions & 0 deletions poem-openapi/tests/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,18 @@ fn test_max_length() {
value: "abcd".to_string()
}
);
assert_eq!(
A::parse_from_json(Some(json!({ "value": "abcde" }))).unwrap(),
A {
value: "abcde".to_string()
}
);
assert_eq!(
A::parse_from_json(Some(json!({ "value": "שלום!" }))).unwrap(),
A {
value: "שלום!".to_string()
}
);
assert_eq!(
A::parse_from_json(Some(json!({ "value": "abcdef" })))
.unwrap_err()
Expand All @@ -147,6 +159,12 @@ fn test_min_length() {
value: String,
}

assert_eq!(
A::parse_from_json(Some(json!({ "value": "abcde" }))).unwrap(),
A {
value: "abcde".to_string()
}
);
assert_eq!(
A::parse_from_json(Some(json!({ "value": "abcdef" }))).unwrap(),
A {
Expand All @@ -159,6 +177,12 @@ fn test_min_length() {
.into_message(),
"failed to parse \"A\": field `value` verification failed. minLength(5)"
);
assert_eq!(
A::parse_from_json(Some(json!({ "value": "שלום" })))
.unwrap_err()
.into_message(),
"failed to parse \"A\": field `value` verification failed. minLength(5)"
);

let mut schema = MetaSchema::new("string");
validation::MinLength::new(10).update_meta(&mut schema);
Expand Down

0 comments on commit 0a1dc1e

Please sign in to comment.