More insta tests
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-12-13 02:42:03 +01:00
parent cecfdddfea
commit 34bbe0c76a
20 changed files with 328 additions and 76 deletions

37
Cargo.lock generated
View File

@ -108,6 +108,7 @@ dependencies = [
"colored",
"derive_more",
"env_logger",
"insta",
"lib_efo",
"log",
"miette",
@ -212,6 +213,18 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "console"
version = "0.15.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
dependencies = [
"encode_unicode",
"libc",
"once_cell",
"windows-sys 0.59.0",
]
[[package]]
name = "convert_case"
version = "0.10.0"
@ -265,6 +278,12 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "encode_unicode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]]
name = "env_filter"
version = "0.1.4"
@ -322,6 +341,17 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "insta"
version = "1.44.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5c943d4415edd8153251b6f197de5eb1640e56d84e8d9159bea190421c73698"
dependencies = [
"console",
"once_cell",
"similar",
]
[[package]]
name = "is_ci"
version = "1.2.0"
@ -383,6 +413,7 @@ dependencies = [
"colored",
"derive_more",
"env_logger",
"insta",
"log",
"miette",
"once_cell",
@ -678,6 +709,12 @@ dependencies = [
"serde_core",
]
[[package]]
name = "similar"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
[[package]]
name = "strsim"
version = "0.11.1"

View File

@ -13,3 +13,4 @@ env_logger = "0.11.8"
log = "0.4.28"
derive_more = { version = "2.0.1", features = ["display", "add"] }
colored = "3.0.0"
insta = "1.44.3"

View File

@ -1,6 +1,5 @@
![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg)
# 📦 Epoch Forge (`epoch_forge`)
![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg)
> **A Rust-powered CLI for managing fantasy organisations across time.**
> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.*

View File

@ -14,3 +14,6 @@ env_logger = {workspace = true}
log = {workspace = true}
derive_more = {workspace = true}
colored = {workspace = true}
[dev-dependencies]
insta = {workspace = true}

View File

@ -22,13 +22,13 @@ pub enum SuccessMessages {
#[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")]
EpochNextSuccess(EpochId, EpochId),
#[display("Successfully deleted the entity {_0} ({_1} @ {_2})")]
#[display("Successfully deleted the entity {_0} ({_1} 󰻾[{_2}])")]
DeletedEntity(String, String, String),
#[display("Successfully created the entity {_0} ({_1} @ {_2})")]
#[display("Successfully created the entity {_0} ({_1} 󰻾[{_2}])")]
CreatedEntity(String, String, String),
#[display("Successfully edited the entity {_0} ({_1} @ {_2})")]
#[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),

View File

@ -17,3 +17,7 @@ uuid = { version = "1.18.1", features = ["serde", "v4"] }
colored = {workspace = true}
rand = "0.9.2"
once_cell = "1.21.3"
[dev-dependencies]
insta = {workspace = true}

View File

@ -147,6 +147,6 @@ pub enum EntityIdentifier {
Id(String),
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[cfg(test)]
mod test;

View File

@ -29,14 +29,14 @@ impl Displayable for Entity {
.metadata
.capital
.as_ref()
.map(|c| format!(" | 💰 {:>2}", c))
.map(|c| format!(" 󰻾[{:>2}] ", c).green())
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!(" | 👑 {:>2}", g))
.map(|g| format!(" 󰻾[{:>2}]", g).red())
.unwrap_or_default();
let prestige = if *self.metadata.prestige > 0 {
@ -169,7 +169,7 @@ impl Entity {
// ── Top line: <entity_type> <name>
out.push_str(&format!(
"[{} {} ({})]\n",
"[{} {} 󰻾[{}]]\n",
self.entity_type.to_symbol().blue().bold(),
self.name.cyan().bold(),
self.id.to_string().blue().bold()
@ -214,7 +214,7 @@ impl Entity {
let symbol = if last { "└─" } else { "├─" };
out.push_str(&indent(
1,
&format!("{} {}", symbol.cyan(), link.to_string().yellow()),
&format!("{} 󰻾[{}]\n", symbol, link.to_string().yellow()),
));
}
}

View File

@ -5,7 +5,7 @@ use crate::{
error::EpochError,
};
use std::str::FromStr;
use std::{ops::Range, str::FromStr};
/// Simple error type used by `FromStr`.
/// clap only needs the error to implement `Display`, so a `String` is fine.
@ -112,3 +112,21 @@ impl FromStr for EntityIdentifier {
}
}
}
impl From<(usize, usize)> for EffectBounds {
fn from(value: (usize, usize)) -> Self {
Self {
min: value.0,
max: value.1,
}
}
}
impl From<Range<usize>> for EffectBounds {
fn from(value: Range<usize>) -> Self {
Self {
min: value.start,
max: value.end,
}
}
}

View File

@ -0,0 +1,14 @@
---
source: lib_efo/src/entity/test.rs
expression: e.to_pretty_tree()
---
[ Hero 󰻾[0c000000-0000-0000-0000-000000000000]]
├─ metadata
│ ├─ capital: Some(TownId(50))
│ ├─ prestige: 3
│ └─ position: ( 2, 4)⚓
├─ links
│ └─ 󰻾[3]
├─ duration: ⧗10
├─ effect_nature: Recurring
└─ effect_bounds: (1 ⭾ 5)

View File

@ -0,0 +1,8 @@
---
source: lib_efo/src/entity/test.rs
expression: e.oneline_display()
---
├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10
│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3📈
│ └─  󰻾[50]  󰻾[11]
│

View File

@ -0,0 +1,12 @@
---
source: lib_efo/src/entity/test.rs
expression: "format!(\"{}\", table)"
---
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘


View File

@ -0,0 +1,12 @@
---
source: lib_efo/src/entity/test.rs
expression: "format!(\"{}\", table)"
---
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘


View File

@ -0,0 +1,10 @@
---
source: lib_efo/src/entity/test.rs
expression: e.to_pretty_tree()
---
[ 󰻾[00000000-0000-0000-0000-000000000000]]
├─ metadata
│ └─ position: ( 0, 0)⚓
├─ duration: ✔
├─ effect_nature: PermanentEffectToApply
└─ effect_bounds: (0 ⭾ 0)

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/entity/test.rs
expression: e.oneline_display()
---
├──┬─ 0000000  ──────> ( 0, 0)⚓ ✔
│ └─ Faction: Ø │ Effect: ☈ (0 ⭾ 0), Stats: 0 0💰 0 0󰡢
│

View File

@ -0,0 +1,5 @@
---
source: lib_efo/src/entity/test.rs
expression: output
---

View File

@ -3,8 +3,18 @@
use std::str::FromStr;
use crate::entity::{EffectBounds, EntityDuration, EntityIdentifier};
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier};
use crate::error::EpochError;
use crate::stats::{self, EntityType, MetaStats, Position, TownId};
use std::io::Write;
use super::*;
use crate::Displayable;
use insta::assert_snapshot;
use uuid::Uuid;
/// The same structs & enums that the original crate exports – adjust the names
/// if your crate uses different identifiers.
// ---------- EntityDuration ----------
#[test]
@ -226,3 +236,98 @@ fn entity_identifier_errors_on_invalid_id() {
// _ => panic!("Expected Name variant"),
// }
// }
//
/// Disable coloured output so that snapshots are stable (no ANSI codes).
fn init_snapshot_env() {
colored::control::set_override(false);
}
/// Build a fully‑featured entity (capital, governor, prestige > 0).
fn full_entity() -> Entity {
Entity {
id: Uuid::from_u128_le(12),
name: "Hero".into(),
entity_type: EntityType::Character, // ← change to a real variant
metadata: MetaStats {
capital: Some(stats::TownId(50)),
governor: Some(stats::CharacterId(11)),
prestige: stats::GenericStat(3),
position: Position::from((2, 4)), // ← real variant
faction: Some(crate::stats::FactionId(2)),
links: vec![TownId(3)],
},
duration: EntityDuration::Duration(10),
effect_nature: EffectApplication::Recurring, // ← real variant
effect_bounds: EffectBounds::from((1, 5)), // ← real constructor
stats: stats::OverallStats::default(), // ← real constructor
temp_stats: Some(stats::OverallStats::default()),
}
}
#[test]
fn snapshot_full_oneline_display() {
init_snapshot_env();
let e = full_entity();
assert_snapshot!(e.oneline_display());
assert_snapshot!(e.to_pretty_tree());
}
#[test]
fn snapshot_minimal_oneline_display() {
init_snapshot_env();
let e = Entity::default();
assert_snapshot!(e.oneline_display());
assert_snapshot!(e.to_pretty_tree());
}
#[test]
fn snapshot_print_full_output() {
init_snapshot_env();
let e = full_entity();
// Capture stdout into a buffer
let buffer = Vec::new();
{
// let stdout = std::io::stdout();
// let mut handle = stdout.lock();
// // Temporarily swap the real stdout for our buffer.
// let original = std::mem::replace(&mut handle, &mut buffer);
// Run the method we want to snapshot.
e.print_full();
// Restore the original stdout.
// std::mem::replace(&mut handle, original);
}
// Convert buffer → UTF‑8 string and snapshot it.
let output = String::from_utf8_lossy(&buffer);
assert_snapshot!(output);
}
#[test]
fn snapshot_full_stats_no_temp() {
init_snapshot_env();
let e = full_entity();
let table = e.full_stats_to_table().expect("table generation failed");
assert_snapshot!(format!("{}", table));
}
#[test]
fn snapshot_full_stats_with_temp() {
init_snapshot_env();
let mut e = full_entity();
// Give the entity a temporary stat that is *different* from the
// permanent one so we can see two distinct rows in the table.
//
// If `Stats` offers a builder or `new` you can use it here.
// Otherwise just clone the default – the snapshot will contain
// two identical rows and that is fine for a regression test.
e.temp_stats = Some(OverallStats::default());
let table = e.full_stats_to_table().expect("table generation failed");
assert_snapshot!(format!("{}", table));
}

View File

@ -1,13 +1,13 @@
//! All traits implementatition for the main structs are deffered here
use crate::stats::GameStat;
use colored::Colorize;
use std::str::FromStr;
use crate::entity::{EffectApplication, EffectBounds, EntityDuration};
use crate::error::EpochError;
use crate::stats::{
self, EntityType, FactionId, GameStat, GenericStat, ListStats, OverallStats, Position,
StatPair, Symbols,
EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols,
};
/// Creates a thin, deref-able wrapper around an inner type.
@ -301,68 +301,6 @@ impl OverallStats {
}
}
impl FromStr for StatPair {
type Err = EpochError;
/// Parse a string into a `StatPair`.
///
/// The input can be either in the form `"stat:value"` or `"stat value"`.
/// If the format is invalid, an `EpochError::IllFormedStatQualifier`
/// is returned.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (stat_str, val_str) = if let Some(idx) = s.find(':') {
(&s[..idx], &s[idx + 1..])
} else {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.len() != 2 {
return Err(EpochError::IllFormedStatQualifier(s.to_owned()));
}
(parts[0], parts[1])
};
let stat: ListStats = stat_str.parse()?;
let value: isize = val_str
.parse()
.map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
Ok(StatPair {
stat,
value: stats::GenericStat(value),
})
}
}
/// Parse a string into a `Position`.
///
/// The input must be two signed integers separated by a comma, optionally
/// surrounded by whitespace. Leading and trailing whitespace around each
/// component is ignored.
///
/// # Errors
///
/// * `ParsePositionError::InvalidFormat` - the string does not contain
/// exactly one comma or there are not exactly two components.
/// * `ParsePositionError::ParseIntError` - one of the components cannot be
/// parsed as an `isize`.
impl std::str::FromStr for Position {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Err(EpochError::InvalidPositionFormat(s.to_string()));
}
let x: isize = parts[0]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
let y: isize = parts[1]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
Ok(Position(x, y))
}
}
impl Symbols for EntityType {
fn to_shortest(&self) -> String {
match self {
@ -510,5 +448,8 @@ impl Symbols for Option<FactionId> {
}
}
}
mod from_impl;
#[cfg(test)]
pub(crate) mod test;

View File

@ -0,0 +1,75 @@
//! All from implementations
use crate::{
error::EpochError,
stats::{self, ListStats, Position, StatPair},
};
use std::str::FromStr;
impl FromStr for StatPair {
type Err = EpochError;
/// Parse a string into a `StatPair`.
///
/// The input can be either in the form `"stat:value"` or `"stat value"`.
/// If the format is invalid, an `EpochError::IllFormedStatQualifier`
/// is returned.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (stat_str, val_str) = if let Some(idx) = s.find(':') {
(&s[..idx], &s[idx + 1..])
} else {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.len() != 2 {
return Err(EpochError::IllFormedStatQualifier(s.to_owned()));
}
(parts[0], parts[1])
};
let stat: ListStats = stat_str.parse()?;
let value: isize = val_str
.parse()
.map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
Ok(StatPair {
stat,
value: stats::GenericStat(value),
})
}
}
/// Parse a string into a `Position`.
///
/// The input must be two signed integers separated by a comma, optionally
/// surrounded by whitespace. Leading and trailing whitespace around each
/// component is ignored.
///
/// # Errors
///
/// * `ParsePositionError::InvalidFormat` - the string does not contain
/// exactly one comma or there are not exactly two components.
/// * `ParsePositionError::ParseIntError` - one of the components cannot be
/// parsed as an `isize`.
impl std::str::FromStr for Position {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Err(EpochError::InvalidPositionFormat(s.to_string()));
}
let x: isize = parts[0]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
let y: isize = parts[1]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
Ok(Position(x, y))
}
}
impl From<(isize, isize)> for Position {
fn from(value: (isize, isize)) -> Self {
Self(value.0, value.1)
}
}

View File

@ -2,6 +2,7 @@
use super::*;
use crate::stats::GameStat;
use crate::stats::GenericStat;
use crate::stats::StatPair;
use std::str::FromStr;
struct Person {