lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

money.rs (9814B)


      1 use radroots_domain::{
      2     CURRENCY_REGISTRY_ID, CURRENCY_REGISTRY_SHA256, Currency, CurrencyError, MinorAmount, Money,
      3     MoneyError, SUPPORTED_CURRENCY_COUNT,
      4 };
      5 use std::{collections::BTreeSet, error::Error};
      6 
      7 fn money(code: &str, value: &str, exponent: u8) -> Money {
      8     Money::from_parts(code, value, exponent).unwrap()
      9 }
     10 
     11 #[test]
     12 fn complete_pinned_registry_preserves_each_code_and_exponent_without_defaults() {
     13     let expected = include_str!("../data/currency_registry_v1.csv")
     14         .lines()
     15         .filter(|line| !line.starts_with('#'))
     16         .map(|line| {
     17             let (code, exponent) = line.split_once(',').unwrap();
     18             (code, exponent.parse::<u8>().unwrap())
     19         })
     20         .collect::<Vec<_>>();
     21     assert_eq!(expected.len(), 165);
     22     assert_eq!(SUPPORTED_CURRENCY_COUNT, expected.len());
     23     assert_eq!(CURRENCY_REGISTRY_ID, "radroots.currency_registry.v1");
     24     assert_eq!(CURRENCY_REGISTRY_SHA256.len(), 64);
     25     let actual = Currency::supported()
     26         .map(|currency| (currency.code(), currency.exponent()))
     27         .collect::<Vec<_>>();
     28     assert_eq!(actual, expected);
     29     assert_eq!(
     30         actual
     31             .iter()
     32             .map(|row| row.0)
     33             .collect::<BTreeSet<_>>()
     34             .len(),
     35         165
     36     );
     37     for (code, exponent) in actual {
     38         let currency: Currency = code.parse().unwrap();
     39         assert_eq!(currency.code(), code);
     40         assert_eq!(currency.exponent(), exponent);
     41         let value = money(code, "1", exponent);
     42         assert_eq!(value.currency(), currency);
     43         for other in 0..=4 {
     44             if other != exponent {
     45                 assert_eq!(
     46                     Money::from_parts(code, "1", other),
     47                     Err(MoneyError::ExponentMismatch)
     48                 );
     49             }
     50         }
     51     }
     52 }
     53 
     54 #[test]
     55 fn independent_iso_minor_units_are_distinct_from_display_rounding() {
     56     for (code, exponent) in [
     57         ("CAD", 2),
     58         ("JPY", 0),
     59         ("KWD", 3),
     60         ("CLF", 4),
     61         ("UYW", 4),
     62         ("AFN", 2),
     63         ("ALL", 2),
     64         ("COP", 2),
     65         ("HUF", 2),
     66         ("XAD", 2),
     67     ] {
     68         assert_eq!(Currency::from_code(code).unwrap().exponent(), exponent);
     69     }
     70 }
     71 
     72 #[test]
     73 fn currency_admission_is_ascii_canonical_bounded_and_supported_only() {
     74     for input in [
     75         "",
     76         "US",
     77         "USDD",
     78         "usd",
     79         "Usd",
     80         " USD",
     81         "USD ",
     82         "12A",
     83         "éA",
     84         "USD",
     85         "A\0B",
     86     ] {
     87         assert_eq!(
     88             Currency::from_code(input),
     89             Err(CurrencyError::InvalidFormat)
     90         );
     91     }
     92     assert_eq!(
     93         Currency::from_code(&"A".repeat(100_000)),
     94         Err(CurrencyError::InvalidFormat)
     95     );
     96     for input in [
     97         "ZZZ", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XDR", "XPD", "XPT", "XSU", "XTS", "XUA",
     98         "XXX", "BGN", "ANG",
     99     ] {
    100         assert_eq!(
    101             Currency::from_code(input),
    102             Err(CurrencyError::UnsupportedCode)
    103         );
    104     }
    105 }
    106 
    107 #[test]
    108 fn minor_amount_strings_and_numeric_construction_are_exact_at_both_bounds() {
    109     for (text, expected) in [
    110         ("0", 0),
    111         ("1", 1),
    112         ("900719925474099", 900_719_925_474_099),
    113         ("999999999999999", 999_999_999_999_999),
    114     ] {
    115         let amount: MinorAmount = text.parse().unwrap();
    116         assert_eq!(amount.get(), expected);
    117         assert_eq!(amount.to_string(), text);
    118         assert_eq!(MinorAmount::try_from(expected).unwrap(), amount);
    119     }
    120     assert_eq!(MinorAmount::ZERO.get(), 0);
    121     assert_eq!(MinorAmount::MAX.get(), MinorAmount::MAX_VALUE);
    122     assert_eq!(
    123         MinorAmount::new(1_000_000_000_000_000),
    124         Err(MoneyError::MinorOutOfRange)
    125     );
    126     assert_eq!(MinorAmount::new(u64::MAX), Err(MoneyError::MinorOutOfRange));
    127     for input in [
    128         "", "-0", "-1", "+1", "1.0", "1e2", " 1", "1 ", "1\n", "1,000", "1_000", "1", "١", "NaN",
    129     ] {
    130         assert_eq!(
    131             input.parse::<MinorAmount>(),
    132             Err(MoneyError::InvalidMinorFormat)
    133         );
    134     }
    135     for input in ["00", "01", "000000000000000"] {
    136         assert_eq!(
    137             input.parse::<MinorAmount>(),
    138             Err(MoneyError::NonCanonicalMinor)
    139         );
    140     }
    141     for input in ["1000000000000000", "9999999999999999", &"9".repeat(100_000)] {
    142         assert_eq!(
    143             input.parse::<MinorAmount>(),
    144             Err(MoneyError::MinorOutOfRange)
    145         );
    146     }
    147 }
    148 
    149 #[test]
    150 fn money_checks_explicit_exponents_and_never_changes_currency_or_price_mode() {
    151     for (code, exponent) in [("JPY", 0), ("CAD", 2), ("KWD", 3), ("CLF", 4)] {
    152         let value = money(code, "325", exponent);
    153         assert_eq!(value.currency().code(), code);
    154         assert_eq!(value.exponent(), exponent);
    155         assert_eq!(value.minor().get(), 325);
    156         assert_eq!(Money::new(value.currency(), value.minor()), value);
    157         assert_eq!(
    158             Money::from_parts(code, "325", 5),
    159             Err(MoneyError::InvalidExponent)
    160         );
    161         assert_eq!(
    162             Money::from_parts(code, "325", u8::MAX),
    163             Err(MoneyError::InvalidExponent)
    164         );
    165     }
    166     assert_eq!(money("CAD", "0", 2).minor(), MinorAmount::ZERO);
    167     assert_eq!(
    168         Money::from_parts("XXX", "0", 0),
    169         Err(MoneyError::Currency(CurrencyError::UnsupportedCode))
    170     );
    171     assert_eq!(
    172         Money::from_parts("cad", "0", 2),
    173         Err(MoneyError::Currency(CurrencyError::InvalidFormat))
    174     );
    175     assert_eq!(
    176         Money::from_parts("CAD", "0.1", 2),
    177         Err(MoneyError::InvalidMinorFormat)
    178     );
    179 }
    180 
    181 #[test]
    182 fn checked_money_arithmetic_preserves_bounds_and_refuses_cross_currency_operations() {
    183     let zero = money("CAD", "0", 2);
    184     let one = money("CAD", "1", 2);
    185     let maximum = money("CAD", "999999999999999", 2);
    186     assert_eq!(maximum.checked_add(zero).unwrap(), maximum);
    187     assert_eq!(maximum.checked_sub(zero).unwrap(), maximum);
    188     assert_eq!(maximum.checked_sub(maximum).unwrap(), zero);
    189     assert_eq!(
    190         money("CAD", "998", 2).checked_add(one).unwrap(),
    191         money("CAD", "999", 2)
    192     );
    193     assert_eq!(maximum.checked_add(one), Err(MoneyError::MinorOutOfRange));
    194     assert_eq!(
    195         maximum.checked_add(maximum),
    196         Err(MoneyError::MinorOutOfRange)
    197     );
    198     assert_eq!(zero.checked_sub(one), Err(MoneyError::NegativeResult));
    199     for other in [
    200         money("USD", "1", 2),
    201         money("JPY", "1", 0),
    202         money("CLF", "1", 4),
    203     ] {
    204         assert_eq!(one.checked_add(other), Err(MoneyError::CurrencyMismatch));
    205         assert_eq!(one.checked_sub(other), Err(MoneyError::CurrencyMismatch));
    206     }
    207 }
    208 
    209 #[test]
    210 fn diagnostics_are_fixed_and_money_values_are_redacted() {
    211     let value = money("CAD", "928174615", 2);
    212     for debug in [
    213         format!("{value:?}"),
    214         format!("{:?}", value.minor()),
    215         format!("{:?}", value.currency()),
    216     ] {
    217         assert!(!debug.contains("928174615"));
    218         assert!(!debug.contains("CAD"));
    219     }
    220     for error in [
    221         MoneyError::InvalidMinorFormat,
    222         MoneyError::NonCanonicalMinor,
    223         MoneyError::MinorOutOfRange,
    224         MoneyError::InvalidExponent,
    225         MoneyError::ExponentMismatch,
    226         MoneyError::CurrencyMismatch,
    227         MoneyError::NegativeResult,
    228         CurrencyError::InvalidFormat.into(),
    229         CurrencyError::UnsupportedCode.into(),
    230     ] {
    231         assert!(!error.to_string().is_empty());
    232         assert!(!error.to_string().contains("928174615"));
    233         assert!(!error.to_string().contains("CAD"));
    234     }
    235     assert!(
    236         MoneyError::Currency(CurrencyError::UnsupportedCode)
    237             .source()
    238             .is_some()
    239     );
    240     assert!(MoneyError::ExponentMismatch.source().is_none());
    241 }
    242 
    243 #[cfg(feature = "serde")]
    244 #[test]
    245 fn money_serde_is_closed_duplicate_safe_and_validates_every_explicit_field() {
    246     let value = money("CAD", "999999999999999", 2);
    247     let encoded = serde_json::to_string(&value).unwrap();
    248     assert_eq!(
    249         encoded,
    250         r#"{"currency":"CAD","minor":"999999999999999","exponent":2}"#
    251     );
    252     assert_eq!(serde_json::from_str::<Money>(&encoded).unwrap(), value);
    253     assert_eq!(
    254         serde_json::to_string(&value.currency()).unwrap(),
    255         r#""CAD""#
    256     );
    257     assert_eq!(
    258         serde_json::to_string(&value.minor()).unwrap(),
    259         r#""999999999999999""#
    260     );
    261     for input in [
    262         r#"{"currency":"CAD","minor":325,"exponent":2}"#,
    263         r#"{"currency":"CAD","minor":"0325","exponent":2}"#,
    264         r#"{"currency":"CAD","minor":"1000000000000000","exponent":2}"#,
    265         r#"{"currency":"CAD","minor":"325","exponent":0}"#,
    266         r#"{"currency":"CAD","minor":"325","exponent":5}"#,
    267         r#"{"currency":"CAD","minor":"325","exponent":256}"#,
    268         r#"{"currency":"CAD","minor":"325","exponent":-1}"#,
    269         r#"{"currency":"CAD","minor":"325","exponent":"2"}"#,
    270         r#"{"currency":"CAD","minor":"325","exponent":2.0}"#,
    271         r#"{"currency":"XXX","minor":"0","exponent":0}"#,
    272         r#"{"currency":"CAD","minor":"0","exponent":2,"extra":null}"#,
    273         r#"{"currency":"CAD","currency":"USD","minor":"0","exponent":2}"#,
    274         r#"{"currency":"CAD","minor":"0","minor":"1","exponent":2}"#,
    275         r#"{"currency":"CAD","minor":"0","exponent":2,"exponent":2}"#,
    276         r#"{"currency":"CAD","minor":"0"}"#,
    277         r#"{"currency":"CAD","exponent":2}"#,
    278         r#"{"minor":"0","exponent":2}"#,
    279         r#"[]"#,
    280         r#"["CAD","325",2]"#,
    281         r#"null"#,
    282     ] {
    283         assert!(serde_json::from_str::<Money>(input).is_err(), "{input}");
    284     }
    285     for input in ["325", "325.0", "null", r#""1.5""#, r#""-1""#] {
    286         assert!(serde_json::from_str::<MinorAmount>(input).is_err());
    287     }
    288     for input in ["325", "null", r#""cad""#, r#""ZZZ""#] {
    289         assert!(serde_json::from_str::<Currency>(input).is_err());
    290     }
    291 }