]> git.proxmox.com Git - rustc.git/blob - vendor/handlebars-3.5.5/src/helpers/helper_boolean.rs
New upstream version 1.70.0+dfsg2
[rustc.git] / vendor / handlebars-3.5.5 / src / helpers / helper_boolean.rs
1 //! Helpers for boolean operations
2
3 use crate::json::value::JsonTruthy;
4
5 handlebars_helper!(eq: |x: Json, y: Json| x == y);
6 handlebars_helper!(ne: |x: Json, y: Json| x != y);
7 handlebars_helper!(gt: |x: i64, y: i64| x > y);
8 handlebars_helper!(gte: |x: i64, y: i64| x >= y);
9 handlebars_helper!(lt: |x: i64, y: i64| x < y);
10 handlebars_helper!(lte: |x: i64, y: i64| x <= y);
11 handlebars_helper!(and: |x: Json, y: Json| x.is_truthy(false) && y.is_truthy(false));
12 handlebars_helper!(or: |x: Json, y: Json| x.is_truthy(false) || y.is_truthy(false));
13 handlebars_helper!(not: |x: Json| !x.is_truthy(false));
14
15 #[cfg(test)]
16 mod test_conditions {
17 fn test_condition(condition: &str, expected: bool) {
18 let handlebars = crate::Handlebars::new();
19
20 let result = handlebars
21 .render_template(
22 &format!(
23 "{{{{#if {condition}}}}}lorem{{{{else}}}}ipsum{{{{/if}}}}",
24 condition = condition
25 ),
26 &json!({}),
27 )
28 .unwrap();
29 assert_eq!(&result, if expected { "lorem" } else { "ipsum" });
30 }
31
32 #[test]
33 fn foo() {
34 test_condition("(gt 5 3)", true);
35 test_condition("(gt 3 5)", false);
36 test_condition("(or (gt 3 5) (gt 5 3))", true);
37 test_condition("(not [])", true);
38 test_condition("(and null 4)", false);
39 }
40
41 #[test]
42 fn test_eq() {
43 test_condition("(eq 5 5)", true);
44 test_condition("(eq 5 6)", false);
45 test_condition(r#"(eq "foo" "foo")"#, true);
46 test_condition(r#"(eq "foo" "Foo")"#, false);
47 test_condition(r#"(eq [5] [5])"#, true);
48 test_condition(r#"(eq [5] [4])"#, false);
49 test_condition(r#"(eq 5 "5")"#, false);
50 test_condition(r#"(eq 5 [5])"#, false);
51 }
52
53 #[test]
54 fn test_ne() {
55 test_condition("(ne 5 6)", true);
56 test_condition("(ne 5 5)", false);
57 test_condition(r#"(ne "foo" "foo")"#, false);
58 test_condition(r#"(ne "foo" "Foo")"#, true);
59 }
60
61 #[test]
62 fn nested_conditions() {
63 let handlebars = crate::Handlebars::new();
64
65 let result = handlebars
66 .render_template("{{#if (gt 5 3)}}lorem{{else}}ipsum{{/if}}", &json!({}))
67 .unwrap();
68 assert_eq!(&result, "lorem");
69
70 let result = handlebars
71 .render_template(
72 "{{#if (not (gt 5 3))}}lorem{{else}}ipsum{{/if}}",
73 &json!({}),
74 )
75 .unwrap();
76 assert_eq!(&result, "ipsum");
77 }
78 }