Skip to content

Commit

Permalink
Added unit tests for decode
Browse files Browse the repository at this point in the history
  • Loading branch information
ashishajr authored and hurl-bot committed Jan 20, 2025
1 parent cc30851 commit 0a6ee2f
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions packages/hurl/src/runner/filter/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,97 @@ pub fn eval_decode(
}
}
}

#[cfg(test)]
mod tests {
use hurl_core::ast::{Filter, FilterValue, SourceInfo, Template, TemplateElement, Whitespace};
use hurl_core::reader::Pos;

use super::*;
use crate::runner::filter::eval::eval_filter;
use crate::runner::VariableSet;

/// Helper function to return a new filter given an `encoding`
fn new_decode_filter(encoding: &str) -> Filter {
// Example: decode "gb2312"
Filter {
source_info: SourceInfo::new(Pos::new(1, 1), Pos::new(1, 1)),
value: FilterValue::Decode {
space0: Whitespace {
value: String::new(),
source_info: SourceInfo::new(Pos::new(7, 1), Pos::new(8, 1)),
},
encoding: Template {
delimiter: None,
elements: vec![TemplateElement::String {
value: encoding.to_string(),
encoded: encoding.to_string(),
}],
source_info: SourceInfo::new(Pos::new(8, 1), Pos::new(8 + encoding.len(), 1)),
},
},
}
}

#[test]
fn eval_filter_decode_ok() {
let variables = VariableSet::new();

let filter = new_decode_filter("utf-8");
let bytes = vec![
0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd, 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c,
];
let ret = eval_filter(&filter, &Value::Bytes(bytes), &variables, false);
assert_eq!(ret.unwrap().unwrap(), Value::String("你好世界".to_string()));

let filter = new_decode_filter("gb2312");
let bytes = vec![0xc4, 0xe3, 0xba, 0xc3, 0xca, 0xc0, 0xbd, 0xe7];
let ret = eval_filter(&filter, &Value::Bytes(bytes), &variables, false);
assert_eq!(ret.unwrap().unwrap(), Value::String("你好世界".to_string()));
}

#[test]
fn eval_filter_decode_ko_unknown_encoding() {
let variables = VariableSet::new();

let filter = new_decode_filter("xxx");
let bytes = vec![];

let ret = eval_filter(&filter, &Value::Bytes(bytes), &variables, false);

assert_eq!(
ret.unwrap_err().kind,
RunnerErrorKind::FilterInvalidEncoding("xxx".to_string()),
);
}

#[test]
fn eval_filter_decode_ko_bad_bytes_input() {
let variables = VariableSet::new();

let filter = new_decode_filter("gb2312");
let bytes = vec![0xc4, 0x00];
let ret = eval_filter(&filter, &Value::Bytes(bytes), &variables, false);
assert_eq!(
ret.unwrap_err().kind,
RunnerErrorKind::FilterDecode("gb2312".to_string()),
);
}

#[test]
fn eval_filter_decode_ko_bad_input_type() {
let variables = VariableSet::new();

let filter = new_decode_filter("utf-8");
let ret = eval_filter(
&filter,
&Value::String("café".to_string()),
&variables,
false,
);
assert_eq!(
ret.unwrap_err().kind,
RunnerErrorKind::FilterInvalidInput("string".to_string()),
);
}
}

0 comments on commit 0a6ee2f

Please sign in to comment.