Skip to main content

minijinja/
tests.rs

1//! Test functions and abstractions.
2//!
3//! Test functions in MiniJinja are like [`filters`](crate::filters) but a
4//! different syntax is used to invoke them and they have to return boolean
5//! values.  For instance the expression `{% if foo is odd %}` invokes the
6//! [`is_odd`] test to check if the value is indeed an odd number.
7//!
8//! MiniJinja comes with some built-in test functions that are listed below. To
9//! create a custom test write a function that takes at least a value argument
10//! that returns a boolean result, then register it with
11//! [`add_test`](crate::Environment::add_test).
12//!
13//! # Using Tests
14//!
15//! Tests are useful to "test" a value in a specific way.  For instance if
16//! you want to assign different classes to alternating rows one way is
17//! using the `odd` test:
18//!
19//! ```jinja
20//! {% if seq is defined %}
21//!   <ul>
22//!   {% for item in seq %}
23//!     <li class="{{ 'even' if loop.index is even else 'odd' }}">{{ item }}</li>
24//!   {% endfor %}
25//!   </ul>
26//! {% endif %}
27//! ```
28//!
29//! # Custom Tests
30//!
31//! A custom test function is just a simple function which accepts its
32//! inputs as parameters and then returns a bool.  For instance the following
33//! shows a test function which takes an input value and checks if it's
34//! lowercase:
35//!
36//! ```
37//! # use minijinja::Environment;
38//! # let mut env = Environment::new();
39//! fn is_lowercase(value: String) -> bool {
40//!     value.chars().all(|x| x.is_lowercase())
41//! }
42//!
43//! env.add_test("lowercase", is_lowercase);
44//! ```
45//!
46//! MiniJinja will perform the necessary conversions automatically.  For more
47//! information see the [`Function`](crate::functions::Function) trait.  If a
48//! test returns a value that is not a bool, it will be evaluated for truthiness
49//! with [`Value::is_true`].
50//!
51//! # Built-in Tests
52//!
53//! When the `builtins` feature is enabled a range of built-in tests are
54//! automatically added to the environment.  These are also all provided in
55//! this module.  Note though that these functions are not to be
56//! called from Rust code as their exact interface (arguments and return types)
57//! might change from one MiniJinja version to another.
58#[cfg(feature = "builtins")]
59use crate::error::Error;
60use crate::value::Value;
61#[cfg(feature = "builtins")]
62use crate::vm::State;
63
64/// Checks if a value is undefined.
65///
66/// ```jinja
67/// {{ 42 is undefined }} -> false
68/// ```
69pub fn is_undefined(v: &Value) -> bool {
70    v.is_undefined()
71}
72
73/// Checks if a value is defined.
74///
75/// ```jinja
76/// {{ 42 is defined }} -> true
77/// ```
78pub fn is_defined(v: &Value) -> bool {
79    !v.is_undefined()
80}
81
82/// Checks if a value is none.
83///
84/// ```jinja
85/// {{ none is none }} -> true
86/// ```
87pub fn is_none(v: &Value) -> bool {
88    v.is_none()
89}
90
91/// Checks if a value is safe.
92///
93/// ```jinja
94/// {{ "<hello>"|escape is safe }} -> true
95/// ```
96///
97/// This filter is also registered with the `escaped` alias.
98pub fn is_safe(v: &Value) -> bool {
99    v.is_safe()
100}
101
102#[cfg(feature = "builtins")]
103mod builtins {
104    use super::*;
105
106    use std::borrow::Cow;
107
108    use crate::value::ops::{coerce, rem, CoerceResult, WideInt};
109    use crate::value::ValueKind;
110
111    /// Return true if the object is a boolean value.
112    ///
113    /// ```jinja
114    /// {{ true is boolean }} -> true
115    /// ```
116    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
117    pub fn is_boolean(v: &Value) -> bool {
118        v.kind() == ValueKind::Bool
119    }
120
121    /// Checks if a value is odd.
122    ///
123    /// ```jinja
124    /// {{ 41 is odd }} -> true
125    /// ```
126    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
127    pub fn is_odd(v: Value) -> bool {
128        int_is_odd(v) == Some(true)
129    }
130
131    /// Checks if a value is even.
132    ///
133    /// ```jinja
134    /// {{ 42 is even }} -> true
135    /// ```
136    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
137    pub fn is_even(v: Value) -> bool {
138        int_is_odd(v) == Some(false)
139    }
140
141    /// Returns whether an integer is odd, or `None` if it is not an integer.
142    ///
143    /// Integers above the `i128` range are stored as `u128` and are checked
144    /// as such.  Like in Jinja2, floats with an integer value count as
145    /// integers, so `1e20 is even` is true.
146    fn int_is_odd(v: Value) -> Option<bool> {
147        match v.0 {
148            crate::value::ValueRepr::U128(x) => Some(x.0 % 2 != 0),
149            // `fract` is NaN for infinity, so it is not an integer
150            crate::value::ValueRepr::F64(x) => (x.fract() == 0.0).then(|| x % 2.0 != 0.0),
151            _ => i128::try_from(v).ok().map(|x| x % 2 != 0),
152        }
153    }
154
155    /// Return true if the value is divisible by another one.
156    ///
157    /// ```jinja
158    /// {{ 42 is divisibleby(2) }} -> true
159    /// ```
160    ///
161    /// When used as the builtin `divisibleby` test, dividing a number by zero
162    /// fails like `%` does.  This function returns `false` in that case.
163    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
164    pub fn is_divisibleby(v: &Value, other: &Value) -> bool {
165        is_divisibleby_checked(v, other).unwrap_or(false)
166    }
167
168    /// The builtin `divisibleby` test.  Like [`is_divisibleby`] but dividing
169    /// a number by zero is an error like for `%` and in Jinja2.
170    pub(crate) fn is_divisibleby_checked(v: &Value, other: &Value) -> Result<bool, Error> {
171        let is_numeric = |v: &Value| matches!(v.kind(), ValueKind::Number | ValueKind::Bool);
172        if is_numeric(v) && is_numeric(other) && !other.is_true() {
173            return rem(v, other).map(|_| false);
174        }
175        Ok(match coerce(v, other, false) {
176            // `wrapping_rem` only wraps for `i128::MIN % -1`, which is 0.
177            Some(CoerceResult::I128(a, b)) => b != 0 && a.wrapping_rem(b) == 0,
178            Some(CoerceResult::F64(a, b)) => (a % b) == 0.0,
179            Some(CoerceResult::Str(..)) => false,
180            None => match (WideInt::from_value(v), WideInt::from_value(other)) {
181                (Some(a), Some(b)) => a.div_rem_floor(b).is_some_and(|(_, rem)| rem.is_zero()),
182                _ => false,
183            },
184        })
185    }
186
187    /// Checks if this value is a number.
188    ///
189    /// ```jinja
190    /// {{ 42 is number }} -> true
191    /// {{ "42" is number }} -> false
192    /// ```
193    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
194    pub fn is_number(v: &Value) -> bool {
195        matches!(v.kind(), ValueKind::Number | ValueKind::Bool)
196    }
197
198    /// Checks if this value is an integer.
199    ///
200    /// ```jinja
201    /// {{ 42 is integer }} -> true
202    /// {{ 42.0 is integer }} -> false
203    /// ```
204    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
205    pub fn is_integer(v: &Value) -> bool {
206        v.is_integer()
207    }
208
209    /// Checks if this value is a float
210    ///
211    /// ```jinja
212    /// {{ 42 is float }} -> false
213    /// {{ 42.0 is float }} -> true
214    /// ```
215    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
216    pub fn is_float(v: &Value) -> bool {
217        matches!(v.0, crate::value::ValueRepr::F64(_))
218    }
219
220    /// Checks if this value is a string.
221    ///
222    /// ```jinja
223    /// {{ "42" is string }} -> true
224    /// {{ 42 is string }} -> false
225    /// ```
226    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
227    pub fn is_string(v: &Value) -> bool {
228        matches!(v.kind(), ValueKind::String)
229    }
230
231    /// Checks if this value is a sequence
232    ///
233    /// ```jinja
234    /// {{ [1, 2, 3] is sequence }} -> true
235    /// {{ 42 is sequence }} -> false
236    /// ```
237    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
238    pub fn is_sequence(v: &Value) -> bool {
239        v.is_undefined() || matches!(v.kind(), ValueKind::Seq)
240    }
241
242    /// Checks if this value can be iterated over.
243    ///
244    /// ```jinja
245    /// {{ [1, 2, 3] is iterable }} -> true
246    /// {{ 42 is iterable }} -> false
247    /// ```
248    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
249    pub fn is_iterable(v: &Value) -> bool {
250        v.try_iter().is_ok()
251    }
252
253    /// Checks if this value is a mapping
254    ///
255    /// ```jinja
256    /// {{ {"foo": "bar"} is mapping }} -> true
257    /// {{ [1, 2, 3] is mapping }} -> false
258    /// ```
259    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
260    pub fn is_mapping(v: &Value) -> bool {
261        matches!(v.kind(), ValueKind::Map)
262    }
263
264    /// Checks if the value is starting with a string.
265    ///
266    /// ```jinja
267    /// {{ "foobar" is startingwith "foo" }} -> true
268    /// {{ "foobar" is startingwith "bar" }} -> false
269    /// ```
270    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
271    pub fn is_startingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool {
272        v.starts_with(&other as &str)
273    }
274
275    /// Checks if the value is ending with a string.
276    ///
277    /// ```jinja
278    /// {{ "foobar" is endingwith "bar" }} -> true
279    /// {{ "foobar" is endingwith "foo" }} -> false
280    /// ```
281    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
282    pub fn is_endingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool {
283        v.ends_with(&other as &str)
284    }
285
286    /// Test version of `==`.
287    ///
288    /// This is useful when combined with [`select`](crate::filters::select).
289    ///
290    /// ```jinja
291    /// {{ 1 is eq 1 }} -> true
292    /// {{ [1, 2, 3]|select("==", 1) }} => [1]
293    /// ```
294    ///
295    /// By default aliased to `equalto` and `==`.
296    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
297    #[cfg(feature = "builtins")]
298    pub fn is_eq(value: &Value, other: &Value) -> bool {
299        *value == *other
300    }
301
302    /// Test version of `!=`.
303    ///
304    /// This is useful when combined with [`select`](crate::filters::select).
305    ///
306    /// ```jinja
307    /// {{ 2 is ne 1 }} -> true
308    /// {{ [1, 2, 3]|select("!=", 1) }} => [2, 3]
309    /// ```
310    ///
311    /// By default aliased to `!=`.
312    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
313    #[cfg(feature = "builtins")]
314    pub fn is_ne(value: &Value, other: &Value) -> bool {
315        *value != *other
316    }
317
318    /// Test version of `<`.
319    ///
320    /// This is useful when combined with [`select`](crate::filters::select).
321    ///
322    /// ```jinja
323    /// {{ 1 is lt 2 }} -> true
324    /// {{ [1, 2, 3]|select("<", 2) }} => [1]
325    /// ```
326    ///
327    /// By default aliased to `lessthan` and `<`.
328    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
329    #[cfg(feature = "builtins")]
330    pub fn is_lt(value: &Value, other: &Value) -> bool {
331        *value < *other
332    }
333
334    /// Test version of `<=`.
335    ///
336    /// This is useful when combined with [`select`](crate::filters::select).
337    ///
338    /// ```jinja
339    /// {{ 1 is le 2 }} -> true
340    /// {{ [1, 2, 3]|select("<=", 2) }} => [1, 2]
341    /// ```
342    ///
343    /// By default aliased to `<=`.
344    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
345    #[cfg(feature = "builtins")]
346    pub fn is_le(value: &Value, other: &Value) -> bool {
347        *value <= *other
348    }
349
350    /// Test version of `>`.
351    ///
352    /// This is useful when combined with [`select`](crate::filters::select).
353    ///
354    /// ```jinja
355    /// {{ 2 is gt 1 }} -> true
356    /// {{ [1, 2, 3]|select(">", 2) }} => [3]
357    /// ```
358    ///
359    /// By default aliased to `greaterthan` and `>`.
360    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
361    #[cfg(feature = "builtins")]
362    pub fn is_gt(value: &Value, other: &Value) -> bool {
363        *value > *other
364    }
365
366    /// Test version of `>=`.
367    ///
368    /// This is useful when combined with [`select`](crate::filters::select).
369    ///
370    /// ```jinja
371    /// {{ 2 is ge 1 }} -> true
372    /// {{ [1, 2, 3]|select(">=", 2) }} => [2, 3]
373    /// ```
374    ///
375    /// By default aliased to `>=`.
376    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
377    #[cfg(feature = "builtins")]
378    pub fn is_ge(value: &Value, other: &Value) -> bool {
379        *value >= *other
380    }
381
382    /// Test version of `in`.
383    ///
384    /// ```jinja
385    /// {{ 1 is in [1, 2, 3] }} -> true
386    /// {{ [1, 2, 3]|select("in", [1, 2]) }} => [1, 2]
387    /// ```
388    ///
389    /// This is useful when combined with [`select`](crate::filters::select).
390    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
391    #[cfg(feature = "builtins")]
392    pub fn is_in(state: &State, value: &Value, other: &Value) -> Result<bool, Error> {
393        ok!(state.undefined_behavior().assert_iterable(other));
394        Ok(crate::value::ops::contains(Some(state), other, value)
395            .map(|value| value.is_true())
396            .unwrap_or(false))
397    }
398
399    /// Checks if a value is `true`.
400    ///
401    /// ```jinja
402    /// {% if value is true %}...{% endif %}
403    /// ```
404    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
405    #[cfg(feature = "builtins")]
406    pub fn is_true(value: &Value) -> bool {
407        matches!(value.0, crate::value::ValueRepr::Bool(true))
408    }
409
410    /// Checks if a value is `false`.
411    ///
412    /// ```jinja
413    /// {% if value is false %}...{% endif %}
414    /// ```
415    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
416    #[cfg(feature = "builtins")]
417    pub fn is_false(value: &Value) -> bool {
418        matches!(value.0, crate::value::ValueRepr::Bool(false))
419    }
420
421    /// Checks if a filter with a given name is available.
422    ///
423    /// ```jinja
424    /// {% if 'tojson' is filter %}...{% endif %}
425    /// ```
426    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
427    #[cfg(feature = "builtins")]
428    pub fn is_filter(state: &State, name: &str) -> bool {
429        state.env().get_filter(name).is_some()
430    }
431
432    /// Checks if a test with a given name is available.
433    ///
434    /// ```jinja
435    /// {% if 'greaterthan' is test %}...{% endif %}
436    /// ```
437    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
438    #[cfg(feature = "builtins")]
439    pub fn is_test(state: &State, name: &str) -> bool {
440        state.env().get_test(name).is_some()
441    }
442
443    /// Checks if a string is all lowercase.
444    ///
445    /// ```jinja
446    /// {{ 'foo' is lower }} -> true
447    /// ```
448    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
449    #[cfg(feature = "builtins")]
450    pub fn is_lower(value: &Value) -> bool {
451        let Some(name) = value.as_str() else {
452            return false;
453        };
454        let mut has_cased = false;
455        for ch in name.chars() {
456            if ch.is_uppercase()
457                || (!ch.is_lowercase()
458                    && (ch.to_lowercase().any(|mapped| mapped != ch)
459                        || ch.to_uppercase().any(|mapped| mapped != ch)))
460            {
461                return false;
462            }
463            has_cased |= ch.is_lowercase();
464        }
465        has_cased
466    }
467
468    /// Checks if a string is all uppercase.
469    ///
470    /// ```jinja
471    /// {{ 'FOO' is upper }} -> true
472    /// ```
473    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
474    #[cfg(feature = "builtins")]
475    pub fn is_upper(value: &Value) -> bool {
476        let Some(name) = value.as_str() else {
477            return false;
478        };
479        let mut has_cased = false;
480        for ch in name.chars() {
481            if ch.is_lowercase()
482                || (!ch.is_uppercase()
483                    && (ch.to_lowercase().any(|mapped| mapped != ch)
484                        || ch.to_uppercase().any(|mapped| mapped != ch)))
485            {
486                return false;
487            }
488            has_cased |= ch.is_uppercase();
489        }
490        has_cased
491    }
492
493    /// Checks if two values are identical.
494    ///
495    /// This primarily exists for compatibilith with Jinja2.  It can be seen as a much
496    /// stricter comparison than a regular comparison.  The main difference is that
497    /// values that have the same structure but a different internal object will not
498    /// compare equal.
499    ///
500    /// ```jinja
501    /// {{ [1, 2, 3] is sameas [1, 2, 3] }}
502    ///     -> false
503    ///
504    /// {{ false is sameas false }}
505    ///     -> true
506    /// ```
507    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
508    #[cfg(feature = "builtins")]
509    pub fn is_sameas(value: &Value, other: &Value) -> bool {
510        match (value.as_object(), other.as_object()) {
511            (Some(a), Some(b)) => a.is_same_object(b),
512            (None, Some(_)) | (Some(_), None) => false,
513            (None, None) => {
514                if value.kind() != other.kind() || value.is_integer() != other.is_integer() {
515                    false
516                } else {
517                    value == other
518                }
519            }
520        }
521    }
522}
523
524#[cfg(feature = "builtins")]
525pub use self::builtins::*;