commit bda18df0aafe22fad505453b2dcdbe9868c90a54 from: witcher date: Fri Jan 6 14:49:29 2023 UTC Add TryFrom implementation for Task and unit tests `Task` can now be created from `&str` via `TryFrom`. The `new_key_value` method on `Tag` now has unit tests. commit - caf5a2e4344d368c834c8d00be84873248d843bc commit + bda18df0aafe22fad505453b2dcdbe9868c90a54 blob - f5b1b8e532a444f4930b6d44be6d74995cd94971 blob + af4b5dbd2ab934d82ac95ac79ff2cb7de160e0bf --- src/err.rs +++ src/err.rs @@ -8,12 +8,12 @@ use thiserror::Error; /// The general error used in the library. #[non_exhaustive] -#[derive(Debug, Error)] +#[derive(Debug, Error, PartialEq, Eq)] pub enum TodoError { /// The input has an incorrect format. #[error("Incorrect format: {0}")] IncorrectFormat(&'static str), - /// An error occured while parsing the input. + /// An error occurred while parsing the input. #[error("Error while parsing: {0}")] ParsingError(&'static str), } blob - cc3b2ef7ab549d76a82bc2cf486bd9189329539a blob + 15183b4929d763f4b870c60c739fe9925d1b155c --- src/types.rs +++ src/types.rs @@ -318,3 +318,43 @@ impl<'a> }) } } + +impl<'a> TryFrom<&'a str> for Task<'a> { + type Error = TodoError; + + fn try_from(value: &'a str) -> Result { + Ok(parser::task(value) + .finish() + .map_err(|_| TodoError::ParsingError("Unable to parse task"))? + .1) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_tag_new_key_value() { + assert_eq!( + Tag::new_key_value("due", "2023-01-06"), + Ok(Tag::Due(NaiveDate::from_ymd_opt(2023, 1, 6).unwrap())), + ); + assert!(matches!( + Tag::new_key_value("due", "invalid format"), + Err(TodoError::IncorrectFormat(_)) + )); + + assert_eq!( + Tag::new_key_value("rec", "+420y"), + Ok(Tag::Rec(Recurring::new( + true, + TimeAmount::new(420, TimeUnit::Year) + ))), + ); + assert!(matches!( + Tag::new_key_value("rec", "0d"), + Err(TodoError::IncorrectFormat(_)) + )); + } +}