From 56269781c5df818e32c8e37eefa2aba994942fde Mon Sep 17 00:00:00 2001 From: Mishmish Dev Date: Fri, 6 Oct 2023 00:45:41 +0300 Subject: [PATCH] count string length correctly in OpenAPI validators --- poem-openapi/src/validation/max_length.rs | 2 +- poem-openapi/src/validation/min_length.rs | 2 +- poem-openapi/tests/validation.rs | 24 +++++++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/poem-openapi/src/validation/max_length.rs b/poem-openapi/src/validation/max_length.rs index 57cf287e58..8bd0b9a10a 100644 --- a/poem-openapi/src/validation/max_length.rs +++ b/poem-openapi/src/validation/max_length.rs @@ -21,7 +21,7 @@ impl MaxLength { impl> Validator for MaxLength { #[inline] fn check(&self, value: &T) -> bool { - value.as_ref().len() <= self.len + value.as_ref().chars().nth(self.len).is_none() } } diff --git a/poem-openapi/src/validation/min_length.rs b/poem-openapi/src/validation/min_length.rs index e51a8184de..2bc7fed9e8 100644 --- a/poem-openapi/src/validation/min_length.rs +++ b/poem-openapi/src/validation/min_length.rs @@ -21,7 +21,7 @@ impl MinLength { impl> Validator 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() } } diff --git a/poem-openapi/tests/validation.rs b/poem-openapi/tests/validation.rs index 358bbad137..9ab1282ac5 100644 --- a/poem-openapi/tests/validation.rs +++ b/poem-openapi/tests/validation.rs @@ -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() @@ -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 { @@ -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);