|
| 1 | +use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue}; |
| 2 | +use fluent_syntax::ast::Pattern; |
| 3 | + |
| 4 | +#[test] |
| 5 | +fn test_builtin_number() { |
| 6 | + // 1. Create bundle |
| 7 | + let ftl_string = String::from( |
| 8 | + r#" |
| 9 | +count = { NUMBER($num, type: "cardinal") -> |
| 10 | + *[other] A |
| 11 | + [one] B |
| 12 | +} |
| 13 | +order = { NUMBER($num, type: "ordinal") -> |
| 14 | + *[other] {$num}th |
| 15 | + [one] {$num}st |
| 16 | + [two] {$num}nd |
| 17 | + [few] {$num}rd |
| 18 | +} |
| 19 | + "#, |
| 20 | + ); |
| 21 | + |
| 22 | + let mut bundle = FluentBundle::default(); |
| 23 | + bundle |
| 24 | + .add_resource(FluentResource::try_new(ftl_string).expect("Could not parse an FTL string.")) |
| 25 | + .expect("Failed to add FTL resources to the bundle."); |
| 26 | + bundle |
| 27 | + .add_builtins() |
| 28 | + .expect("Failed to add builtin functions to the bundle."); |
| 29 | + |
| 30 | + let get_val = |pattern: &Pattern<&'_ str>, num: isize| { |
| 31 | + let mut args = FluentArgs::new(); |
| 32 | + args.set("num", FluentValue::from(num)); |
| 33 | + let mut errors = vec![]; |
| 34 | + let val = bundle.format_pattern(pattern, Some(&args), &mut errors); |
| 35 | + if errors.is_empty() { |
| 36 | + Ok(val.into_owned()) |
| 37 | + } else { |
| 38 | + Err(errors) |
| 39 | + } |
| 40 | + }; |
| 41 | + |
| 42 | + let count = bundle |
| 43 | + .get_message("count") |
| 44 | + .expect("Message doesn't exist") |
| 45 | + .value() |
| 46 | + .expect("Message has no value"); |
| 47 | + |
| 48 | + assert_eq!(get_val(count, 0).unwrap(), "A"); |
| 49 | + assert_eq!(get_val(count, 1).unwrap(), "B"); |
| 50 | + assert_eq!(get_val(count, 2).unwrap(), "A"); |
| 51 | + assert_eq!(get_val(count, 12).unwrap(), "A"); |
| 52 | + assert_eq!(get_val(count, 15).unwrap(), "A"); |
| 53 | + assert_eq!(get_val(count, 123).unwrap(), "A"); |
| 54 | + |
| 55 | + let order = bundle |
| 56 | + .get_message("order") |
| 57 | + .expect("Message doesn't exist") |
| 58 | + .value() |
| 59 | + .expect("Message has no value"); |
| 60 | + |
| 61 | + assert_eq!(get_val(order, 0).unwrap(), "\u{2068}0\u{2069}th"); |
| 62 | + assert_eq!(get_val(order, 1).unwrap(), "\u{2068}1\u{2069}st"); |
| 63 | + assert_eq!(get_val(order, 2).unwrap(), "\u{2068}2\u{2069}nd"); |
| 64 | + assert_eq!(get_val(order, 12).unwrap(), "\u{2068}12\u{2069}th"); |
| 65 | + assert_eq!(get_val(order, 15).unwrap(), "\u{2068}15\u{2069}th"); |
| 66 | + assert_eq!(get_val(order, 123).unwrap(), "\u{2068}123\u{2069}rd"); |
| 67 | +} |
0 commit comments