From 52775f26b7928610cefd21dde761469d27bbab86 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 3 Nov 2024 02:36:35 +0100 Subject: [PATCH] Adds coverage (and a badge) to the project --- README.md | 1 + badge.svg | 23 ++++++++ src/config.rs | 1 + src/date/date_tools.rs | 129 ++++++++++++++++++++++++++++++++++++++--- src/error_handling.rs | 17 +++++- src/io.rs | 47 ++++++++++----- src/main.rs | 1 + src/votes.rs | 9 ++- 8 files changed, 205 insertions(+), 23 deletions(-) create mode 100644 badge.svg diff --git a/README.md b/README.md index b60d85b..35c9b15 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # idlefox +![code coverage](badge.svg) A Rust Discord Bot, in charge of greatly simplifying the process of finding a meeting date, organising an event and choosing between several options. diff --git a/badge.svg b/badge.svg new file mode 100644 index 0000000..750f2df --- /dev/null +++ b/badge.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + coverage + coverage + 100 + 100 + + \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index b1dba39..06f358f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -62,6 +62,7 @@ pub(crate) struct GlobalConfig {} /// log::warn!("Warning: This will be written on file and on screen"); /// ``` /// +#[cfg(not(tarpaulin_include))] pub fn init_logger() -> Result<(), IdleError> { CombinedLogger::init(vec![ TermLogger::new( diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index 2999584..e2f85ae 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -24,7 +24,6 @@ use super::date_parse::{DateObject, DatePoint}; /// ```rust /// # use chrono::{Weekday, Local}; /// # use idlefox::date::date_tools::relative_day_to_date; -/// /// let today = Local::now().date_naive(); /// // Get the date for next Monday relative to today /// let monday = relative_day_to_date(Weekday::Mon, Some(today)); @@ -73,8 +72,9 @@ pub fn relative_date_to_date( Some(m) if m.number_from_month() >= context.month() => context .with_month(m.number_from_month()) .ok_or(IdleError::InvalidDate), - Some(_m) => context + Some(m) => context .checked_add_months(Months::new(12)) + .and_then(|d| d.with_month(m.number_from_month())) .ok_or(IdleError::InvalidDate), None if day >= context.day() => Ok(context), None => context @@ -147,6 +147,7 @@ pub enum NaiveDateObject { /// A collection of [NaiveDateObject]s, allowing for sequential and random access to their start dates. /// /// This struct can be used to iterate over a list of dates in order or access any date by its index. +#[cfg_attr(test, derive(PartialEq, Debug))] pub struct NaiveDateList { /// The inner vector inner: Vec, @@ -175,10 +176,14 @@ impl DateObject { context: Option, ) -> Result { match self { - DateObject::Range(date_range) => Ok(NaiveDateObject::Range { - start: date_range.start.to_naive_date(context)?, - stop: date_range.stop.to_naive_date(context)?, - }), + DateObject::Range(date_range) => { + // This shenenigan is important otherwise very long ranges can overlap and become negative making no sense + let start = date_range.start.to_naive_date(context)?; + Ok(NaiveDateObject::Range { + start, + stop: date_range.stop.to_naive_date(Some(start))?, + }) + } DateObject::Single(date_point) => { Ok(NaiveDateObject::Single(date_point.to_naive_date(context)?)) } @@ -250,10 +255,13 @@ impl NaiveDateList { // } #[cfg(test)] pub(crate) mod tests { + + use crate::date::date_parse::DateRange; + use super::*; #[test] - fn test_relative_dates() { + fn test_relative_days() { let date = NaiveDate::from_ymd_opt(2024, 10, 30); let date_next_mon = NaiveDate::from_ymd_opt(2024, 11, 4); let date_next_tue = NaiveDate::from_ymd_opt(2024, 11, 7); @@ -278,4 +286,111 @@ pub(crate) mod tests { date3_next_sat.unwrap() ); } + + #[test] + fn test_relative_date() { + let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); + + assert_eq!( + relative_date_to_date(16, Some(Month::December), context).unwrap(), + NaiveDate::from_ymd_opt(2024, 12, 16).unwrap() + ); + assert_eq!( + relative_date_to_date(7, Some(Month::January), context).unwrap(), + NaiveDate::from_ymd_opt(2025, 1, 7).unwrap() + ); + assert_eq!( + relative_date_to_date(17, None, context).unwrap(), + NaiveDate::from_ymd_opt(2024, 11, 17).unwrap() + ); + assert_eq!( + relative_date_to_date(5, None, context).unwrap(), + NaiveDate::from_ymd_opt(2024, 12, 5).unwrap() + ); + + assert!(relative_date_to_date(52, None, None).is_err()); + // TODO: Do we consider this to be normal behaviour ? + assert!(relative_date_to_date( + 31, + Some(Month::February), + NaiveDate::from_ymd_opt(2020, 1, 30) + ) + .is_err()); + } + + #[test] + fn test_impl_date() { + let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); + + assert_eq!( + DatePoint::Weekday(Weekday::Mon) + .to_naive_date(context) + .unwrap(), + NaiveDate::from_ymd_opt(2024, 11, 11).unwrap() + ); + assert_eq!( + DatePoint::Date { + day: 10, + month: Some(Month::January) + } + .to_naive_date(context) + .unwrap(), + NaiveDate::from_ymd_opt(2025, 1, 10).unwrap() + ); + } + #[test] + fn test_impl_dateobj() { + let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); + let date_a = DatePoint::Date { + day: 10, + month: Some(Month::January), + }; + let date_b = DatePoint::Date { + day: 21, + month: Some(Month::December), + }; + assert_eq!( + DateObject::Single(date_a) + .to_naive_date_object(context) + .unwrap(), + NaiveDateObject::Single(NaiveDate::from_ymd_opt(2025, 1, 10).unwrap()) + ); + + let date_obj = DateObject::Range(DateRange { + start: date_a, + stop: date_b, + }) + .to_naive_date_object(context) + .unwrap(); + assert_eq!( + date_obj, + NaiveDateObject::Range { + start: NaiveDate::from_ymd_opt(2025, 1, 10).unwrap(), + stop: NaiveDate::from_ymd_opt(2025, 12, 21).unwrap() + } + ); + + let vec_obj = NaiveDateList::new(vec![date_obj.clone()]); + assert_eq!(vec_obj.len(), 1); + assert!(!vec_obj.is_empty()); + assert_eq!(vec_obj.get(0).unwrap(), &date_obj); + + assert!(!NaiveDateList::from_context( + vec![DateObject::Single(date_a), DateObject::Single(date_a)], + context, + ) + .unwrap() + .is_empty()); + assert!(NaiveDateList::from_context( + vec![ + DateObject::Single(DatePoint::Date { + day: 32, + month: None + }), + DateObject::Single(date_a) + ], + context, + ) + .is_err()); + } } diff --git a/src/error_handling.rs b/src/error_handling.rs index 7174d1d..9e4c343 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -61,5 +61,20 @@ impl From>> for IdleError { #[cfg(test)] mod tests { - // use super::*; + use super::*; + + fn into_error() -> Result<(), IdleError> { + Err(nom::Err::Error(nom::error::Error::new( + "", + nom::error::ErrorKind::Tag, + )))? + } + + #[test] + fn test_nom_error() { + match into_error() { + Err(IdleError::InvalidDateParsing(_d)) => {} + _ => panic!("The convertion from a nom error into a IdleError failed"), + }; + } } diff --git a/src/io.rs b/src/io.rs index 547c78b..fecf2fa 100644 --- a/src/io.rs +++ b/src/io.rs @@ -35,27 +35,27 @@ type Context<'a> = poise::Context<'a, Data, GenericError>; #[allow(dead_code)] // fields only used for Debug print #[name = "Créer un nouveau Vote"] struct VoteCreation { - /// The title of the event - #[name = "Titre"] - #[placeholder = "Titre de votre événement"] - title: String, - /// The name of the event - #[name = "Nom du jeu"] - #[placeholder = "'FFXIV', 'MHW', 'D&D'..."] - short_name: Option, - /// The group that will be tagged by the bot - #[name = "Groupe"] - #[placeholder = "groupe (sans le @)"] - group: Option, /// The description of the event #[paragraph] #[name = "Description"] #[placeholder = "petite description de votre événement"] description: String, + /// The group that will be tagged by the bot + #[name = "Groupe"] + #[placeholder = "groupe (sans le @)"] + group: Option, /// The time a which the event shall take place #[name = "Horaires"] #[placeholder = "'21h - 23h' par défaut"] hours: Option, + /// The name of the event + #[name = "Nom du jeu"] + #[placeholder = "'FFXIV', 'MHW', 'D&D'..."] + short_name: Option, + /// The title of the event + #[name = "Titre"] + #[placeholder = "Titre de votre événement"] + title: String, // Max fields is 5 so the two below will have to be command-exclusive // #[name = "Date de début du vote"] // #[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"] @@ -65,11 +65,25 @@ struct VoteCreation { // non_days: Option, } +#[cfg(test)] // This default implementation only exists during testing +impl Default for VoteCreation { + fn default() -> Self { + VoteCreation { + description: "Dummy vote".into(), + group: Some("Base group".into()), + hours: Some("21h - 23".into()), + short_name: Some("Base vote".into()), + title: "The base test vote".into(), + } + } +} + /// Creates a Discord Modal for a user-friendly vote creation form. /// /// This function triggers the creation of a modal that allows users to input details about an event they would like to organize. /// The input fields are predefined and include the title, short name of the game or event, group to tag, description, /// and hours at which the event will take place. +#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call #[poise::command(slash_command)] pub async fn vote_modal( ctx: poise::ApplicationContext<'_, Data, GenericError>, @@ -113,6 +127,7 @@ pub enum ListOfRoles { // Since this is a discord command and not a real rust command, this many arguments is "normal" #[allow(clippy::too_many_arguments)] #[poise::command(prefix_command, slash_command)] +#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call pub async fn vote_command( ctx: Context<'_>, #[description = "Titre"] title: String, @@ -137,6 +152,7 @@ pub async fn vote_command( // Since this is a discord command and not a real rust command, this many arguments is "normal" #[allow(clippy::too_many_arguments)] #[poise::command(prefix_command, slash_command)] +#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call pub async fn short_vote( ctx: Context<'_>, #[description = "Titre"] title: String, @@ -158,8 +174,9 @@ pub async fn short_vote( /// /// Text command for the creation of votes that span on a very long period to decide on dates for larger-scale events. /// Takes mandatory title, description, beginning and end date and optional starting date for the vote. -#[allow(clippy::too_many_arguments)] -#[poise::command(prefix_command, slash_command)] // i have no idea what causes this warning +#[allow(clippy::too_many_arguments)] // As this is not a real command by a discord command, there isn't really that many arguments +#[poise::command(prefix_command, slash_command)] +#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call pub async fn long_vote( ctx: Context<'_>, #[description = "Titre"] title: String, @@ -179,6 +196,8 @@ pub async fn long_vote( /// The main discord interaction loop /// /// Registers all functions and starts a bot client +// As an async loop it is untestable by nature, however thsi loop aims to stay as simple as possible to be "self testing" +#[cfg(not(tarpaulin_include))] pub async fn discord_main_loop() { let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN"); let intents = serenity::GatewayIntents::non_privileged(); diff --git a/src/main.rs b/src/main.rs index 20c5d66..7a6d7a1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use idlefox::config::init_logger; use idlefox::io::discord_main_loop; +// The main loop is untestable #[cfg(not(tarpaulin_include))] #[tokio::main] async fn main() { diff --git a/src/votes.rs b/src/votes.rs index 90e219e..63fec8d 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -127,5 +127,12 @@ static PENDING_EVENTS: LazyLock = LazyLock::new(OngoingEvents::ne #[cfg(test)] mod tests { - // use super::*; + use super::*; + + // Test all structs can be safely initialized + #[test] + fn init_test() { + let _e = PendingEvents::new(); + let _o = OngoingEvents::new(); + } }