Adds a lot of testing and examples

This commit is contained in:
Dandaedre 2024-11-06 18:17:06 +01:00
parent 7761751eae
commit 5f996b26e3
8 changed files with 322 additions and 47 deletions

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 78%"><title>test-coverage: 78%</title><linearGradient id="bms-ed80297b110701f8" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-ed80297b110701f8"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-ed80297b110701f8)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-ed80297b110701f8)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">78%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">78%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 93%"><title>test-coverage: 93%</title><linearGradient id="bms-20996527e2156024" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-20996527e2156024"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-20996527e2156024)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-20996527e2156024)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">93%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">93%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -155,7 +155,7 @@ pub enum NaiveDateObject {
/// over the dates in order or direct access to any date by its index. The structure is designed to handle
/// different sources of date information, allowing for flexible data manipulation based on the provided dates.
#[derive(Debug, Default, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq))]
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct NaiveDateList {
/// The inner vector
inner: Vec<NaiveDateObject>,

View File

@ -67,6 +67,27 @@ pub enum IdleError {
/// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs.
#[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")]
EventPrune(Vec<Uuid>),
/// Error indicating an event could not be deleted
///
/// This error is raised when attempting to delete an event fails,
/// either due to a problem with bookkeping or because the specified UUID
/// does not correspond to any existing events anymore.
#[error("An event couldn't be deleted (Id: {0})")]
DeleteEvent(Uuid),
/// Error indicating that an ongoing event launch couldn't be performed
///
/// This error was likely raised as a launch operation for an event was already underway.
/// Launching multiple times for the same event may lead to inconsistent states or data corruption.
#[error("Couldn't launch event (Id: {0})")]
LaunchingEvent(Uuid),
/// Error indicating a mutex was poisoned or couldn't be acquired
///
/// This is likely due to a thread being terminated but could also arise from a deadlock or a subtle race condition
#[error("An error happened while trying to acquire a mutex")]
MutexError,
}
impl From<nom::Err<nom::error::Error<&str>>> for IdleError {

View File

@ -16,7 +16,12 @@ pub mod io; // Maybe in lib
mod modules; // Maybe in lib
mod persistence; // Likely in lib
mod server; // Maybe in lib
mod votes; // Likely in lib
pub mod votes; // Likely in lib
mod watchdog; // Definitely in lib
// TODO: Make sensible module re-export
// // Re export
// pub use votes::add_future_event;
// pub use votes::launch_future_event;
//
pub use error_handling::IdleError;
pub use watchdog::main_scheduler_loop;

View File

@ -7,13 +7,19 @@
use idlefox::config::init_logger;
use idlefox::io::discord_main_loop;
use idlefox::main_scheduler_loop;
use tokio::time;
// The main loop is untestable
#[cfg(not(tarpaulin_include))]
#[tokio::main]
async fn main() {
use tokio::task;
init_logger().unwrap();
discord_main_loop().await;
// use date_parse::test_parsing;
// test_parsing();
// TODO: Check that this is actually what we want
task::spawn(discord_main_loop());
task::spawn(main_scheduler_loop(time::interval(
time::Duration::from_secs(60 * 10),
)));
}

View File

@ -9,21 +9,164 @@
//! Note:
//! - The types `UserDataType`, `VoteValueType`, and some fields are marked as deprecated and should not be used.
//! They are placeholders for the actual data structures which need to be defined correctly.
//! - Some code is commented out, such as test cases, which are currently unused.
//!
#![allow(dead_code, deprecated)]
#![allow(deprecated)]
use std::{
collections::HashMap,
fmt::Display,
sync::{LazyLock, Mutex},
};
use chrono::{Months, NaiveDateTime, TimeDelta};
use chrono::{NaiveDateTime, TimeDelta};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{date::date_tools::NaiveDateList, error_handling::IdleError};
// Helper functions, user facing
// Helper functions, user facing
/// Adds a parsed vote to the list of planned events.
///
/// This function will use the `PendingEvents` instance to store the provided event.
/// The structure of the input parameter `event` is expected to be a correctly formatted parsed vote.
///
/// ## Parameters:
/// - `event`: A `ParsedVote` struct representing the details of the event to be scheduled.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{add_pending_event, ParsedVote};
/// let parsed_vote = ParsedVote::default();
///
/// let id = add_pending_event(parsed_vote).unwrap();
/// ```
pub fn add_pending_event(event: ParsedVote) -> Result<Uuid, IdleError> {
PENDING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.add_pending_event(event)
}
/// Launches a pending event by transferring it from the pending to ongoing events list.
///
/// This function identifies an event by its UUID and moves it from the planned (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`. Otherwise, it returns an error of type `IdleError`.
///
/// ## Parameters:
/// - `uuid`: A `Uuid` that uniquely identifies the event to be launched.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{add_pending_event, make_into_ongoing_event, ParsedVote};
/// let id = add_pending_event(ParsedVote::default()).unwrap();
///
/// make_into_ongoing_event(id).unwrap()
/// ```
pub fn make_into_ongoing_event(uuid: Uuid) -> Result<(), IdleError> {
PENDING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.launch(uuid)
}
/// Manually adds an ongoing event.
///
/// This function is intended for internal use and directly adds an event
/// to the list of ongoing events. It expects a UUID and a parsed vote as inputs,
/// using which it updates the `OngoingEvents` instance.
///
/// ## Parameters:
/// - `uuid`: A `Uuid` that uniquely identifies the event to be added.
/// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added.
///
/// ## Example:
/// ```rust
/// # use uuid::Uuid;
/// # use idlefox::votes::{add_ongoing_event, ParsedVote};
/// let uuid = Uuid::new_v4(); // A new id
/// let parsed_vote = ParsedVote::default(); // A very legit event
///
/// add_ongoing_event(uuid, parsed_vote).unwrap();
/// ```
pub fn add_ongoing_event(uuid: Uuid, event: ParsedVote) -> Result<(), IdleError> {
ONGOING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.add_event(uuid, event)?;
Ok(())
}
/// Destroy an event without closing it and officially ending it
///
/// This function removes an ongoing event from the list of ongoing events.
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, del_ongoing_event, make_into_ongoing_event, ParsedVote,
/// # };
/// let id = add_pending_event(ParsedVote::default()).unwrap();
/// make_into_ongoing_event(id).unwrap();
///
/// del_ongoing_event(id).unwrap();
/// ```
pub fn del_ongoing_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
ONGOING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
}
/// Destroy a pending event without closing it
///
/// This function removes a pending event from the list of pending events.
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, del_pending_event, make_into_ongoing_event, ParsedVote,
/// # };
/// let id = add_pending_event(ParsedVote::default()).unwrap();
/// del_pending_event(id).unwrap();
/// ```
pub fn del_pending_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
PENDING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
}
/// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment.
/// # Arguments
///
/// * `uuid` - A Uuid representing the identifier of the event that is to be closed.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote,
/// # };
/// let id = add_pending_event(ParsedVote::default()).unwrap();
/// make_into_ongoing_event(id).unwrap();
/// close_ongoing_event(id).unwrap();
/// ```
pub fn close_ongoing_event(uuid: Uuid) -> Result<ParsedVote, IdleError> {
ONGOING_EVENTS
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.close_event(uuid)
}
/// Placeholder datatype
///
/// Links to an event, active or planned
@ -36,12 +179,13 @@ type EventDataType = Uuid;
type UserDataType = String;
/// What an user voted for
#[deprecated(note = "This is an incorrect type to define a vote")]
#[deprecated(note = "This is an incorrect type to define a voting ballot")]
type VoteValueType = String;
/// A vote, represents a user interraction towards an event
#[derive(Serialize, Deserialize)]
pub(crate) struct Vote {
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(test, derive(Clone))]
pub(crate) struct Ballot {
/// The event the vote refers to
linked_event: EventDataType,
/// The user casting the vote
@ -50,11 +194,8 @@ pub(crate) struct Vote {
vote_value: VoteValueType,
}
/// Data type representing a date
type DateDataType = String;
/// The global status of the event
#[derive(Serialize, Deserialize, Default)]
#[derive(Serialize, Deserialize, Default, Debug, Clone, Copy)]
pub(crate) enum EventStatus {
#[default]
/// The event exists but wasn't started yet
@ -70,8 +211,9 @@ pub(crate) enum EventStatus {
}
/// An event, wether ongoing or planned
#[derive(Serialize, Deserialize, Default)]
pub(crate) struct MockEvent {
#[derive(Debug, Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Clone))]
pub struct ParsedVote {
/// The title of the even
title: String,
/// Description of the event
@ -81,14 +223,29 @@ pub(crate) struct MockEvent {
/// Date at which to autostart the vote process
launch_date: NaiveDateTime,
/// Date at which to autoclose the vote process
// TODO: this option is useless, we need a time to close the votes anyway, just fill it to launch+12months or something smarter
close_date: Option<NaiveDateTime>,
close_date: NaiveDateTime,
/// The inner list of votes cast
votes: Vec<Vote>,
votes: Vec<Ballot>,
/// The list of values to vote for, this list all the valid dates to vote for
vote_values: NaiveDateList,
list_candidates: NaiveDateList,
// / The vote type
}
impl MockEvent {
impl ParsedVote {
// #[allow(dead_code, unused_variables)]
// pub(crate) fn new(
// title: String,
// description: String,
// status: EventStatus,
// launch_date: NaiveDateTime,
// close_date: NaiveDateTime,
// // ballots: Vec<Ballot>,
// list_candidates: NaiveDateList,
// ) -> Self {
// // Have a rather smart close date if not specified
// todo!()
// }
/// All the logic behind a vote becoming live
fn launch(&mut self, id: Uuid) -> Result<(), IdleError> {
let _ = id;
@ -100,15 +257,29 @@ impl MockEvent {
}
}
// impl From<VoteContainer> for ParsedVote {
// fn from(value: VoteContainer) -> Self {
// todo!()
// }
// }
impl Display for ParsedVote {
/// A display for a vote, it is exactly what the discord bot will send
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO: Complete this (vky)
write!(f, "{:?}", self)
}
}
// This split in two differents structs conceptually represents
// the fact that very differents actions will be performed for each struct
type EventListType = HashMap<Uuid, MockEvent>;
type EventListType = HashMap<Uuid, ParsedVote>;
// The list of pending events, not yet started
///
/// This struct represents the collection of events that have been scheduled but have not yet begun.
#[derive(Serialize, Deserialize)]
pub(crate) struct PendingEvents {
pub struct PendingEvents {
/// The list of pending events
pending_events: EventListType,
}
@ -126,8 +297,10 @@ impl PendingEvents {
/// Add a new event to the list of upcoming events.
///
/// This function generates a new UUID for the event before adding it to the list.
fn add_future_event(&mut self, event: MockEvent) {
self.pending_events.insert(Uuid::new_v4(), event);
fn add_pending_event(&mut self, event: ParsedVote) -> Result<Uuid, IdleError> {
let id = Uuid::new_v4();
self.pending_events.insert(id, event);
Ok(id)
}
/// Process and activate all upcoming events if the auto-launch time has been reached.
@ -135,7 +308,7 @@ impl PendingEvents {
/// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list.
pub fn process_upcoming(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> {
self.pending_events
.insert(Uuid::new_v4(), MockEvent::default());
.insert(Uuid::new_v4(), ParsedVote::default());
self.find_upcoming(current_time)
.iter()
.try_for_each(|uuid| {
@ -152,7 +325,8 @@ impl PendingEvents {
.pending_events
.remove(&uuid)
.ok_or(IdleError::EventLaunch(uuid))?;
ONGOING_EVENTS.lock().unwrap().add_event(uuid, event)?;
add_ongoing_event(uuid, event)?;
// make_into_ongoing_event(uuid)?;
Ok(())
}
@ -166,17 +340,24 @@ impl PendingEvents {
.map(|(k, _v)| (*k))
.collect()
}
/// delete the event without launching it
pub fn del_event(&mut self, uuid: Uuid) -> Result<ParsedVote, IdleError> {
self.pending_events
.remove(&uuid)
.ok_or(IdleError::DeleteEvent(uuid))
}
}
/// The list of ongoing events, not yet closed
///
/// This struct represents the collection of events that have been initiated but have not yet concluded.
#[derive(Serialize, Deserialize)]
pub(crate) struct OngoingEvents {
pub struct OngoingEvents {
/// The list of ongoing events
ongoing_events: EventListType,
}
#[allow(dead_code, unused_variables)]
impl OngoingEvents {
/// Create a new empty list of ongoing events, called in case of a first initialization.
///
@ -215,12 +396,7 @@ impl OngoingEvents {
fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
self.ongoing_events
.iter()
.filter(|(_, e)| {
e.close_date
.unwrap_or(e.launch_date.checked_add_months(Months::new(12)).unwrap())
.signed_duration_since(current_time)
> TimeDelta::days(3)
})
.filter(|(_, e)| e.close_date.signed_duration_since(current_time) > TimeDelta::days(3))
.map(|(k, _)| *k)
.collect()
}
@ -228,11 +404,29 @@ impl OngoingEvents {
/// Add a new event to the list of ongoing events.
///
/// This function also launch the event based and adds a callback with the Uuid of the original caller.
pub(crate) fn add_event(&mut self, id: Uuid, mut event: MockEvent) -> Result<(), IdleError> {
pub(crate) fn add_event(&mut self, id: Uuid, mut event: ParsedVote) -> Result<(), IdleError> {
event.launch(id)?;
self.ongoing_events.insert(id, event);
Ok(())
}
/// delete the event without launching it
pub fn del_event(&mut self, uuid: Uuid) -> Result<ParsedVote, IdleError> {
self.ongoing_events
.remove(&uuid)
.ok_or(IdleError::DeleteEvent(uuid))
}
/// Close an event removing it from the ongoing event list
pub fn close_event(&mut self, uuid: Uuid) -> Result<ParsedVote, IdleError> {
// TODO: Another vkypoint, as we cant continue without knowing how to send a message
let event = self
.ongoing_events
.remove(&uuid)
.ok_or(IdleError::LaunchingEvent(uuid))?;
let str_event = event.to_string();
// TODO: Do something with this string
Ok(event)
}
}
/// The thread safe list of pending events
@ -250,7 +444,6 @@ mod tests {
// Test all structs can be safely initialized
#[test]
#[ignore]
fn init_test() {
let _e = PendingEvents::new();
let _o = OngoingEvents::new();
@ -270,17 +463,60 @@ mod tests {
}
#[test]
#[ignore]
fn test_launch() {
assert!(MockEvent::default().launch(Uuid::new_v4()).is_ok());
fn test_base_vote_handling() {
// assert!(ParsedVote::default().launch(Uuid::new_v4()).is_ok());
let ev = ParsedVote::default();
// Can we add a vote ?
let id = add_pending_event(ev.clone()).unwrap();
assert!(PENDING_EVENTS
.lock()
.unwrap()
.pending_events
.contains_key(&id)); // Is the vote present ?
del_pending_event(id).unwrap();
assert!(!PENDING_EVENTS
.lock()
.unwrap()
.pending_events
.contains_key(&id)); // Is the vote now deleted
let id = add_pending_event(ev.clone()).unwrap();
make_into_ongoing_event(id).unwrap(); // Launching this event
assert!(!PENDING_EVENTS
.lock()
.unwrap()
.pending_events
.contains_key(&id)); // Is the vote now not pending
assert!(ONGOING_EVENTS
.lock()
.unwrap()
.ongoing_events
.contains_key(&id)); // Is the vote now ongoing
close_ongoing_event(id).unwrap();
assert!(!ONGOING_EVENTS
.lock()
.unwrap()
.ongoing_events
.contains_key(&id)); // Is the vote now not ongoing
let id = add_pending_event(ev.clone()).unwrap();
make_into_ongoing_event(id).unwrap(); // Launching this event
del_ongoing_event(id).unwrap();
assert!(!ONGOING_EVENTS
.lock()
.unwrap()
.ongoing_events
.contains_key(&id)); // Is the vote now not ongoing
}
#[test]
#[ignore]
fn test_upcomming_events() {
let e = MockEvent::default();
let _e = ParsedVote::default();
// e.launch_date = NaiveDateTime
// ; PENDING_EVENTS.lock().unwrap().add_future_event(e)
// ; PENDING_EVENTS.lock().unwrap().add_pending_event(e)
}
#[test]

View File

@ -27,7 +27,7 @@ use crate::votes::{ONGOING_EVENTS, PENDING_EVENTS};
/// loop continues indefinitely, allowing for continuous scheduling of the
/// `watchdog_update` task at the specified intervals.
#[cfg(not(tarpaulin_include))] // This loop is untestable instead the logic is kept to the minimal
async fn main_scheduler_loop(mut interval: tokio::time::Interval) {
pub async fn main_scheduler_loop(mut interval: tokio::time::Interval) {
loop {
interval.tick().await;
// tokio::spawn(async {watchdog_update().await;}); // For async task

View File

@ -1,6 +1,13 @@
#[cfg(test)]
mod tests {
use idlefox::votes::{
add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote,
};
#[test]
fn generic_integration_test() {}
fn generic_integration_test() {
let id = add_pending_event(ParsedVote::default()).unwrap();
make_into_ongoing_event(id).unwrap();
close_ongoing_event(id).unwrap();
}
}