|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +use crate::DscError; |
| 5 | +use crate::configure::context::Context; |
| 6 | +use crate::functions::AcceptedArgKind; |
| 7 | +use super::Function; |
| 8 | +use rust_i18n::t; |
| 9 | +use serde_json::Value; |
| 10 | + |
| 11 | +#[derive(Debug, Default)] |
| 12 | +pub struct If {} |
| 13 | + |
| 14 | +impl Function for If { |
| 15 | + fn accepted_arg_types(&self) -> Vec<AcceptedArgKind> { |
| 16 | + vec![AcceptedArgKind::Boolean, AcceptedArgKind::String, AcceptedArgKind::Number, AcceptedArgKind::Array, AcceptedArgKind::Object] |
| 17 | + } |
| 18 | + |
| 19 | + fn min_args(&self) -> usize { |
| 20 | + 3 |
| 21 | + } |
| 22 | + |
| 23 | + fn max_args(&self) -> usize { |
| 24 | + 3 |
| 25 | + } |
| 26 | + |
| 27 | + fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> { |
| 28 | + let Some(condition) = args[0].as_bool() else { |
| 29 | + return Err(DscError::Function("if".to_string(), t!("functions.if.conditionNotBoolean").to_string())); |
| 30 | + }; |
| 31 | + |
| 32 | + if condition { |
| 33 | + Ok(args[1].clone()) |
| 34 | + } else { |
| 35 | + Ok(args[2].clone()) |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +#[cfg(test)] |
| 41 | +mod tests { |
| 42 | + use crate::configure::context::Context; |
| 43 | + use crate::parser::Statement; |
| 44 | + |
| 45 | + #[test] |
| 46 | + fn invalid_condition() { |
| 47 | + let mut parser = Statement::new().unwrap(); |
| 48 | + let result = parser.parse_and_execute("[if('PATH', 1 , 2)]", &Context::new()); |
| 49 | + assert!(result.is_err()); |
| 50 | + } |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn condition_true() { |
| 54 | + let mut parser = Statement::new().unwrap(); |
| 55 | + let result = parser.parse_and_execute("[if(true, 'left', 'right')]", &Context::new()).unwrap(); |
| 56 | + assert_eq!(result, "left"); |
| 57 | + } |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn condition_false() { |
| 61 | + let mut parser = Statement::new().unwrap(); |
| 62 | + let result = parser.parse_and_execute("[if(false, 'left', 'right')]", &Context::new()).unwrap(); |
| 63 | + assert_eq!(result, "right"); |
| 64 | + } |
| 65 | +} |
0 commit comments