Skip to content

Commit

Permalink
Add negative tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Techassi committed Sep 13, 2023
1 parent 88d4677 commit 128eff7
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down Expand Up @@ -82,6 +79,11 @@ impl FromStr for Duration {
type Err = DurationParseError;

fn from_str(input: &str) -> Result<Self, Self::Err> {
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();
Expand Down Expand Up @@ -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")]
Expand Down

0 comments on commit 128eff7

Please sign in to comment.