From 128eff76f3146cd9373cacc50d62fbcb5b714f34 Mon Sep 17 00:00:00 2001 From: Techassi Date: Wed, 13 Sep 2023 13:05:43 +0200 Subject: [PATCH] Add negative tests --- src/duration.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/duration.rs b/src/duration.rs index 63ffc5317..107780e45 100644 --- a/src/duration.rs +++ b/src/duration.rs @@ -39,14 +39,11 @@ const HOURS_FACTOR: u64 = MINUTES_FACTOR * 60; const MINUTES_FACTOR: u64 = SECONDS_FACTOR * 60; const SECONDS_FACTOR: u64 = 1; -#[derive(Debug, Error)] +#[derive(Debug, Error, PartialEq)] pub enum DurationParseError { #[error("failed to parse string as number")] ParseIntError(#[from] ParseIntError), - #[error("expected a number, found character")] - ExpectedNumber, - #[error("expected a character, found number")] ExpectedChar, @@ -82,6 +79,11 @@ impl FromStr for Duration { type Err = DurationParseError; fn from_str(input: &str) -> Result { + let input = input.trim(); + if input.is_empty() || !input.is_ascii() { + return Err(DurationParseError::InvalidInput); + } + let mut state = DurationParseState::Init; let mut buffer = String::new(); let mut iter = input.chars(); @@ -318,6 +320,18 @@ mod test { assert_eq!(dur.as_secs(), output); } + #[rstest] + #[case("2y2", DurationParseError::ExpectedChar)] + #[case("-1y", DurationParseError::InvalidInput)] + #[case("1Y", DurationParseError::InvalidInput)] + #[case("1รค", DurationParseError::InvalidInput)] + #[case("1q", DurationParseError::InvalidUnit)] + #[case(" ", DurationParseError::InvalidInput)] + fn parse_invalid(#[case] input: &str, #[case] expected_err: DurationParseError) { + let err = Duration::from_str(input).unwrap_err(); + assert_eq!(err, expected_err) + } + #[rstest] #[case("2y 2h 20m 42s")] #[case("15d 2m 2s")]