Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

count string length correctly in OpenAPI validators #666

Merged
merged 1 commit into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading