Add trim option to shell extension and tests

This commit is contained in:
Federico Terzi 2019-12-13 22:28:43 +01:00
parent db2ff8c6ca
commit 12fc31700e

View File

@ -56,8 +56,20 @@ impl super::Extension for ShellExtension {
match output {
Ok(output) => {
let output_str = String::from_utf8_lossy(output.stdout.as_slice());
let mut output_str = output_str.into_owned();
Some(output_str.into_owned())
// If specified, trim the output
let trim_opt = params.get(&Value::from("trim"));
if let Some(value) = trim_opt {
let val = value.as_bool();
if let Some(val) = val {
if val {
output_str = output_str.trim().to_owned()
}
}
}
Some(output_str)
},
Err(e) => {
error!("Could not execute cmd '{}', error: {}", cmd, e);
@ -65,4 +77,75 @@ impl super::Extension for ShellExtension {
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extension::Extension;
#[test]
fn test_shell_basic() {
let mut params = Mapping::new();
params.insert(Value::from("cmd"), Value::from("echo hello world"));
let extension = ShellExtension::new();
let output = extension.calculate(&params);
assert!(output.is_some());
assert_eq!(output.unwrap(), "hello world\n");
}
#[test]
fn test_shell_trimmed() {
let mut params = Mapping::new();
params.insert(Value::from("cmd"), Value::from("echo hello world"));
params.insert(Value::from("trim"), Value::from(true));
let extension = ShellExtension::new();
let output = extension.calculate(&params);
assert!(output.is_some());
assert_eq!(output.unwrap(), "hello world");
}
#[test]
fn test_shell_trimmed_2() {
let mut params = Mapping::new();
params.insert(Value::from("cmd"), Value::from("echo \" hello world \""));
params.insert(Value::from("trim"), Value::from(true));
let extension = ShellExtension::new();
let output = extension.calculate(&params);
assert!(output.is_some());
assert_eq!(output.unwrap(), "hello world");
}
#[test]
fn test_shell_trimmed_malformed() {
let mut params = Mapping::new();
params.insert(Value::from("cmd"), Value::from("echo hello world"));
params.insert(Value::from("trim"), Value::from("error"));
let extension = ShellExtension::new();
let output = extension.calculate(&params);
assert!(output.is_some());
assert_eq!(output.unwrap(), "hello world\n");
}
#[test]
#[cfg(not(target_os = "windows"))]
fn test_shell_pipes() {
let mut params = Mapping::new();
params.insert(Value::from("cmd"), Value::from("echo hello world | cat"));
params.insert(Value::from("trim"), Value::from(true));
let extension = ShellExtension::new();
let output = extension.calculate(&params);
assert!(output.is_some());
assert_eq!(output.unwrap(), "hello world");
}
}