Lines
99.75 %
Functions
95.24 %
Branches
100 %
use super::wire::{
IndexTable, TagLink, TagLinks, apply_parsed_entities, millis_to_datetime, serialize_state,
};
use super::*;
use finance::transaction::TransactionBuilder;
use scripting::{EntityData, EntityType, Operation, ParsedEntity};
use sqlx::types::chrono::Local;
#[test]
fn test_transaction_state_new() {
let tx = TransactionBuilder::new()
.id(Uuid::new_v4())
.post_date(Local::now().into())
.enter_date(Local::now().into())
.build()
.unwrap();
let state = TransactionState::new(tx);
assert!(state.splits.is_empty());
assert!(state.transaction_tags.is_empty());
assert!(state.split_tags.is_empty());
assert!(state.prices.is_empty());
}
fn test_serialize_empty_state() {
let (bytes, index_table, _) = serialize_state(&state);
assert!(!bytes.is_empty());
assert!(
index_table.contains_key(&0),
"transaction missing at index 0"
);
fn test_apply_tag_to_transaction() {
let tx_id = Uuid::new_v4();
.id(tx_id)
let mut state = TransactionState::new(tx);
let mut index_table = IndexTable::new();
index_table.insert(0, (EntityType::Transaction, tx_id));
let tag_entity = ParsedEntity {
entity_type: EntityType::Tag,
operation: Operation::Create,
flags: 0,
id: *Uuid::new_v4().as_bytes(),
parent_idx: 0, // Points to transaction at index 0
data: EntityData::Tag {
name: "category".to_string(),
value: "groceries".to_string(),
},
apply_parsed_entities(
&mut state,
vec![tag_entity],
&mut index_table,
&TagLinks::new(),
)
assert_eq!(state.transaction_tags.len(), 1);
assert_eq!(state.transaction_tags[0].tag_name, "category");
assert_eq!(state.transaction_tags[0].tag_value, "groceries");
fn test_apply_tag_to_split() {
let split_id = Uuid::new_v4();
let split = Split {
id: split_id,
tx_id,
account_id: Uuid::new_v4(),
commodity_id: Uuid::new_v4(),
value_num: 100,
value_denom: 1,
reconcile_state: None,
reconcile_date: None,
lot_id: None,
let mut state = TransactionState::new(tx).with(vec![FinanceEntity::Split(split)]);
index_table.insert(1, (EntityType::Split, split_id));
parent_idx: 1, // Points to split at index 1
assert_eq!(state.split_tags.len(), 1);
assert_eq!(state.split_tags[0].0, split_id);
assert_eq!(state.split_tags[0].1.tag_name, "category");
assert_eq!(state.split_tags[0].1.tag_value, "groceries");
fn test_serialize_state_with_split_tags() {
let tag = Tag {
id: Uuid::new_v4(),
tag_name: "category".to_string(),
tag_value: "food".to_string(),
description: None,
let state = TransactionState::new(tx)
.with(vec![FinanceEntity::Split(split)])
.with_split_tags(vec![(split_id, tag)]);
assert_eq!(index_table.len(), 2); // transaction + split
assert_eq!(index_table.get(&1).unwrap(), &(EntityType::Split, split_id));
fn test_millis_to_datetime() {
let dt = millis_to_datetime(1704067200000);
assert_eq!(dt.timestamp(), 1704067200);
fn test_tag_sync_copies_split_tags_to_transaction() {
const TAG_SYNC_WASM: &[u8] = include_bytes!("../../../web/static/wasm/tag_sync.wasm");
let split1_id = Uuid::new_v4();
let split2_id = Uuid::new_v4();
let commodity_id = Uuid::new_v4();
let split1 = Split {
id: split1_id,
commodity_id,
value_num: -5000,
value_denom: 100,
let split2 = Split {
id: split2_id,
value_num: 5000,
let category_tag = Tag {
.with(vec![
FinanceEntity::Split(split1),
FinanceEntity::Split(split2),
])
.with_note(Some("groceries".to_string()))
.with_split_tags(vec![(split1_id, category_tag)]);
let script_id = Uuid::new_v4();
let executor = ScriptExecutor::try_new().expect("baseline engine");
let report = state
.run_scripts(&executor, &[(script_id, TAG_SYNC_WASM.to_vec())])
.expect("run_scripts failed");
report.failures.is_empty(),
"tag_sync.wasm must run cleanly: {:?}",
report.failures
let new_tx_tags: Vec<_> = report
.state
.transaction_tags
.iter()
.filter(|t| t.tag_name != "note")
.collect();
assert_eq!(
new_tx_tags.len(),
1,
"tag_sync should copy category tag from split to transaction"
assert_eq!(new_tx_tags[0].tag_name, "category");
assert_eq!(new_tx_tags[0].tag_value, "food");
/// Bad bytecode lands as a structured `ScriptFailure` in the report
/// rather than being silently swallowed. The state is preserved
/// (no side effects from a failed script).
fn run_scripts_captures_failed_script_into_structured_report() {
let invalid_bytecode: Vec<u8> = vec![0xde, 0xad, 0xbe, 0xef];
.run_scripts(&executor, &[(script_id, invalid_bytecode)])
.expect("run_scripts must surface bad-bytecode as a failure cell, not an outer Err");
report.failures.len(),
"single bad script should produce exactly one captured failure"
assert_eq!(report.failures[0].script_id, script_id);
!report.failures[0].code.is_empty(),
"captured failure must carry a non-empty code symbol"
report.state.transaction_tags.is_empty(),
"failed script must not have mutated state"
assert_eq!(report.state.transaction.id, tx_id);
/// A mixed batch — one failing script followed by a working one —
/// captures the failure but still applies the second script's
/// output. Validates the "successive scripts still see state
/// mutations from earlier successes" invariant of the report shape.
/// Setup mirrors `test_tag_sync_copies_split_tags_to_transaction`'s
/// two-split balanced shape because tag_sync.wasm only fires once
/// the transaction's splits sum to zero.
fn run_scripts_continues_past_failure_and_applies_subsequent_scripts() {
let bad_id = Uuid::new_v4();
let good_id = Uuid::new_v4();
.run_scripts(
&executor,
&[
(bad_id, vec![0xde, 0xad, 0xbe, 0xef]),
(good_id, TAG_SYNC_WASM.to_vec()),
],
.expect("run_scripts must capture per-script failures structurally");
assert_eq!(report.failures.len(), 1);
assert_eq!(report.failures[0].script_id, bad_id);
let category_tx_tags: Vec<_> = report
.filter(|t| t.tag_name == "category")
category_tx_tags.len(),
"tag_sync.wasm must still copy the split's category tag onto the transaction \
after an earlier script failed"
/// `classify_script_failure` routes engine-classified errors
/// through `err_code_and_message` so the code symbols match catch-each's
/// err cells. A commodity mismatch is the load-bearing case — it now
/// `throw`s `$nomi_error` in-guest and arrives as a `ScriptRaised`
/// carrying the reader-folded symbol `COMMODITY-MISMATCH` (ADR-0026),
/// the structural signal scripts react to, distinct from generic traps.
fn classify_script_failure_maps_engine_error_to_symbol_code() {
use scripting::runtime::EngineError;
let engine_err = EngineError::ScriptRaised {
code: "COMMODITY-MISMATCH".to_string(),
message: "USD vs EUR".to_string(),
detail: None,
let hook_err = HookError::Engine(engine_err);
let id = Uuid::new_v4();
let failure = classify_script_failure(id, &hook_err);
assert_eq!(failure.script_id, id);
assert_eq!(failure.code, "COMMODITY-MISMATCH");
assert_eq!(failure.message, "USD vs EUR");
/// Non-engine `HookError` variants (Parse / Lock / Script) fall
/// through to a `runtime` code with the engine's own message —
/// the catch-all path that keeps `ScriptFailure`'s shape
/// non-empty for any cause `executor.execute` can surface.
fn classify_script_failure_falls_back_to_runtime_for_non_engine_error() {
let hook_err = HookError::Script("synthetic test failure".to_string());
assert_eq!(failure.code, "runtime");
assert!(failure.message.contains("synthetic test failure"));
fn shared_tag_state() -> anyhow::Result<(TransactionState, Uuid, [Uuid; 2])> {
.build()?;
let splits = [Uuid::new_v4(), Uuid::new_v4()];
let trip = Tag {
tag_name: "trip".to_string(),
tag_value: "japan".to_string(),
let mut state = TransactionState::new(tx)
.with_split_tags(splits.iter().map(|id| (*id, trip.clone())).collect());
state.transaction_tags.push(trip.clone());
Ok((state, trip.id, splits))
fn delete_entity(wire_id: Uuid) -> ParsedEntity {
ParsedEntity {
operation: Operation::Delete,
id: *wire_id.as_bytes(),
parent_idx: -1,
name: String::new(),
value: String::new(),
fn wire_id_of(tag_links: &TagLinks, link: TagLink) -> anyhow::Result<Uuid> {
tag_links
.find_map(|(wire_id, candidate)| (*candidate == link).then_some(*wire_id))
.ok_or_else(|| anyhow::anyhow!("{link:?} not serialized"))
fn deleting_a_shared_tag_on_one_split_keeps_its_other_owners() -> anyhow::Result<()> {
let (mut state, trip, splits) = shared_tag_state()?;
let (_, mut index_table, tag_links) = serialize_state(&state);
let wire_id = wire_id_of(&tag_links, TagLink::Split(splits[0], trip))?;
vec![delete_entity(wire_id)],
&tag_links,
)?;
assert_eq!(state.split_tags[0].0, splits[1]);
assert!(state.deleted_transaction_tags.is_empty());
assert_eq!(state.deleted_split_tags, HashSet::from([(splits[0], trip)]));
Ok(())
fn deleting_a_shared_transaction_tag_keeps_its_split_owners() -> anyhow::Result<()> {
let (mut state, trip, _) = shared_tag_state()?;
let wire_id = wire_id_of(&tag_links, TagLink::Transaction(trip))?;
let twice = vec![delete_entity(wire_id), delete_entity(wire_id)];
apply_parsed_entities(&mut state, twice, &mut index_table, &tag_links)?;
assert_eq!(state.split_tags.len(), 2);
assert_eq!(state.deleted_transaction_tags, HashSet::from([trip]));
assert!(state.deleted_split_tags.is_empty());