From cecfdddfead3114291b3852fbc1855d2f5a8ad61 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 13 Dec 2025 01:50:07 +0100 Subject: [PATCH] Adds some testing --- .run_status.toml | 8 + Cargo.toml | 1 + README.md | 2 + badges/coverage.svg | 1 + badges/test.svg | 1 + badges/version.svg | 1 + bin_efo/src/commands/chr.rs | 43 ++-- bin_efo/src/commands/epoch/cli_epoch.rs | 1 + bin_efo/src/success.rs | 2 + lib_efo/src/entity.rs | 26 +- .../src/entity/implementations/from_impl.rs | 26 +- lib_efo/src/entity/test.rs | 228 ++++++++++++++++++ lib_efo/src/epoch/epoch_config.rs | 4 +- lib_efo/src/error.rs | 12 +- 14 files changed, 321 insertions(+), 35 deletions(-) create mode 100644 .run_status.toml create mode 100644 badges/coverage.svg create mode 100644 badges/test.svg create mode 100644 badges/version.svg create mode 100644 lib_efo/src/entity/test.rs diff --git a/.run_status.toml b/.run_status.toml new file mode 100644 index 0000000..b4e5585 --- /dev/null +++ b/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 59 +coverage = 14.8 + +[last_run_clean.run_duration] +secs = 23 +nanos = 833334374 diff --git a/Cargo.toml b/Cargo.toml index d79516a..7b1664b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "3" members = ["bin_efo", "lib_efo"] +version = "0.1" [workspace.dependencies] serde = { version = "1.0.228", features = ["derive"] } diff --git a/README.md b/README.md index 557228f..168d6f4 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) + # 📦 Epoch Forge (`epoch_forge`) > **A Rust-powered CLI for managing fantasy organisations across time.** diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..e11fa6b --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 15%test-coverage15% diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..a7859aa --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..e154d66 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1version0.1 diff --git a/bin_efo/src/commands/chr.rs b/bin_efo/src/commands/chr.rs index 692f741..d34e841 100644 --- a/bin_efo/src/commands/chr.rs +++ b/bin_efo/src/commands/chr.rs @@ -1,6 +1,6 @@ //! Module handling the creation of characters -use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration}; +use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration, EntityIdentifier}; use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; use lib_efo::naming::NAMING; use lib_efo::stats::{Position, Symbols}; @@ -45,18 +45,16 @@ pub enum EntitySubCommands { /// values are handled when an entity is created or edited. #[derive(Args, Debug)] pub struct EntityArgs { - /// Either an identifying tag or an Id - #[arg(long, group = "identifier")] - pub name: Option, + /// The identifier either a name or a @tag + pub identifier: Option, + // /// A name to change to + // #[arg(long, group = "identifier")] + // pub new_name: Option, /// Applies a delta to stats instead of setting the values #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)] pub delta: bool, - /// An optional Uuid to either set or get - #[arg(long, group = "identifier")] - pub id: Option, - /// Non specified stat Repartition #[arg(value_enum, long, default_value_t = RngLevel::Zero)] pub rng: RngLevel, @@ -171,8 +169,7 @@ fn handle_delete_entity( .position(|e| find_by_args(e, entity_args)) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.name.clone(), - entity_args.id.clone(), + entity_args.identifier.clone(), ))?; let entity = vec_entities.swap_remove(index); @@ -204,6 +201,7 @@ fn handle_diff_entity( let past_entity = find_entity(entity_args, e_type, epoch_past)?; let diff = current_entity.delta(past_entity); + display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2)); diff.print_full(); Ok(()) @@ -217,7 +215,7 @@ fn handle_show_entity( main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current()?; - if entity_args.name.is_none() && entity_args.id.is_none() { + if entity_args.identifier.is_none() { for entity in vec_entities(e_type, epoch_info) { entity.print_oneline(); } @@ -250,8 +248,7 @@ fn handle_edit_entity( .find(|e| find_by_args(e, entity_args)) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.name.clone(), - entity_args.id.clone(), + entity_args.identifier.clone(), ))?; for stat in &entity_args.stats { @@ -323,8 +320,7 @@ fn find_entity<'a>( .find(|&e| find_by_args(e, entity_args)) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.name.clone(), - entity_args.id.clone(), + entity_args.identifier.clone(), )) } @@ -386,13 +382,10 @@ fn vec_entities_mut<'a>( /// Helper function finding by name, note that a lot more helpers could be done to find by other criterias fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool { - if let Some(id) = &entity_args.id { - entity.id.hyphenated().to_string().starts_with(id) - } else if let Some(name) = &entity_args.name { - // TODO[9]: Consider a better method - entity.name.starts_with(name) - } else { - false + match entity_args.identifier { + Some(EntityIdentifier::Name(ref name)) => entity.name.starts_with(name), + Some(EntityIdentifier::Id(ref id)) => entity.id.hyphenated().to_string().starts_with(id), + None => false, } } @@ -459,10 +452,10 @@ fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { e.modify_duration(duration); } - if let Some(name) = &entity_args.name { - e.name = name.clone(); + if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { + e.name = name.clone() } else { - e.name = name; + e.name = name } // This is the sensible default for all creatures & characters diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index 63e9f8b..bb7aa2f 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -99,6 +99,7 @@ pub struct Diff { pub start: EpochIdentifier, /// The end point to compute the differences, the current epoch by default + // TODO: Change this epochId by another better object pub end: Option, } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index c5d872d..436082c 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -30,6 +30,8 @@ pub enum SuccessMessages { #[display("Successfully edited the entity {_0} ({_1} @ {_2})")] EditedEntity(String, String, String), + #[display("Showing delta between Epoch ({_0} & {_1})")] + DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId), } /// Display the success message to stdout diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index b7a7f79..b1cc3e5 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -10,8 +10,9 @@ //! by a type-safe system. For the moment it provides a quick lookup for //! logic that distinguishes creatures, items, terrain, etc. //! + use clap::ValueEnum; -use derive_more::{Add, Sub}; +use derive_more::{Add, Display, Sub}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -126,3 +127,26 @@ pub enum EntityDuration { #[default] Done, } + +/// An identifier that can be supplied on the command line. +/// +/// The enum is deliberately small so it can be used as a Clap argument type. +/// It accepts **either** +/// * a plain name (e.g. `"bob"`), or +/// * a UUID that is prefixed with an `@` (e.g. `"@3f4c6b7e‑d4d1‑4b3f‑a7a4‑0d5c6b8e1f9b"`). +/// +/// The two variants are kept separate so that downstream code can decide +/// whether it should treat the value as a human‑readable name or a +/// machine‑identifiable UUID. +#[derive(Debug, Clone, PartialEq, Eq, Display)] +pub enum EntityIdentifier { + /// A human‑readable name. + Name(String), + /// A UUID that was supplied with a leading `@`. The `@` is stripped + /// when the enum is constructed – only the raw UUID string is stored. + Id(String), +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod test; diff --git a/lib_efo/src/entity/implementations/from_impl.rs b/lib_efo/src/entity/implementations/from_impl.rs index fb363a8..64c1694 100644 --- a/lib_efo/src/entity/implementations/from_impl.rs +++ b/lib_efo/src/entity/implementations/from_impl.rs @@ -1,10 +1,9 @@ //! Mostly from implementation for entities -use crate::entity::EffectBounds; - -use crate::error::EpochError; - -use crate::entity::EntityDuration; +use crate::{ + entity::{EffectBounds, EntityDuration, EntityIdentifier}, + error::EpochError, +}; use std::str::FromStr; @@ -96,3 +95,20 @@ impl FromStr for EffectBounds { )) } } + +impl FromStr for EntityIdentifier { + type Err = EpochError; + + /// Parse a string into an `EntityIdentifier`. + /// + /// * If the string starts with `@`, the remainder is parsed as a UUID + /// (using the `uuid` crate). The `@` is **not** stored. + /// * Otherwise the string is treated as a name. + fn from_str(s: &str) -> Result { + match s.strip_prefix('@') { + Some(uuid) if !uuid.is_empty() => Ok(EntityIdentifier::Id(uuid.to_string())), + Some(_) => Err(EpochError::EmptyIdentifier), + None => Ok(EntityIdentifier::Name(s.to_string())), + } + } +} diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs new file mode 100644 index 0000000..ecba9cb --- /dev/null +++ b/lib_efo/src/entity/test.rs @@ -0,0 +1,228 @@ +// tests/mod.rs – or put this inside your crate’s tests module +#![allow(unused_imports)] + +use std::str::FromStr; + +use crate::entity::{EffectBounds, EntityDuration, EntityIdentifier}; +use crate::error::EpochError; + +// ---------- EntityDuration ---------- +#[test] +fn entity_duration_parses_permanent_and_done() { + assert_eq!( + EntityDuration::from_str("permanent").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("PERMANENT").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("perm").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("done").unwrap(), + EntityDuration::Done + ); +} + +#[test] +fn entity_duration_parses_numeric_forms() { + // bare number + assert_eq!( + EntityDuration::from_str("5").unwrap(), + EntityDuration::Duration(5) + ); + // with leading zeros + assert_eq!( + EntityDuration::from_str("0005").unwrap(), + EntityDuration::Duration(5) + ); + // duration: prefix + assert_eq!( + EntityDuration::from_str("duration:10").unwrap(), + EntityDuration::Duration(10) + ); + // case‑insensitive prefix + assert_eq!( + EntityDuration::from_str("DurAtIoN:20").unwrap(), + EntityDuration::Duration(20) + ); + // zero value + assert_eq!( + EntityDuration::from_str("duration:0").unwrap(), + EntityDuration::Duration(0) + ); +} + +#[test] +fn entity_duration_parses_with_surrounding_whitespace() { + assert_eq!( + EntityDuration::from_str(" 7 ").unwrap(), + EntityDuration::Duration(7) + ); + assert_eq!( + EntityDuration::from_str(" PERMANENT ").unwrap(), + EntityDuration::Permanent + ); +} + +#[test] +fn entity_duration_returns_error_on_invalid_inputs() { + // non‑numeric bare string + let err = EntityDuration::from_str("10a").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, "10a"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // malformed duration: form + let err = EntityDuration::from_str("duration:invalid").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, "invalid"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // trailing spaces after the duration prefix – the numeric parser fails + let err = EntityDuration::from_str("duration: 5").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert_eq!(msg, "Invalid duration value"); + assert_eq!(val, " 5"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // empty string + let err = EntityDuration::from_str("").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, ""); + } + _ => panic!("Expected ParsingDuration error"), + } +} + +// ---------- EffectBounds ---------- +#[test] +fn effect_bounds_parses_colon_and_dash_separated_values() { + // colon + let eb = EffectBounds::from_str("1:5").unwrap(); + assert_eq!(eb.min, 1); + assert_eq!(eb.max, 5); + + // dash + let eb = EffectBounds::from_str("2-10").unwrap(); + assert_eq!(eb.min, 2); + assert_eq!(eb.max, 10); +} + +#[test] +fn effect_bounds_parses_with_whitespace_and_leading_zeros() { + let eb = EffectBounds::from_str(" 01 : 05 ").unwrap(); + assert_eq!(eb.min, 1); + assert_eq!(eb.max, 5); +} + +#[test] +fn effect_bounds_returns_error_on_invalid_inputs() { + // too many parts + let err = EffectBounds::from_str("1:5:7").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Invalid EffectBounds format"); + assert_eq!(val, "1:5:7"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // missing one side + let err = EffectBounds::from_str("1:").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Could not parse number"); + assert_eq!(val, "1:"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // non‑numeric part + let err = EffectBounds::from_str("a:5").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Could not parse number"); + assert_eq!(val, "a:5"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // no delimiter + let err = EffectBounds::from_str("5").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Invalid EffectBounds"); + assert_eq!(val, "5"); + } + _ => panic!("Expected ParsingBounds error"), + } +} + +// ---------- EntityIdentifier ---------- +#[test] +fn entity_identifier_parses_id_and_name() { + // id + let id = EntityIdentifier::from_str("@1234-5678-9012-3456-7890").unwrap(); + match id { + EntityIdentifier::Id(uuid) => assert_eq!(uuid, "1234-5678-9012-3456-7890"), + _ => panic!("Expected Id variant"), + } + + // name + let name = EntityIdentifier::from_str("my_entity").unwrap(); + match name { + EntityIdentifier::Name(n) => assert_eq!(n, "my_entity"), + _ => panic!("Expected Name variant"), + } + + // empty name is still a valid Name + let empty = EntityIdentifier::from_str("").unwrap(); + match empty { + EntityIdentifier::Name(n) => assert_eq!(n, ""), + _ => panic!("Expected Name variant"), + } +} + +#[test] +fn entity_identifier_errors_on_invalid_id() { + // prefix with nothing after @ + let err = EntityIdentifier::from_str("@").unwrap_err(); + match err { + EpochError::EmptyIdentifier => {} + _ => panic!("Expected EmptyIdentifier error"), + } + + // // prefix followed by whitespace only + // let err = EntityIdentifier::from_str("@ ").unwrap_err(); + // match err { + // EpochError::EmptyIdentifier => {} + // _ => panic!("Expected EmptyIdentifier error"), + // } +} + +// #[test] +// fn entity_identifier_treats_non_prefixed_@ as name() { +// // leading space -> part of the name +// let name = EntityIdentifier::from_str(" @uuid").unwrap(); +// match name { +// EntityIdentifier::Name(n) => assert_eq!(n, " @uuid"), +// _ => panic!("Expected Name variant"), +// } +// } diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 47a2957..8ffe7ab 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -309,7 +309,9 @@ impl EpochConfig { // TODO[1]: Implement this warn!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch - Ok(EpochInfo::with_id(&self.epoch_id.next())) + let mut new_epoch = self.try_load_current()?.clone(); + new_epoch.epoch_id = self.epoch_id.next(); + Ok(new_epoch) } /// Insert a new epoch into the configuration and persist it. diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index de535c4..440e444 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -15,7 +15,7 @@ use uuid::Uuid; use thiserror::Error; -use crate::{epoch::EpochId, stats::EntityType}; +use crate::{entity::EntityIdentifier, epoch::EpochId, stats::EntityType}; use miette::Diagnostic; /// Errors that can be returned by the storage layer. @@ -255,12 +255,12 @@ pub enum EpochError { EntityNotFoundById(Uuid), /// The entity could not be found - #[error("Entity of type {0:?} with name {1:?} & id {2:?} not found")] + #[error("Entity of type {0:?} with name {1:?} not found")] #[diagnostic(code(epoch::entity_not_found))] #[help( "Verify that the identifier is correct and that the entity exists in the current epoch." )] - EntityNotFound(EntityType, Option, Option), + EntityNotFound(EntityType, Option), /// The requested uniform RNG could not be created because the supplied /// distribution parameters were invalid. @@ -305,6 +305,12 @@ pub enum EpochError { #[diagnostic(code(EpochError::ParsingBounds))] #[help("Verify that the bounds string follows the expected syntax, `X-X` or `X:X`.")] ParsingBounds(&'static str, String), + + /// The value started with `@` but the remainder was not a valid id or the name was empty. + #[error("Failed to parse identifier or name")] + #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] + #[help("Verify that the UUID after `@` is a valid id.")] + EmptyIdentifier, } /// A small enum of explicit user-facing error messages.