Adds coverage (and a badge) to the project

This commit is contained in:
Dandaedre 2024-11-03 02:36:35 +01:00
parent 60519150d1
commit 52775f26b7
8 changed files with 205 additions and 23 deletions

View File

@ -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.

23
badge.svg Normal file
View File

@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="93" height="20">
<linearGradient id="smooth" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<mask id="round">
<rect width="93" height="20" rx="3" fill="#fff"/>
</mask>
<g mask="url(#round)">
<rect width="64" height="20" fill="#555"/>
<rect x="64" width="29" height="20" fill="#3c1"/>
<rect width="93" height="20" fill="url(#smooth)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
<text x="32" y="15" fill="#010101" fill-opacity=".3">coverage</text>
<text x="32" y="14">coverage</text>
<text x="78" y="15" fill="#010101" fill-opacity=".3">100</text>
<text x="78" y="14">100</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 885 B

View File

@ -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(

View File

@ -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<NaiveDateObject>,
@ -175,10 +176,14 @@ impl DateObject {
context: Option<NaiveDate>,
) -> Result<NaiveDateObject, IdleError> {
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());
}
}

View File

@ -61,5 +61,20 @@ impl From<nom::Err<nom::error::Error<&str>>> 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"),
};
}
}

View File

@ -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<String>,
/// The group that will be tagged by the bot
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
/// 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<String>,
/// The time a which the event shall take place
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: Option<String>,
/// The name of the event
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
/// 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<String>,
}
#[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();

View File

@ -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() {

View File

@ -127,5 +127,12 @@ static PENDING_EVENTS: LazyLock<OngoingEvents> = 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();
}
}