Files
Agent-Workbench/docs/live-context-o-evidence/run/node/source-before/test/expense.test.mjs
T
2026-11-03 22:28:14 +08:00

38 lines
2.5 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { amountToCents } from '../src/amount.mjs';
import { summarize } from '../src/summary.mjs';
import { formatReport } from '../src/report.mjs';
test('decimal strings become exact cents including zero and refunds',()=>{
for(const [input,expected] of [['0',0],[' 12.34 ',1234],['+2.5',250],['-1.05',-105],['-0.00',0],['0009.10',910]]) assert.equal(amountToCents(input),expected);
});
test('finite decimal numbers use the same cents contract',()=>{
for(const [input,expected] of [[0,0],[1.01,101],[2.5,250],[-4.32,-432]]) assert.equal(amountToCents(input),expected);
});
test('malformed overprecision nonfinite and unsafe amounts are rejected',()=>{
for(const input of ['',null,undefined,true,{},'1e2','1,000','.50','1.234',1.234,NaN,Infinity,'900719925474099.99']) assert.throws(()=>amountToCents(input),TypeError,String(input));
});
test('independent currencies are sorted and summed without floating point loss',()=>{
assert.deepEqual(summarize([{currency:'usd',amount:'0.10'},{currency:' CNY ',amount:3},{currency:'USD',amount:'0.20'}]),[
{currency:'CNY',cents:300,count:1},{currency:'USD',cents:30,count:2}]);
});
test('refunds cancel totals while counting every original record',()=>{
assert.deepEqual(summarize([{currency:'eur',amount:'1.20'},{currency:'EUR',amount:'-1.20'}]),[{currency:'EUR',cents:0,count:2}]);
});
test('summarizing retains caller rows and handles an empty list',()=>{
const rows=Object.freeze([Object.freeze({currency:'usd',amount:'2.00'})]);
assert.deepEqual(summarize(rows),[{currency:'USD',cents:200,count:1}]);assert.deepEqual(summarize([]),[]);
});
test('invalid rows currency and unsafe aggregate totals are rejected',()=>{
for(const rows of [null,{},[null],[{currency:'US',amount:'1'}],[{currency:'U1D',amount:'1'}],[{currency:'USD',amount:'1.234'}],
[{currency:'USD',amount:'90071992547409.91'},{currency:'USD',amount:'0.01'}]]) assert.throws(()=>summarize(rows),TypeError);
});
test('reports use two decimals and render negative subunit amounts',()=>{
assert.equal(formatReport([{currency:'CNY',cents:300,count:2},{currency:'USD',cents:-105,count:1}]),'CNY 3.00 (2)\nUSD -1.05 (1)');
assert.equal(formatReport([{currency:'EUR',cents:-5,count:1}]),'EUR -0.05 (1)');assert.equal(formatReport([]),'');
});
test('complete expense flow preserves exact decimal sums',()=>{
assert.equal(formatReport(summarize([{currency:'usd',amount:'0.29'},{currency:'USD',amount:'-0.30'},{currency:'CNY',amount:'10.50'}])),
'CNY 10.50 (1)\nUSD -0.01 (2)');
});