currency.rs (2589B)
1 use core::str::FromStr; 2 3 use radroots_core::{Currency, currency::ParseError}; 4 5 #[test] 6 fn from_str_upper_accepts_valid() { 7 let usd = Currency::from_str_upper("USD").unwrap(); 8 assert_eq!(usd.as_str(), "USD"); 9 } 10 11 #[test] 12 fn from_str_upper_rejects_invalid() { 13 assert_eq!( 14 Currency::from_str_upper("Usd"), 15 Err(ParseError::InvalidFormat) 16 ); 17 assert_eq!( 18 Currency::from_str_upper("US"), 19 Err(ParseError::InvalidFormat) 20 ); 21 } 22 23 #[test] 24 fn from_str_trims_and_uppercases() { 25 let usd = Currency::from_str(" usd ").unwrap(); 26 assert_eq!(usd.as_str(), "USD"); 27 } 28 29 #[test] 30 fn from_str_rejects_non_alpha() { 31 assert_eq!(Currency::from_str("US1"), Err(ParseError::InvalidFormat)); 32 assert_eq!(Currency::from_str("US"), Err(ParseError::InvalidFormat)); 33 } 34 35 #[test] 36 fn from_const_validates_bytes() { 37 assert!(Currency::from_const(*b"USD").is_ok()); 38 assert_eq!( 39 Currency::from_const(*b"1SD"), 40 Err(ParseError::InvalidFormat) 41 ); 42 assert_eq!( 43 Currency::from_const(*b"Usd"), 44 Err(ParseError::InvalidFormat) 45 ); 46 assert_eq!( 47 Currency::from_const(*b"USd"), 48 Err(ParseError::InvalidFormat) 49 ); 50 assert_eq!( 51 Currency::from_const(*b"usd"), 52 Err(ParseError::InvalidFormat) 53 ); 54 } 55 56 #[test] 57 fn minor_unit_exponent_matches_known_currencies() { 58 let jpy = Currency::from_str_upper("JPY").unwrap(); 59 let kwd = Currency::from_str_upper("KWD").unwrap(); 60 let usd = Currency::from_str_upper("USD").unwrap(); 61 62 assert_eq!(jpy.minor_unit_exponent(), 0); 63 assert_eq!(kwd.minor_unit_exponent(), 3); 64 assert_eq!(usd.minor_unit_exponent(), 2); 65 } 66 67 #[test] 68 fn display_debug_tryfrom_and_error_display_paths_are_exercised() { 69 let usd = Currency::from_str("usd").unwrap(); 70 assert_eq!(usd.to_string(), "USD"); 71 assert_eq!(format!("{usd:?}"), "Currency(\"USD\")"); 72 let via_try_from = Currency::try_from("usd").unwrap(); 73 assert_eq!(via_try_from, usd); 74 assert_eq!( 75 ParseError::InvalidFormat.to_string(), 76 "currency must be a 3-letter code" 77 ); 78 } 79 80 #[cfg(feature = "serde")] 81 #[test] 82 fn serde_deserialize_paths_are_exercised() { 83 let parsed: Currency = serde_json::from_str("\"USD\"").unwrap(); 84 assert_eq!(parsed.as_str(), "USD"); 85 let err = serde_json::from_str::<Currency>("\"US1\"").unwrap_err(); 86 assert!(err.to_string().contains("currency must be a 3-letter code")); 87 let non_string_err = serde_json::from_str::<Currency>("123").unwrap_err(); 88 assert!(non_string_err.to_string().contains("invalid type")); 89 }