From f05a6184f00998889990d7ced8e0cd0f9fc51695 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 05:17:43 +0100 Subject: [PATCH] Adds more testing updates coverage --- .run_status.toml | 6 +- Cargo.lock | 20 +++ badges/coverage.svg | 2 +- lib_efo/Cargo.toml | 2 +- lib_efo/src/epoch.rs | 79 +++++++++++ lib_efo/src/epoch/epoch_traits.rs | 124 ++++++++++++++++++ ...raits__tests__config_writable_as_json.snap | 8 ++ ...ch_traits__tests__prettiable_as_table.snap | 10 ++ lib_efo/src/lib.rs | 81 ++++++++---- ...efo__epoch__test__epoch_identifier_id.snap | 5 + ...fo__epoch__test__epoch_identifier_tag.snap | 5 + .../lib_efo__tests__dummy_vec_oneline.snap | 5 + lib_efo/src/stats/implementations/test.rs | 50 +++++++ 13 files changed, 370 insertions(+), 27 deletions(-) create mode 100644 lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__config_writable_as_json.snap create mode 100644 lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__prettiable_as_table.snap create mode 100644 lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_id.snap create mode 100644 lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_tag.snap create mode 100644 lib_efo/src/snapshots/lib_efo__tests__dummy_vec_oneline.snap diff --git a/.run_status.toml b/.run_status.toml index 12ed86c..bf74534 100644 --- a/.run_status.toml +++ b/.run_status.toml @@ -1,8 +1,8 @@ [last_run_clean] run_status = "Success" -lines_parsed = 83 -coverage = 50.17 +lines_parsed = 98 +coverage = 52.9 [last_run_clean.run_duration] secs = 25 -nanos = 72743368 +nanos = 607715147 diff --git a/Cargo.lock b/Cargo.lock index d7d9682..00d03ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -317,6 +317,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + [[package]] name = "getrandom" version = "0.3.4" @@ -420,6 +426,7 @@ dependencies = [ "rand", "serde", "serde_json", + "tempfile", "thiserror", "uuid", ] @@ -753,6 +760,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "termcolor" version = "1.4.1" diff --git a/badges/coverage.svg b/badges/coverage.svg index d697e70..0416daf 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 50%test-coverage50% \ No newline at end of file +test-coverage: 53%test-coverage53% \ No newline at end of file diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index e96c4e6..b96c3cb 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -20,4 +20,4 @@ once_cell = "1.21.3" [dev-dependencies] insta = {workspace = true} - +tempfile = "3.23.0" diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs index 404bae4..c26c6fd 100644 --- a/lib_efo/src/epoch.rs +++ b/lib_efo/src/epoch.rs @@ -165,3 +165,82 @@ impl FromStr for EpochIdentifier { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod test { + use insta::assert_debug_snapshot; + // tests/epoch.rs + use serde_json::to_string_pretty; + + use crate::epoch::{EpochId, EpochIdentifier, SaveMode, TagList}; + + #[test] + fn epoch_id_arithmetic() { + let id = EpochId::new(42); + assert_eq!(*id, 42); + + let next = id.next(); + assert_eq!(*next, 43); + + let added = id.add_to_epoch(5); + assert_eq!(*added, 47); + + let negative = id.add_to_epoch(-10); + assert_eq!(*negative, 32); + + // saturating behaviour + let zero = EpochId::new(0); + let under = zero.add_to_epoch(-1); + assert_eq!(*under, 0); + } + + #[test] + fn epoch_identifier_parsing() { + // numeric string → Id + let parsed: EpochIdentifier = "7".parse().unwrap(); + assert!(matches!(parsed, EpochIdentifier::Id(_))); + + // non‑empty string → Tag + let parsed: EpochIdentifier = "winter-b".parse().unwrap(); + assert!(matches!(parsed, EpochIdentifier::Tag(_))); + + // empty string → error + assert!("".parse::().is_err()); + } + + #[test] + fn epoch_identifier_serialisation() { + // Id variant should serialize to a number + let id = EpochIdentifier::Id(EpochId::new(13)); + let json = to_string_pretty(&id).unwrap(); + assert_debug_snapshot!("epoch_identifier_id", json); + + // Tag variant should serialize to a string + let tag = EpochIdentifier::Tag("alpha".into()); + let json = to_string_pretty(&tag).unwrap(); + assert_debug_snapshot!("epoch_identifier_tag", json); + } + + #[test] + fn tag_list_deref_and_mut() { + let mut list = TagList::new(); + list.push("one".into()); + list.push("two".into()); + + // Deref to Vec + assert_eq!(list[0], "one"); + assert_eq!(list[1], "two"); + + // Mutating through DerefMut + list[1] = "TWO".into(); + assert_eq!(list[1], "TWO"); + } + + #[test] + fn save_mode_variants() { + // Just a quick check that the variants exist and can be constructed + let _do_not = SaveMode::DoNotErase; + let _erase = SaveMode::Erase; + } +} diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs index 9fd4488..059e38a 100644 --- a/lib_efo/src/epoch/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -108,3 +108,127 @@ pub trait ConfigWritable: Serialize { Ok(()) } } + +#[allow(clippy::unwrap_used)] +#[cfg(test)] +mod tests { + use super::*; + use derive_more::Display; + use insta::assert_snapshot; + use tempfile::tempdir; + + /// A tiny helper struct that implements every trait you defined. + #[derive(Debug, Clone, PartialEq, Serialize, Table, Display)] + #[display("{id}:{value}")] + struct DummyItem { + id: Uuid, + value: i32, + #[serde(skip)] + #[table(skip)] + save: String, + } + + impl DummyItem { + fn new(value: i32) -> Self { + Self { + id: Uuid::nil(), + value, + save: tempdir() + .expect("Tempdir") + .path() + .join("dummy.json") + .to_string_lossy() + .into(), + } + } + } + + impl Diffable for DummyItem { + fn delta(&self, other: &Self) -> Self { + Self { + id: self.id, // keep the same id + value: self.value - other.value, + save: self.save.clone(), + } + } + } + + // impl Applyable for DummyItem {} + // impl Nextable for DummyItem {} + impl Prettiable for DummyItem {} + + /* ------------------- ConfigWritable ------------------- */ + impl ConfigWritable for DummyItem { + fn save_path(&self) -> String { + self.save.clone() + } + + fn save_folder(&self) -> String { + String::new() + } + } + + #[test] + fn test_prettiable_as_table() { + let item = DummyItem::new(42); + let table = DummyItem::as_table(vec![&item]).expect("Dummytable"); + assert_snapshot!(format!("{}", table)); + } + + #[test] + fn test_prettiable_show_as_log() { + DummyItem::new(7).show_as_log(); + } + + #[test] + fn test_config_writable_as_json() { + let item = DummyItem::new(123); + let json = item.as_json("test action".into()).unwrap(); + assert_snapshot!(json); + } + + // fn dummy_with_tempfile(value: i32) -> (DummyItem, std::path::PathBuf) { + // let dummy = DummyItem::new(value); + // (dummy.clone(), dummy.save.clone().into()) + // } + // #[test] + // fn test_config_writable_save_with_context_erase() { + // let (item, path) = dummy_with_tempfile(10); + // // Erase: we expect a file to be created (or overwritten) + // item.save_with_context("Erase test", &SaveMode::DoNotErase) + // .unwrap(); + + // // Verify file contents + // let mut file = File::open(&path).unwrap(); + // let mut contents = String::new(); + // file.read_to_string(&mut contents).unwrap(); + + // assert_snapshot!(contents); + // } + + // #[test] + // fn test_config_writable_save_with_context_donot_erase() { + // let (item, _path) = dummy_with_tempfile(20); + + // // First write – must succeed + // item.save_with_context("DoNotErase test 1", &SaveMode::DoNotErase) + // .unwrap(); + + // // Second write – should fail with `ConfigCreation` because the file + // // already exists. + // let err = item + // .save_with_context("DoNotErase test 2", &SaveMode::DoNotErase) + // .unwrap_err(); + + // assert_snapshot!(format!("{}", err)); + // } + + #[test] + fn test_diffable_delta() { + let a = DummyItem::new(30); + let b = DummyItem::new(15); + let diff = a.delta(&b); + assert_eq!(diff.value, 15); + assert_eq!(diff.id, a.id); // same id + } +} diff --git a/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__config_writable_as_json.snap b/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__config_writable_as_json.snap new file mode 100644 index 0000000..0d5466b --- /dev/null +++ b/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__config_writable_as_json.snap @@ -0,0 +1,8 @@ +--- +source: lib_efo/src/epoch/epoch_traits.rs +expression: json +--- +{ + "id": "00000000-0000-0000-0000-000000000000", + "value": 123 +} diff --git a/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__prettiable_as_table.snap b/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__prettiable_as_table.snap new file mode 100644 index 0000000..0bb3a6b --- /dev/null +++ b/lib_efo/src/epoch/snapshots/lib_efo__epoch__epoch_traits__tests__prettiable_as_table.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/epoch/epoch_traits.rs +expression: "format!(\"{}\", table)" +--- +┌──────────────────────────────────────┬───────┐ +│ id  │ value │ +├──────────────────────────────────────┼───────┤ +│ 00000000-0000-0000-0000-000000000000 │ 42  │ +└──────────────────────────────────────┴───────┘ + diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 45ea9bf..31154bf 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -18,33 +18,33 @@ pub mod naming; pub mod stats; pub mod utils; -use std::io::Result as IoResult; +// use std::io::Result as IoResult; -/// Marker trait for anything that can be persisted via the `Store` abstraction. -/// -/// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the -/// compiler can infer that the type is both serialisable *and* deserialisable. -pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {} -impl Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {} +// /// Marker trait for anything that can be persisted via the `Store` abstraction. +// /// +// /// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the +// /// compiler can infer that the type is both serialisable *and* deserialisable. +// pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {} +// impl Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {} -/// The generic store. All domain entities that need persistence should use this trait. -/// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`. -pub trait Store -where - T: Persistable, -{ - /// Read a value identified by `id`. - fn read(&self, id: &str) -> IoResult>; +// /// The generic store. All domain entities that need persistence should use this trait. +// /// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`. +// pub trait Store +// where +// T: Persistable, +// { +// /// Read a value identified by `id`. +// fn read(&self, id: &str) -> IoResult>; - /// Write (or overwrite) a value identified by `id`. - fn write(&self, id: &str, value: &T) -> IoResult<()>; +// /// Write (or overwrite) a value identified by `id`. +// fn write(&self, id: &str, value: &T) -> IoResult<()>; - /// Delete the value identified by `id`. - fn delete(&self, id: &str) -> IoResult<()>; +// /// Delete the value identified by `id`. +// fn delete(&self, id: &str) -> IoResult<()>; - /// List all ids known to this store. - fn list_ids(&self) -> IoResult>; -} +// /// List all ids known to this store. +// fn list_ids(&self) -> IoResult>; +// } /// A trait for types that can be displayed in a command-line tool. /// /// Implementors should provide three levels of representation: @@ -103,3 +103,40 @@ impl Displayable for Vec { .join(",") } } + +// tests/api.rs -------------------------------------------------------------- +#[cfg(test)] +mod tests { + use super::*; + use insta::assert_snapshot; + struct Dummy { + name: String, + } + + impl Displayable for Dummy { + fn oneline_display(&self) -> String { + self.name.clone() + } + } + + #[test] + fn test_displayable_vec() { + let vec = vec![ + Dummy { + name: "Alice".to_string(), + }, + Dummy { + name: "Bob".to_string(), + }, + Dummy { + name: "Eve".to_string(), + }, + ]; + + assert_eq!(vec.oneline_display(), "Alice,Bob,Eve".to_string()); + vec.print_full(); + vec.print_short(); + vec.print_oneline(); + assert_snapshot!("dummy_vec_oneline", vec.oneline_display()); + } +} diff --git a/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_id.snap b/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_id.snap new file mode 100644 index 0000000..73a14ea --- /dev/null +++ b/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_id.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/epoch.rs +expression: json +--- +"{\n \"id\": 13\n}" diff --git a/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_tag.snap b/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_tag.snap new file mode 100644 index 0000000..02010a0 --- /dev/null +++ b/lib_efo/src/snapshots/lib_efo__epoch__test__epoch_identifier_tag.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/epoch.rs +expression: json +--- +"\"alpha\"" diff --git a/lib_efo/src/snapshots/lib_efo__tests__dummy_vec_oneline.snap b/lib_efo/src/snapshots/lib_efo__tests__dummy_vec_oneline.snap new file mode 100644 index 0000000..13778a1 --- /dev/null +++ b/lib_efo/src/snapshots/lib_efo__tests__dummy_vec_oneline.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/lib.rs +expression: vec.oneline_display() +--- +Alice,Bob,Eve diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 55ceb9b..90bfad7 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -58,7 +58,57 @@ fn test_stat_pair_parsing() { assert_pair_ok("Pop -5", ListStats::Population, -5); assert_pair_ok("grow 0", ListStats::Growthrate, 0); } +#[test] +fn stat_pair_ill_formed_errors_are_detected() { + // 1️⃣ No separator at all + let err = StatPair::from_str("justastring").unwrap_err(); + assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); + // 2️⃣ Separator but missing the value + let err = StatPair::from_str("cri:").unwrap_err(); + assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); + + // 3️⃣ Separator but missing the stat name + let err = StatPair::from_str(":10").unwrap_err(); + assert!(matches!(err, EpochError::UnknownStatAcronim(_))); + + // 4️⃣ Two spaces (splits into > 2 parts) + let err = StatPair::from_str("cri 10 20").unwrap_err(); + assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); + + // 5️⃣ Value part is not an integer + let err = StatPair::from_str("cri:abc").unwrap_err(); + assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); + + // 6️⃣ Unknown stat – this is caught by the `ListStats::parse()` call, + // which already returns `IllFormedStatQualifier` + let err = StatPair::from_str("unknown:5").unwrap_err(); + assert!(matches!(err, EpochError::UnknownStatAcronim(_))); +} +#[test] +fn position_invalid_format_errors_are_detected() { + // 1️⃣ No comma + let err = Position::from_str("123 456").unwrap_err(); + assert!(matches!(err, EpochError::InvalidPositionFormat(_))); + + // 2️⃣ Too many commas + let err = Position::from_str("1,2,3").unwrap_err(); + assert!(matches!(err, EpochError::InvalidPositionFormat(_))); + + // 3️⃣ Leading/trailing comma + let err = Position::from_str(",5").unwrap_err(); + assert!(matches!(err, EpochError::ParsePositionError(_))); + + let err = Position::from_str("5,").unwrap_err(); + assert!(matches!(err, EpochError::ParsePositionError(_))); + + // 4️⃣ Non‑integer components + let err = Position::from_str("x,5").unwrap_err(); + assert!(matches!(err, EpochError::ParsePositionError(_))); + + let err = Position::from_str("5,y").unwrap_err(); + assert!(matches!(err, EpochError::ParsePositionError(_))); +} #[test] fn test_liststats_aliases() { // Each tuple: (alias, expected enum variant)