diff --git a/src/bre.rs b/src/bre.rs index 6e04fbcd..daa6d5ae 100644 --- a/src/bre.rs +++ b/src/bre.rs @@ -262,19 +262,54 @@ fn translate_bracket( mod tests { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; - fn matches(pattern: &str, text: &str) -> bool { - Bre::new(pattern).unwrap().is_match(text.as_bytes()) - } - - #[test] - fn groups_and_alternatives() { - assert!(matches(r"^ *\(sub\|fn\) ", " fn main")); - assert!(matches(r"^ *\(sub\|fn\) ", "sub x")); - assert!(!matches(r"^ *\(sub\|fn\) ", " let x")); - // Unescaped operators of extended expressions are ordinary characters. - assert!(matches(r"f(x)|y+?", "f(x)|y+?")); - assert!(!matches(r"f(x)|y+?", "fx")); + #[rstest] + // Groups and alternatives. + #[case::alternative_first(r"^ *\(sub\|fn\) ", " fn main", true)] + #[case::alternative_second(r"^ *\(sub\|fn\) ", "sub x", true)] + #[case::alternative_none(r"^ *\(sub\|fn\) ", " let x", false)] + // Unescaped operators of extended expressions are ordinary characters. + #[case::ere_operators_are_literal(r"f(x)|y+?", "f(x)|y+?", true)] + #[case::ere_operators_do_not_group(r"f(x)|y+?", "fx", false)] + // Intervals and repetitions. + #[case::interval(r"^ab\{2,3\}c$", "abbc", true)] + #[case::interval_too_few(r"^ab\{2,3\}c$", "abc", false)] + #[case::one_or_more(r"^x\+$", "xxx", true)] + #[case::zero_or_one(r"^y\?z$", "z", true)] + // `*` with nothing to repeat is literal. + #[case::leading_star(r"*q", "a*q", true)] + #[case::star_after_anchor(r"^*q", "*q", true)] + #[case::star_after_group_start(r"\(*\)", "*", true)] + #[case::star_repeats(r"to*k", "tk", true)] + // Anchors only at the ends. + #[case::caret_in_middle(r"a^b", "a^b", true)] + #[case::dollar_in_middle(r"a$b", "a$b", true)] + #[case::dollar_at_end(r"end$", "the end", true)] + #[case::dollar_at_end_no_match(r"end$", "endless", false)] + #[case::anchors_in_alternatives(r"\(x$\|^y\)", "yes", true)] + // Bracket expressions. + #[case::class_with_dollar(r"^[[:alpha:]$_]", "$var", true)] + #[case::class_with_underscore(r"^[[:alpha:]$_]", "_x", true)] + #[case::class_no_match(r"^[[:alpha:]$_]", " x", false)] + #[case::leading_bracket(r"[]x]", "]", true)] + #[case::negated_leading_bracket(r"[^]x]", "y", true)] + #[case::backslash_in_bracket(r"[a\]", "\\", true)] + #[case::range(r"[a-c]", "b", true)] + #[case::trailing_dash(r"[a-]", "-", true)] + #[case::doubled_set_operators(r"[&&~~[]", "[", true)] + // Operators with nothing to repeat are literal. + #[case::leading_interval(r"\{3\}", "{3}", true)] + #[case::plus_after_group_start(r"\(\+x\)", "+x", true)] + #[case::interval_without_min(r"q\{,2\}r", "r", true)] + #[case::interval_without_max(r"^q\{2,\}$", "qqqq", true)] + #[case::collating_symbol(r"[[.-.][=k=]]", "-", true)] + #[case::equivalence_class(r"[[.-.][=k=]]", "k", true)] + fn matches(#[case] pattern: &str, #[case] text: &str, #[case] expected: bool) { + assert_eq!( + Bre::new(pattern).unwrap().is_match(text.as_bytes()), + expected + ); } // Only is_match() is used and back references are rejected, so a group @@ -287,74 +322,22 @@ mod tests { assert!(!bre.is_match(b"abd")); } - #[test] - fn intervals_and_repetitions() { - assert!(matches(r"^ab\{2,3\}c$", "abbc")); - assert!(!matches(r"^ab\{2,3\}c$", "abc")); - assert!(matches(r"^x\+$", "xxx")); - assert!(matches(r"^y\?z$", "z")); - // `*` with nothing to repeat is literal. - assert!(matches(r"*q", "a*q")); - assert!(matches(r"^*q", "*q")); - assert!(matches(r"\(*\)", "*")); - assert!(matches(r"to*k", "tk")); - } - - #[test] - fn anchors_only_at_the_ends() { - assert!(matches(r"a^b", "a^b")); - assert!(matches(r"a$b", "a$b")); - assert!(matches(r"end$", "the end")); - assert!(!matches(r"end$", "endless")); - assert!(matches(r"\(x$\|^y\)", "yes")); - } - - #[test] - fn bracket_expressions() { - assert!(matches(r"^[[:alpha:]$_]", "$var")); - assert!(matches(r"^[[:alpha:]$_]", "_x")); - assert!(!matches(r"^[[:alpha:]$_]", " x")); - assert!(matches(r"[]x]", "]")); - assert!(matches(r"[^]x]", "y")); - assert!(matches(r"[a\]", "\\")); - assert!(matches(r"[a-c]", "b")); - assert!(matches(r"[a-]", "-")); - assert!(matches(r"[&&~~[]", "[")); - } - - #[test] - fn errors() { - for (pattern, message) in [ - ("ab\\", "Trailing backslash"), - ("[ab", "Unmatched [, [^, [:, [., or [="), - ("[[:alpha:]", "Unmatched [, [^, [:, [., or [="), - (r"\(a\)\1", "Invalid back reference"), - (r"x\(y", r"Unmatched ( or \("), - (r"x\)y", r"Unmatched ) or \)"), - (r"k\{4", r"Unmatched \{"), - (r"k\{\}", r"Invalid content of \{\}"), - (r"k\{2,z\}", r"Invalid content of \{\}"), - (r"k\{5,2\}", r"Invalid content of \{\}"), - (r"k\{40000\}", "Regular expression too big"), - ("[[:vowel:]]", "Invalid character class name"), - ("[[.ab.]]", "Invalid collation character"), - ("[m-c]", "Invalid range end"), - ] { - assert_eq!( - Bre::new(pattern).err().as_deref(), - Some(message), - "{pattern}" - ); - } - } - - #[test] - fn literal_operators_with_nothing_to_repeat() { - assert!(matches(r"\{3\}", "{3}")); - assert!(matches(r"\(\+x\)", "+x")); - assert!(matches(r"q\{,2\}r", "r")); - assert!(matches(r"^q\{2,\}$", "qqqq")); - assert!(matches(r"[[.-.][=k=]]", "-")); - assert!(matches(r"[[.-.][=k=]]", "k")); + #[rstest] + #[case::trailing_backslash("ab\\", "Trailing backslash")] + #[case::unmatched_bracket("[ab", "Unmatched [, [^, [:, [., or [=")] + #[case::unmatched_class_bracket("[[:alpha:]", "Unmatched [, [^, [:, [., or [=")] + #[case::back_reference(r"\(a\)\1", "Invalid back reference")] + #[case::unmatched_open_group(r"x\(y", r"Unmatched ( or \(")] + #[case::unmatched_close_group(r"x\)y", r"Unmatched ) or \)")] + #[case::unmatched_interval(r"k\{4", r"Unmatched \{")] + #[case::empty_interval(r"k\{\}", r"Invalid content of \{\}")] + #[case::non_numeric_interval(r"k\{2,z\}", r"Invalid content of \{\}")] + #[case::reversed_interval(r"k\{5,2\}", r"Invalid content of \{\}")] + #[case::huge_interval(r"k\{40000\}", "Regular expression too big")] + #[case::unknown_class("[[:vowel:]]", "Invalid character class name")] + #[case::multi_char_collation("[[.ab.]]", "Invalid collation character")] + #[case::reversed_range("[m-c]", "Invalid range end")] + fn errors(#[case] pattern: &str, #[case] message: &str) { + assert_eq!(Bre::new(pattern).err().as_deref(), Some(message)); } } diff --git a/src/cmp.rs b/src/cmp.rs index ed677e8d..4010342c 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -724,570 +724,182 @@ fn report_difference( #[cfg(test)] mod tests { use super::*; + use rstest::rstest; + fn os(s: &str) -> OsString { OsString::from(s) } - #[test] - fn help() { - for args in [ - vec!["cmp", "--help"], - vec!["cmp", "foo", "--help"], - vec!["cmp", "--help", "--invalid"], - vec!["cmp", "-l", "-s", "--help"], - ] { - let params = parse_params(args.into_iter().map(os).peekable()).unwrap(); - assert!(params.help); - assert_eq!(params.executable, os("cmp")); - } + fn parse(args: &[&str]) -> Result { + parse_params( + std::iter::once("cmp") + .chain(args.iter().copied()) + .map(os) + .peekable(), + ) } - #[test] - fn count_newlines_across_chunks() { - assert_eq!(count_newlines(b""), 0); - assert_eq!(count_newlines(b"no newline"), 0); - // more than one 255-byte chunk of nothing but newlines - assert_eq!(count_newlines(&[b'\n'; 1000]), 1000); - assert_eq!(count_newlines(&b"ab\ncd\n".repeat(300)), 600); - } - - #[test] - fn positional() { - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params([os("cmp"), os("foo"), os("bar")].iter().cloned().peekable()) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("-"), - ..Default::default() - }), - parse_params([os("cmp"), os("foo")].iter().cloned().peekable()) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("--help"), - ..Default::default() - }), - parse_params( - [os("cmp"), os("foo"), os("--"), os("--help")] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(1), - skip_b: None, - ..Default::default() - }), - parse_params( - [os("cmp"), os("foo"), os("bar"), os("1")] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(1), - skip_b: Some(SkipU64::MAX), - ..Default::default() - }), - parse_params( - [os("cmp"), os("foo"), os("bar"), os("1"), os("2Y")] - .iter() - .cloned() - .peekable() - ) - ); - - // Bad positional arguments. - assert_eq!( - Err("Usage: cmp ".to_string()), - parse_params( - [os("cmp"), os("foo"), os("bar"), os("1"), os("2"), os("3")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Err("Usage: cmp ".to_string()), - parse_params([os("cmp")].iter().cloned().peekable()) - ); - } - - #[test] - fn execution_modes() { - let print_bytes = Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - print_bytes: true, - ..Default::default() - }; - assert_eq!( - Ok(print_bytes.clone()), - parse_params( - [os("cmp"), os("-b"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(print_bytes), - parse_params( - [os("cmp"), os("--print-bytes"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - let verbose = Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - verbose: true, - ..Default::default() - }; - assert_eq!( - Ok(verbose.clone()), - parse_params( - [os("cmp"), os("-l"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(verbose), - parse_params( - [os("cmp"), os("--verbose"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - let verbose_and_print_bytes = Params { + fn foo_bar() -> Params { + Params { executable: os("cmp"), from: os("foo"), to: os("bar"), - print_bytes: true, - verbose: true, ..Default::default() - }; - assert_eq!( - Ok(verbose_and_print_bytes.clone()), - parse_params( - [os("cmp"), os("-l"), os("-b"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(verbose_and_print_bytes.clone()), - parse_params( - [os("cmp"), os("-lb"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(verbose_and_print_bytes), - parse_params( - [os("cmp"), os("-bl"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - quiet: true, - ..Default::default() - }), - parse_params( - [os("cmp"), os("-s"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - // Some options do not mix. - assert_eq!( - Err("cmp: options -l and -s are incompatible".to_string()), - parse_params( - [os("cmp"), os("-l"), os("-s"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); + } } - #[test] - fn max_bytes() { - let max_bytes = Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - max_bytes: Some(1), - ..Default::default() - }; - assert_eq!( - Ok(max_bytes.clone()), - parse_params( - [os("cmp"), os("-n"), os("1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(max_bytes), - parse_params( - [os("cmp"), os("--bytes=1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - max_bytes: Some(BytesLimitU64::MAX), - ..Default::default() - }), - parse_params( - [ - os("cmp"), - os("--bytes=99999999999999999999999999999999999999999999999999999999999"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); + #[rstest] + #[case::alone(&["--help"])] + #[case::with_operand(&["foo", "--help"])] + #[case::before_invalid(&["--help", "--invalid"])] + #[case::incompatible_options(&["-l", "-s", "--help"])] + fn help(#[case] args: &[&str]) { + let params = parse(args).unwrap(); + assert!(params.help); + assert_eq!(params.executable, os("cmp")); + } - // Same unit suffixes as --ignore-initial - for (args, bytes) in [ - (&["-n", "1K"][..], 1_024), - (&["--bytes=1kB"][..], 1_000), - (&["--bytes=2M"][..], 2_097_152), - ] { - let mut opts = vec![os("cmp")]; - opts.extend(args.iter().map(|arg| os(arg))); - opts.extend([os("foo"), os("bar")]); - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - max_bytes: Some(bytes), - ..Default::default() - }), - parse_params(opts.into_iter().peekable()), - "{args:?}" - ); - } + #[rstest] + #[case::empty(b"".to_vec(), 0)] + #[case::no_newline(b"no newline".to_vec(), 0)] + // more than one 255-byte chunk of nothing but newlines + #[case::only_newlines(vec![b'\n'; 1000], 1000)] + #[case::mixed(b"ab\ncd\n".repeat(300), 600)] + fn count_newlines_across_chunks(#[case] input: Vec, #[case] expected: u64) { + assert_eq!(count_newlines(&input), expected); + } - // Failure case - assert_eq!( - Err("cmp: invalid --bytes value '1x'".to_string()), - parse_params( - [os("cmp"), os("--bytes=1x"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); + #[rstest] + #[case::positional_two_operands(&["foo", "bar"], foo_bar())] + #[case::positional_default_to_stdin(&["foo"], Params { to: os("-"), ..foo_bar() })] + #[case::positional_double_dash(&["foo", "--", "--help"], Params { to: os("--help"), ..foo_bar() })] + #[case::positional_skip_a(&["foo", "bar", "1"], Params { skip_a: Some(1), skip_b: None, ..foo_bar() })] + #[case::positional_skip_both( + &["foo", "bar", "1", "2Y"], + Params { skip_a: Some(1), skip_b: Some(SkipU64::MAX), ..foo_bar() }, + )] + #[case::print_bytes_short(&["-b", "foo", "bar"], Params { print_bytes: true, ..foo_bar() })] + #[case::print_bytes_long(&["--print-bytes", "foo", "bar"], Params { print_bytes: true, ..foo_bar() })] + #[case::verbose_short(&["-l", "foo", "bar"], Params { verbose: true, ..foo_bar() })] + #[case::verbose_long(&["--verbose", "foo", "bar"], Params { verbose: true, ..foo_bar() })] + #[case::verbose_print_bytes_separate( + &["-l", "-b", "foo", "bar"], + Params { print_bytes: true, verbose: true, ..foo_bar() }, + )] + #[case::verbose_print_bytes_lb( + &["-lb", "foo", "bar"], + Params { print_bytes: true, verbose: true, ..foo_bar() }, + )] + #[case::verbose_print_bytes_bl( + &["-bl", "foo", "bar"], + Params { print_bytes: true, verbose: true, ..foo_bar() }, + )] + #[case::quiet(&["-s", "foo", "bar"], Params { quiet: true, ..foo_bar() })] + #[case::max_bytes_short(&["-n", "1", "foo", "bar"], Params { max_bytes: Some(1), ..foo_bar() })] + #[case::max_bytes_long(&["--bytes=1", "foo", "bar"], Params { max_bytes: Some(1), ..foo_bar() })] + #[case::max_bytes_overflow( + &["--bytes=99999999999999999999999999999999999999999999999999999999999", "foo", "bar"], + Params { max_bytes: Some(BytesLimitU64::MAX), ..foo_bar() }, + )] + // Same unit suffixes as --ignore-initial + #[case::max_bytes_kibi(&["-n", "1K", "foo", "bar"], Params { max_bytes: Some(1_024), ..foo_bar() })] + #[case::max_bytes_kilo(&["--bytes=1kB", "foo", "bar"], Params { max_bytes: Some(1_000), ..foo_bar() })] + #[case::max_bytes_mebi(&["--bytes=2M", "foo", "bar"], Params { max_bytes: Some(2_097_152), ..foo_bar() })] + #[case::skip_short(&["-i", "1", "foo", "bar"], Params { skip_a: Some(1), skip_b: Some(1), ..foo_bar() })] + #[case::skip_long( + &["--ignore-initial=1", "foo", "bar"], + Params { skip_a: Some(1), skip_b: Some(1), ..foo_bar() }, + )] + #[case::skip_overflow( + &["-i", "99999999999999999999999999999999999999999999999999999999999", "foo", "bar"], + Params { skip_a: Some(SkipU64::MAX), skip_b: Some(SkipU64::MAX), ..foo_bar() }, + )] + #[case::skip_pair( + &["--ignore-initial=1:2", "foo", "bar"], + Params { skip_a: Some(1), skip_b: Some(2), ..foo_bar() }, + )] + // Uses the larger of the -i value and the positional skip, like GNU. + #[case::skip_larger_positional( + &["-i", "5:2", "foo", "bar", "3", "4"], + Params { skip_a: Some(5), skip_b: Some(4), ..foo_bar() }, + )] + #[case::skip_larger_positional_after_double_dash( + &["-i", "1", "--", "foo", "bar", "6"], + Params { skip_a: Some(6), skip_b: Some(1), ..foo_bar() }, + )] + // Also the larger value when -i is given more than once. + #[case::skip_larger_repeated( + &["-i", "1", "--ignore-initial=2:0", "foo", "bar"], + Params { skip_a: Some(2), skip_b: Some(1), ..foo_bar() }, + )] + fn valid(#[case] args: &[&str], #[case] expected: Params) { + assert_eq!(parse(args), Ok(expected)); } #[test] - fn skips() { - let skips = Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(1), - skip_b: Some(1), - ..Default::default() - }; - assert_eq!( - Ok(skips.clone()), - parse_params( - [os("cmp"), os("-i"), os("1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(skips), - parse_params( - [os("cmp"), os("--ignore-initial=1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - + fn skip_suffix_pair() { assert_eq!( Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(SkipU64::MAX), - skip_b: Some(SkipU64::MAX), - ..Default::default() - }), - parse_params( - [ - os("cmp"), - os("-i"), - os("99999999999999999999999999999999999999999999999999999999999"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(1), - skip_b: Some(2), - ..Default::default() - }), - parse_params( - [os("cmp"), os("--ignore-initial=1:2"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), skip_a: Some(1_000_000_000), #[cfg(target_pointer_width = "32")] skip_b: Some((2_147_483_647.5 * 2.0) as usize), #[cfg(target_pointer_width = "64")] skip_b: Some(1_152_921_504_606_846_976 * 2), - ..Default::default() - }), - parse_params( - [ - os("cmp"), - os("--ignore-initial=1GB:2E"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); - - // All special suffixes. - for (i, suffixes) in [ - ["kB", "K"], - ["MB", "M"], - ["GB", "G"], - ["TB", "T"], - ["PB", "P"], - ["EB", "E"], - ["ZB", "Z"], - ["YB", "Y"], - ] - .iter() - .enumerate() - { - let values = [ - (1_000 as SkipU64) - .checked_pow((i + 1) as u32) - .unwrap_or(SkipU64::MAX), - (1024 as SkipU64) - .checked_pow((i + 1) as u32) - .unwrap_or(SkipU64::MAX), - ]; - for (j, v) in values.iter().enumerate() { - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(*v), - skip_b: Some(2), - ..Default::default() - }), - parse_params( - [ - os("cmp"), - os("-i"), - os(&format!("1{}:2", suffixes[j])), - os("foo"), - os("bar"), - ] - .iter() - .cloned() - .peekable() - ) - ); - } - } - - // Uses the larger of the -i value and the positional skip, like GNU. - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(5), - skip_b: Some(4), - ..Default::default() + ..foo_bar() }), - parse_params( - [ - os("cmp"), - os("-i"), - os("5:2"), - os("foo"), - os("bar"), - os("3"), - os("4") - ] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(6), - skip_b: Some(1), - ..Default::default() - }), - parse_params( - [ - os("cmp"), - os("-i"), - os("1"), - os("--"), - os("foo"), - os("bar"), - os("6") - ] - .iter() - .cloned() - .peekable() - ) + parse(&["--ignore-initial=1GB:2E", "foo", "bar"]) ); + } - // Also the larger value when -i is given more than once. + // All special suffixes. + #[rstest] + #[case::kilo("kB", 1_000, 1)] + #[case::kibi("K", 1_024, 1)] + #[case::mega("MB", 1_000, 2)] + #[case::mebi("M", 1_024, 2)] + #[case::giga("GB", 1_000, 3)] + #[case::gibi("G", 1_024, 3)] + #[case::tera("TB", 1_000, 4)] + #[case::tebi("T", 1_024, 4)] + #[case::peta("PB", 1_000, 5)] + #[case::pebi("P", 1_024, 5)] + #[case::exa("EB", 1_000, 6)] + #[case::exbi("E", 1_024, 6)] + #[case::zetta("ZB", 1_000, 7)] + #[case::zebi("Z", 1_024, 7)] + #[case::yotta("YB", 1_000, 8)] + #[case::yobi("Y", 1_024, 8)] + fn skip_suffixes(#[case] suffix: &str, #[case] base: SkipU64, #[case] exponent: u32) { + let skip = format!("1{suffix}:2"); assert_eq!( Ok(Params { - executable: os("cmp"), - from: os("foo"), - to: os("bar"), - skip_a: Some(2), - skip_b: Some(1), - ..Default::default() + skip_a: Some(base.checked_pow(exponent).unwrap_or(SkipU64::MAX)), + skip_b: Some(2), + ..foo_bar() }), - parse_params( - [ - os("cmp"), - os("-i"), - os("1"), - os("--ignore-initial=2:0"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) + parse(&["-i", &skip, "foo", "bar"]) ); + } - // Failure cases - assert_eq!( - Err("cmp: invalid --ignore-initial value '1mb'".to_string()), - parse_params( - [os("cmp"), os("--ignore-initial=1mb"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Err("cmp: invalid --ignore-initial value '1:2:3'".to_string()), - parse_params( - [ - os("cmp"), - os("--ignore-initial=1:2:3"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Err("cmp: invalid --ignore-initial value '-1'".to_string()), - parse_params( - [os("cmp"), os("--ignore-initial=-1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); + #[rstest] + #[case::too_many_operands(&["foo", "bar", "1", "2", "3"], "Usage: cmp ")] + #[case::no_operand(&[], "Usage: cmp ")] + // Some options do not mix. + #[case::verbose_and_quiet(&["-l", "-s", "foo", "bar"], "cmp: options -l and -s are incompatible")] + #[case::invalid_bytes(&["--bytes=1x", "foo", "bar"], "cmp: invalid --bytes value '1x'")] + #[case::invalid_skip_suffix( + &["--ignore-initial=1mb", "foo", "bar"], + "cmp: invalid --ignore-initial value '1mb'", + )] + #[case::invalid_skip_triple( + &["--ignore-initial=1:2:3", "foo", "bar"], + "cmp: invalid --ignore-initial value '1:2:3'", + )] + #[case::invalid_skip_negative( + &["--ignore-initial=-1", "foo", "bar"], + "cmp: invalid --ignore-initial value '-1'", + )] + fn invalid(#[case] args: &[&str], #[case] error: &str) { + assert_eq!(parse(args), Err(error.to_string())); } } diff --git a/src/color.rs b/src/color.rs index cc73c351..64276f60 100644 --- a/src/color.rs +++ b/src/color.rs @@ -171,79 +171,60 @@ fn push_sgr(output: &mut Vec, parameters: &str) { mod tests { use super::*; use pretty_assertions::assert_eq; - - fn colorize_str(output: &str, format: Format) -> String { - String::from_utf8(colorize(output.as_bytes(), format, &Palette::default())).unwrap() - } - - #[test] - fn normal() { - assert_eq!( - colorize_str("3,4c3\n< owl\n< elk\n---\n> yak\n", Format::Normal), - "\x1b[36m3,4c3\x1b[0m\n\x1b[31m< owl\x1b[0m\n\x1b[31m< elk\x1b[0m\n---\n\x1b[32m> yak\x1b[0m\n" - ); - } - - #[test] - fn unified() { - // The deleted text looks like a header line, but only the first two - // lines are headers. - let output = "--- left\n+++ right\n@@ -2 +2 @@\n--- not a header\n+++ nor this\n"; - assert_eq!( - colorize_str(output, Format::Unified), - "\x1b[1m--- left\x1b[0m\n\x1b[1m+++ right\x1b[0m\n\x1b[36m@@ -2 +2 @@\x1b[0m\n\ - \x1b[31m--- not a header\x1b[0m\n\x1b[32m+++ nor this\x1b[0m\n" - ); - } - - #[test] - fn context() { - let output = "*** left\n--- right\n***************\n*** 1,2 ****\n cat\n! dog\n\ - --- 1,3 ----\n cat\n! cow\n+ pig\n"; - assert_eq!( - colorize_str(output, Format::Context), - "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ - \x1b[36m*** 1,2 ****\x1b[0m\n\x1b[31m cat\x1b[0m\n\x1b[31m! dog\x1b[0m\n\ - \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m cat\x1b[0m\n\x1b[32m! cow\x1b[0m\n\x1b[32m+ pig\x1b[0m\n" - ); - } - - #[test] - fn context_lines_take_the_color_of_their_part() { - // Unchanged lines are colored too, whatever their text looks like, - // but not the marker of a missing newline. - let output = "*** left\n--- right\n***************\n*** 1,3 ****\n - ant\n \n! bee\n\ - \\ No newline at end of file\n--- 1,3 ----\n - ant\n \n! fly\n"; - assert_eq!( - colorize_str(output, Format::Context), - "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ - \x1b[36m*** 1,3 ****\x1b[0m\n\x1b[31m - ant\x1b[0m\n\x1b[31m \x1b[0m\n\ - \x1b[31m! bee\x1b[0m\n\\ No newline at end of file\n\ - \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m - ant\x1b[0m\n\x1b[32m \x1b[0m\n\ - \x1b[32m! fly\x1b[0m\n" - ); - } - - #[test] - fn context_lines_without_blank_after_the_marker() { - let output = "*** left\n--- right\n***************\n*** 1,3 ****\n-\n\n! bee\n\ - --- 1,3 ----\n\n! fly\n!\n+\n"; - assert_eq!( - colorize_str(output, Format::Context), - "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ - \x1b[36m*** 1,3 ****\x1b[0m\n\x1b[31m-\x1b[0m\n\x1b[31m\x1b[0m\n\ - \x1b[31m! bee\x1b[0m\n\ - \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m\x1b[0m\n\x1b[32m! fly\x1b[0m\n\ - \x1b[32m!\x1b[0m\n\x1b[32m+\x1b[0m\n" - ); - } - - #[test] - fn missing_newline_marker_is_plain() { - assert_eq!( - colorize_str("1c1\n< ant\n---\n> bee\n\\ No newline at end of file\n", Format::Normal), - "\x1b[36m1c1\x1b[0m\n\x1b[31m< ant\x1b[0m\n---\n\x1b[32m> bee\x1b[0m\n\\ No newline at end of file\n" - ); + use rstest::rstest; + + #[rstest] + #[case::normal( + Format::Normal, + "3,4c3\n< owl\n< elk\n---\n> yak\n", + "\x1b[36m3,4c3\x1b[0m\n\x1b[31m< owl\x1b[0m\n\x1b[31m< elk\x1b[0m\n---\n\x1b[32m> yak\x1b[0m\n" + )] + // The deleted text looks like a header line, but only the first two + // lines are headers. + #[case::unified( + Format::Unified, + "--- left\n+++ right\n@@ -2 +2 @@\n--- not a header\n+++ nor this\n", + "\x1b[1m--- left\x1b[0m\n\x1b[1m+++ right\x1b[0m\n\x1b[36m@@ -2 +2 @@\x1b[0m\n\ + \x1b[31m--- not a header\x1b[0m\n\x1b[32m+++ nor this\x1b[0m\n" + )] + #[case::context( + Format::Context, + "*** left\n--- right\n***************\n*** 1,2 ****\n cat\n! dog\n\ + --- 1,3 ----\n cat\n! cow\n+ pig\n", + "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ + \x1b[36m*** 1,2 ****\x1b[0m\n\x1b[31m cat\x1b[0m\n\x1b[31m! dog\x1b[0m\n\ + \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m cat\x1b[0m\n\x1b[32m! cow\x1b[0m\n\x1b[32m+ pig\x1b[0m\n" + )] + // Unchanged lines are colored too, whatever their text looks like, + // but not the marker of a missing newline. + #[case::context_lines_take_the_color_of_their_part( + Format::Context, + "*** left\n--- right\n***************\n*** 1,3 ****\n - ant\n \n! bee\n\ + \\ No newline at end of file\n--- 1,3 ----\n - ant\n \n! fly\n", + "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ + \x1b[36m*** 1,3 ****\x1b[0m\n\x1b[31m - ant\x1b[0m\n\x1b[31m \x1b[0m\n\ + \x1b[31m! bee\x1b[0m\n\\ No newline at end of file\n\ + \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m - ant\x1b[0m\n\x1b[32m \x1b[0m\n\ + \x1b[32m! fly\x1b[0m\n" + )] + #[case::context_lines_without_blank_after_the_marker( + Format::Context, + "*** left\n--- right\n***************\n*** 1,3 ****\n-\n\n! bee\n\ + --- 1,3 ----\n\n! fly\n!\n+\n", + "\x1b[1m*** left\x1b[0m\n\x1b[1m--- right\x1b[0m\n***************\n\ + \x1b[36m*** 1,3 ****\x1b[0m\n\x1b[31m-\x1b[0m\n\x1b[31m\x1b[0m\n\ + \x1b[31m! bee\x1b[0m\n\ + \x1b[36m--- 1,3 ----\x1b[0m\n\x1b[32m\x1b[0m\n\x1b[32m! fly\x1b[0m\n\ + \x1b[32m!\x1b[0m\n\x1b[32m+\x1b[0m\n" + )] + #[case::missing_newline_marker_is_plain( + Format::Normal, + "1c1\n< ant\n---\n> bee\n\\ No newline at end of file\n", + "\x1b[36m1c1\x1b[0m\n\x1b[31m< ant\x1b[0m\n---\n\x1b[32m> bee\x1b[0m\n\\ No newline at end of file\n" + )] + fn colorize_output(#[case] format: Format, #[case] output: &str, #[case] expected: &str) { + let colored = colorize(output.as_bytes(), format, &Palette::default()); + assert_eq!(String::from_utf8(colored).unwrap(), expected); } #[test] @@ -252,10 +233,12 @@ mod tests { assert_eq!(palette.added, "1;34"); assert_eq!(palette.line_numbers, "35"); assert_eq!(palette.deleted, Palette::default().deleted); - assert_eq!(Palette::parse("ad"), Err(PaletteError::Unparsable)); - assert_eq!( - Palette::parse("xx=1"), - Err(PaletteError::UnrecognizedPrefix("xx".to_string())) - ); + } + + #[rstest] + #[case::missing_value("ad", PaletteError::Unparsable)] + #[case::unknown_prefix("xx=1", PaletteError::UnrecognizedPrefix("xx".to_string()))] + fn palette_errors(#[case] spec: &str, #[case] error: PaletteError) { + assert_eq!(Palette::parse(spec), Err(error)); } } diff --git a/src/context_diff.rs b/src/context_diff.rs index ff303428..f02bcdd8 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -473,6 +473,7 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { mod tests { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; use crate::utils::testcmds::PATCH_CMD; @@ -819,26 +820,11 @@ mod tests { } } - #[test] - fn test_stop_early() { - use crate::assert_diff_eq; - - let from_filename = "foo"; - let from = ["a", "b", "c", ""].join("\n"); - let to_filename = "bar"; - let to = ["a", "d", "c", ""].join("\n"); - - let diff_full = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - ..Default::default() - }, - ); - - let expected_full = [ + #[rstest] + #[case::full( + false, + "a\nd\nc\n", + &[ "*** foo\tTIMESTAMP", "--- bar\tTIMESTAMP", "***************", @@ -852,64 +838,30 @@ mod tests { " c", "", ] - .join("\n"); - assert_diff_eq!(diff_full, expected_full); - - let diff_brief = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - brief: true, - ..Default::default() - }, - ); - - let expected_brief = ["*** foo\tTIMESTAMP", "--- bar\tTIMESTAMP", ""].join("\n"); - assert_diff_eq!(diff_brief, expected_brief); - - let nodiff_full = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - ..Default::default() - }, - ); - assert!(nodiff_full.is_empty()); - - let nodiff_brief = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - brief: true, - ..Default::default() - }, - ); - assert!(nodiff_brief.is_empty()); - } - - #[test] - fn test_change_block_lines_all_changed() { + )] + #[case::brief(true, "a\nd\nc\n", &["*** foo\tTIMESTAMP", "--- bar\tTIMESTAMP", ""])] + #[case::full_identical(false, "a\nb\nc\n", &[])] + #[case::brief_identical(true, "a\nb\nc\n", &[])] + fn test_stop_early(#[case] brief: bool, #[case] to: &str, #[case] expected: &[&str]) { use crate::assert_diff_eq; let params = Params { from: "foo".into(), to: "bar".into(), + brief, ..Default::default() }; + let output = diff(b"a\nb\nc\n", to.as_bytes(), ¶ms); + assert_diff_eq!(output, expected.join("\n")); + } - // Two lines replaced by one: both old lines are changed, not one deleted. - let from = ["a", "b", "c", "d", ""].join("\n"); - let to = ["a", "x", "d", ""].join("\n"); - let expected = [ - "*** foo\tTIMESTAMP", - "--- bar\tTIMESTAMP", - "***************", + #[rstest] + // Two lines replaced by one: both old lines are changed, not one deleted. + #[case::two_lines_replaced_by_one( + "a\nb\nc\nd\n", + "a\nx\nd\n", + 3, + &[ "*** 1,4 ****", " a", "! b", @@ -919,52 +871,21 @@ mod tests { " a", "! x", " d", - "", ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - - // One line replaced by three: all three new lines are changed. - let from = ["a", "b", ""].join("\n"); - let to = ["a", "x", "y", "z", ""].join("\n"); - let expected = [ - "*** foo\tTIMESTAMP", - "--- bar\tTIMESTAMP", - "***************", - "*** 1,2 ****", - " a", - "! b", - "--- 1,4 ----", - " a", - "! x", - "! y", - "! z", - "", - ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - } - - #[test] - fn test_hunk_merging() { - use crate::assert_diff_eq; - - let params = Params { - from: "foo".into(), - to: "bar".into(), - context_count: 1, - ..Default::default() - }; - - // Changes separated by up to twice the context size share one hunk. - let from = ["a", "b", "c", "d", "e", "f", ""].join("\n"); - let to = ["a", "B", "c", "d", "E", "f", ""].join("\n"); - let expected = [ - "*** foo\tTIMESTAMP", - "--- bar\tTIMESTAMP", - "***************", + )] + // One line replaced by three: all three new lines are changed. + #[case::one_line_replaced_by_three( + "a\nb\n", + "a\nx\ny\nz\n", + 3, + &["*** 1,2 ****", " a", "! b", "--- 1,4 ----", " a", "! x", "! y", "! z"] + )] + // Changes separated by up to twice the context size share one hunk. + #[case::changes_share_hunk( + "a\nb\nc\nd\ne\nf\n", + "a\nB\nc\nd\nE\nf\n", + 1, + &[ "*** 1,6 ****", " a", "! b", @@ -979,19 +900,14 @@ mod tests { " d", "! E", " f", - "", ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - - // One more unchanged line between them splits the hunk. - let from = ["a", "b", "c", "d", "e", "f", "g", ""].join("\n"); - let to = ["a", "B", "c", "d", "e", "F", "g", ""].join("\n"); - let expected = [ - "*** foo\tTIMESTAMP", - "--- bar\tTIMESTAMP", - "***************", + )] + // One more unchanged line between them splits the hunk. + #[case::changes_split_hunks( + "a\nb\nc\nd\ne\nf\ng\n", + "a\nB\nc\nd\ne\nF\ng\n", + 1, + &[ "*** 1,3 ****", " a", "! b", @@ -1009,20 +925,15 @@ mod tests { " e", "! F", " g", - "", ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - - // An insertion before a nearby change gives the two sides different - // line counts; the hunks must still be merged (issue #268). - let from = ["milk", "eggs", "bread", "butter", "apples", ""].join("\n"); - let to = ["milk", "eggs", "yogurt", "bread", "honey", "apples", ""].join("\n"); - let expected = [ - "*** foo\tTIMESTAMP", - "--- bar\tTIMESTAMP", - "***************", + )] + // An insertion before a nearby change gives the two sides different + // line counts; the hunks must still be merged (issue #268). + #[case::insertion_before_change( + "milk\neggs\nbread\nbutter\napples\n", + "milk\neggs\nyogurt\nbread\nhoney\napples\n", + 1, + &[ "*** 2,5 ****", " eggs", " bread", @@ -1034,9 +945,26 @@ mod tests { " bread", "! honey", " apples", - "", ] - .join("\n"); + )] + fn test_hunks( + #[case] from: &str, + #[case] to: &str, + #[case] context_count: usize, + #[case] hunks: &[&str], + ) { + use crate::assert_diff_eq; + + let params = Params { + from: "foo".into(), + to: "bar".into(), + context_count, + ..Default::default() + }; + let expected = format!( + "*** foo\tTIMESTAMP\n--- bar\tTIMESTAMP\n***************\n{}\n", + hunks.join("\n") + ); let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); assert_diff_eq!(output, expected); } diff --git a/src/dir_diff.rs b/src/dir_diff.rs index 5eca727c..833f47c6 100644 --- a/src/dir_diff.rs +++ b/src/dir_diff.rs @@ -435,69 +435,64 @@ fn file_kind(metadata: &Metadata) -> &'static str { #[cfg(test)] mod tests { use super::*; + use rstest::rstest; - #[test] - fn entries_are_paired_by_name() { - let names = - |names: &[&str]| -> Vec { names.iter().map(OsString::from).collect() }; - let (from, to) = (names(&["b", "d", "e", "x"]), names(&["a", "d", "x", "z"])); - let entries = pair_entries(&from, &to, |a, b| a.cmp(b)); - let name = OsStr::new; - assert_eq!( - entries, - [ - Entry::ToOnly(name("a")), - Entry::FromOnly(name("b")), - Entry::Both(name("d"), name("d")), - Entry::FromOnly(name("e")), - Entry::Both(name("x"), name("x")), - Entry::ToOnly(name("z")), - ] - ); - assert_eq!(pair_entries(&[], &[], |a, b| a.cmp(b)), []); + fn names(names: &[&str]) -> Vec { + names.iter().map(OsString::from).collect() } - #[test] - fn names_equal_by_order_pair_exact_matches_first() { - let names = - |names: &[&str]| -> Vec { names.iter().map(OsString::from).collect() }; - let ignoring_case = |a: &OsStr, b: &OsStr| { - let lowercase = |name: &OsStr| name.as_encoded_bytes().to_ascii_lowercase(); - lowercase(a).cmp(&lowercase(b)) - }; - let name = OsStr::new; + fn ignoring_case(a: &OsStr, b: &OsStr) -> Ordering { + let lowercase = |name: &OsStr| name.as_encoded_bytes().to_ascii_lowercase(); + lowercase(a).cmp(&lowercase(b)) + } + + /// Pairs the names and writes each entry as `from=to`, `-from` or `+to`. + fn paired( + from: &[&str], + to: &[&str], + order: impl Fn(&OsStr, &OsStr) -> Ordering, + ) -> Vec { + let (from, to) = (names(from), names(to)); + pair_entries(&from, &to, order) + .into_iter() + .map(|entry| match entry { + Entry::Both(a, b) => format!("{}={}", a.display(), b.display()), + Entry::FromOnly(a) => format!("-{}", a.display()), + Entry::ToOnly(b) => format!("+{}", b.display()), + }) + .collect() + } - let (from, to) = (names(&["f", "x"]), names(&["F", "f", "y"])); - assert_eq!( - pair_entries(&from, &to, ignoring_case), - [ - Entry::Both(name("f"), name("f")), - Entry::ToOnly(name("F")), - Entry::FromOnly(name("x")), - Entry::ToOnly(name("y")), - ] - ); + #[rstest] + #[case::interleaved( + &["b", "d", "e", "x"], + &["a", "d", "x", "z"], + &["+a", "-b", "d=d", "-e", "x=x", "+z"] + )] + #[case::empty(&[], &[], &[])] + fn entries_are_paired_by_name( + #[case] from: &[&str], + #[case] to: &[&str], + #[case] expected: &[&str], + ) { + assert_eq!(paired(from, to, |a, b| a.cmp(b)), expected); + } - // What has no exact match pairs in order; the rest is unpaired, and - // comes after the pairs. - let (from, to) = (names(&["Ab", "aB"]), names(&["AB", "aB", "ab"])); - assert_eq!( - pair_entries(&from, &to, ignoring_case), - [ - Entry::Both(name("Ab"), name("AB")), - Entry::Both(name("aB"), name("aB")), - Entry::ToOnly(name("ab")), - ] - ); - let (from, to) = (names(&["AB", "Ab", "aB", "ab"]), names(&["ab"])); - assert_eq!( - pair_entries(&from, &to, ignoring_case), - [ - Entry::Both(name("ab"), name("ab")), - Entry::FromOnly(name("AB")), - Entry::FromOnly(name("Ab")), - Entry::FromOnly(name("aB")), - ] - ); + #[rstest] + #[case::exact_match_first(&["f", "x"], &["F", "f", "y"], &["f=f", "+F", "-x", "+y"])] + // What has no exact match pairs in order; the rest is unpaired, and + // comes after the pairs. + #[case::unpaired_after_pairs(&["Ab", "aB"], &["AB", "aB", "ab"], &["Ab=AB", "aB=aB", "+ab"])] + #[case::unpaired_from_side( + &["AB", "Ab", "aB", "ab"], + &["ab"], + &["ab=ab", "-AB", "-Ab", "-aB"] + )] + fn names_equal_by_order_pair_exact_matches_first( + #[case] from: &[&str], + #[case] to: &[&str], + #[case] expected: &[&str], + ) { + assert_eq!(paired(from, to, ignoring_case), expected); } } diff --git a/src/ed_diff.rs b/src/ed_diff.rs index 3ec43325..6cc8ae69 100644 --- a/src/ed_diff.rs +++ b/src/ed_diff.rs @@ -157,6 +157,7 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { mod tests { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; use crate::utils::testcmds::ED_CMD; @@ -166,19 +167,11 @@ mod tests { output } - #[test] - fn test_basic() { - let from = b"a\n"; - let to = b"b\n"; - let diff = diff(from, to, &Params::default()); - let expected = ["1c", "b", ".", ""].join("\n"); - assert_eq!(diff, expected.as_bytes()); - } - - #[test] - fn test_single_line_deleted() { - let diff = diff(b"a\nb\n", b"a\n", &Params::default()); - assert_eq!(diff, b"2d\n"); + #[rstest] + #[case::changed_line(b"a\n", b"b\n", b"1c\nb\n.\n")] + #[case::single_line_deleted(b"a\nb\n", b"a\n", b"2d\n")] + fn test_basic(#[case] from: &[u8], #[case] to: &[u8], #[case] expected: &[u8]) { + assert_eq!(diff(from, to, &Params::default()), expected); } #[test] @@ -415,37 +408,19 @@ mod tests { } } - #[test] - fn test_stop_early() { - let from = ["a", "b", "c", ""].join("\n"); - let to = ["a", "d", "c", ""].join("\n"); - - let diff_full = diff(from.as_bytes(), to.as_bytes(), &Params::default()); - let expected_full = ["2c", "d", ".", ""].join("\n"); - assert_eq!(diff_full, expected_full.as_bytes()); - - let diff_brief = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - brief: true, - ..Default::default() - }, - ); - let expected_brief = "\0".as_bytes(); - assert_eq!(diff_brief, expected_brief); - - let nodiff_full = diff(from.as_bytes(), from.as_bytes(), &Params::default()); - assert!(nodiff_full.is_empty()); - - let nodiff_brief = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - brief: true, - ..Default::default() - }, + #[rstest] + #[case::full(false, "a\nd\nc\n", "2c\nd\n.\n")] + #[case::brief(true, "a\nd\nc\n", "\0")] + #[case::full_identical(false, "a\nb\nc\n", "")] + #[case::brief_identical(true, "a\nb\nc\n", "")] + fn test_stop_early(#[case] brief: bool, #[case] to: &str, #[case] expected: &str) { + let params = Params { + brief, + ..Default::default() + }; + assert_eq!( + diff(b"a\nb\nc\n", to.as_bytes(), ¶ms), + expected.as_bytes() ); - assert!(nodiff_brief.is_empty()); } } diff --git a/src/normal_diff.rs b/src/normal_diff.rs index e97b5d48..c5ee5db2 100644 --- a/src/normal_diff.rs +++ b/src/normal_diff.rs @@ -241,27 +241,17 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { mod tests { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; use crate::utils::testcmds::PATCH_CMD; - #[test] - fn test_basic() { - let mut a = Vec::new(); - a.write_all(b"a\n").unwrap(); - let mut b = Vec::new(); - b.write_all(b"b\n").unwrap(); - let diff = diff(&a, &b, &Params::default()); - let expected = b"1c1\n< a\n---\n> b\n".to_vec(); - assert_eq!(diff, expected); - } - - #[test] - fn test_single_line_added_or_deleted() { - // A one-line range is written as a single number, as for c. - let added = diff(b"a\n", b"a\nb\n", &Params::default()); - assert_eq!(added, b"1a2\n> b\n".to_vec()); - let deleted = diff(b"a\nb\n", b"a\n", &Params::default()); - assert_eq!(deleted, b"2d1\n< b\n".to_vec()); + #[rstest] + #[case::changed_line(b"a\n", b"b\n", b"1c1\n< a\n---\n> b\n")] + // A one-line range is written as a single number, as for c. + #[case::single_line_added(b"a\n", b"a\nb\n", b"1a2\n> b\n")] + #[case::single_line_deleted(b"a\nb\n", b"a\n", b"2d1\n< b\n")] + fn test_basic(#[case] from: &[u8], #[case] to: &[u8], #[case] expected: &[u8]) { + assert_eq!(diff(from, to, &Params::default()), expected); } #[test] @@ -586,37 +576,19 @@ mod tests { } } - #[test] - fn test_stop_early() { - let from = ["a", "b", "c"].join("\n"); - let to = ["a", "d", "c"].join("\n"); - - let diff_full = diff(from.as_bytes(), to.as_bytes(), &Params::default()); - let expected_full = ["2c2", "< b", "---", "> d", ""].join("\n"); - assert_eq!(diff_full, expected_full.as_bytes()); - - let diff_brief = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - brief: true, - ..Default::default() - }, - ); - let expected_brief = "\0".as_bytes(); - assert_eq!(diff_brief, expected_brief); - - let nodiff_full = diff(from.as_bytes(), from.as_bytes(), &Params::default()); - assert!(nodiff_full.is_empty()); - - let nodiff_brief = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - brief: true, - ..Default::default() - }, + #[rstest] + #[case::full(false, "a\nd\nc", "2c2\n< b\n---\n> d\n")] + #[case::brief(true, "a\nd\nc", "\0")] + #[case::full_identical(false, "a\nb\nc", "")] + #[case::brief_identical(true, "a\nb\nc", "")] + fn test_stop_early(#[case] brief: bool, #[case] to: &str, #[case] expected: &str) { + let params = Params { + brief, + ..Default::default() + }; + assert_eq!( + diff(b"a\nb\nc", to.as_bytes(), ¶ms), + expected.as_bytes() ); - assert!(nodiff_brief.is_empty()); } } diff --git a/src/params.rs b/src/params.rs index f26c7149..84d2c7a5 100644 --- a/src/params.rs +++ b/src/params.rs @@ -613,6 +613,7 @@ fn match_unified_diff_params( #[cfg(test)] mod tests { use super::*; + use rstest::rstest; fn parse_params>(opts: Peekable) -> Result { super::parse_params(opts).map(|(params, _)| params) @@ -620,640 +621,238 @@ mod tests { fn os(s: &str) -> OsString { OsString::from(s) } - #[test] - fn basics() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("--normal"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - } - #[test] - fn basics_ed() { - for arg in ["-e", "--ed"] { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Ed, - ..Default::default() - }), - parse_params( - [os("diff"), os(arg), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - } - } - #[test] - fn context_valid() { - for args in [vec!["-c"], vec!["--context"], vec!["--context="]] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Context, - ..Default::default() - }), - parse_params(params.iter().map(|x| os(x)).peekable()) - ); - } - for args in [ - vec!["-c42"], - vec!["-C42"], - vec!["-C", "42"], - vec!["--context=42"], - vec!["-42c"], - ] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Context, - context_count: 42, - ..Default::default() - }), - parse_params(params.iter().map(|x| os(x)).peekable()) - ); - } - } - #[test] - fn context_invalid() { - for args in [ - vec!["-c", "42"], - vec!["-c=42"], - vec!["-c="], - vec!["-C"], - vec!["-C=42"], - vec!["-C="], - vec!["--context42"], - vec!["--context", "42"], - vec!["-42C"], - ] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert!(parse_params(params.iter().map(|x| os(x)).peekable()).is_err()); - } - } - #[test] - fn unified_valid() { - for args in [vec!["-u"], vec!["--unified"], vec!["--unified="]] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Unified, - ..Default::default() - }), - parse_params(params.iter().map(|x| os(x)).peekable()) - ); - } - for args in [ - vec!["-u42"], - vec!["-U42"], - vec!["-U", "42"], - vec!["--unified=42"], - vec!["-42u"], - ] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Unified, - context_count: 42, - ..Default::default() - }), - parse_params(params.iter().map(|x| os(x)).peekable()) - ); - } - } - #[test] - fn unified_invalid() { - for args in [ - vec!["-u", "42"], - vec!["-u=42"], - vec!["-u="], - vec!["-U"], - vec!["-U=42"], - vec!["-U="], - vec!["--unified42"], - vec!["--unified", "42"], - vec!["-42U"], - ] { - let mut params = vec!["diff"]; - params.extend(args); - params.extend(["foo", "bar"]); - assert!(parse_params(params.iter().map(|x| os(x)).peekable()).is_err()); - } - } - #[test] - fn context_count() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Unified, - context_count: 54, - ..Default::default() - }), - parse_params( - [os("diff"), os("-u54"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Unified, - context_count: 54, - ..Default::default() - }), - parse_params( - [os("diff"), os("-U54"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Unified, - context_count: 54, - ..Default::default() - }), - parse_params( - [os("diff"), os("-U"), os("54"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - format: Format::Context, - context_count: 54, - ..Default::default() - }), - parse_params( - [os("diff"), os("-c54"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - } - #[test] - fn report_identical_files() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - report_identical_files: true, - ..Default::default() - }), - parse_params( - [os("diff"), os("-s"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - report_identical_files: true, - ..Default::default() - }), - parse_params( - [ - os("diff"), - os("--report-identical-files"), - os("foo"), - os("bar"), - ] - .iter() - .cloned() - .peekable() - ) - ); - } - #[test] - fn brief() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - brief: true, - ..Default::default() - }), - parse_params( - [os("diff"), os("-q"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - brief: true, - ..Default::default() - }), - parse_params( - [os("diff"), os("--brief"), os("foo"), os("bar"),] - .iter() - .cloned() - .peekable() - ) - ); - } - #[test] - fn text() { - for option in ["-a", "--text"] { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("old.bin"), - to: os("new.bin"), - text: true, - ..Default::default() - }), - parse_params( - [os("diff"), os(option), os("old.bin"), os("new.bin")] - .iter() - .cloned() - .peekable() - ) - ); - } - } - #[test] - fn expand_tabs() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - for option in ["-t", "--expand-tabs"] { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - expand_tabs: true, - ..Default::default() - }), - parse_params( - [os("diff"), os(option), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - } - } - #[test] - fn ignore_tab_expansion() { - for option in ["-E", "--ignore-tab-expansion"] { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ignore_tab_expansion: true, - ..Default::default() - }), - parse_params( - [os("diff"), os(option), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - } - } - #[test] - fn tabsize() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - ..Default::default() - }), - parse_params( - [os("diff"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - ); - for args in [&["--tabsize", "42"][..], &["--tabsize=42"]] { - let cmd_args = std::iter::once("diff") + fn parse(args: &[&str]) -> Result { + parse_params( + std::iter::once("diff") .chain(args.iter().copied()) - .chain(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - tabsize: 42, - ..Default::default() - }), - parse_params(cmd_args.map(os).peekable()) - ); - } - assert_eq!( - Err("option '--tabsize' requires an argument".to_string()), - parse_params( - [os("diff"), os("foo"), os("bar"), os("--tabsize")] - .iter() - .cloned() - .peekable() - ) - ); - assert!(parse_params( - [os("diff"), os("--tabsize"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [os("diff"), os("--tabsize="), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [os("diff"), os("--tabsize=r2"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [os("diff"), os("--tabsize=-1"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [os("diff"), os("--tabsize=r2"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [ - os("diff"), - os("--tabsize=92233720368547758088"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() + .map(os) + .peekable(), ) - .is_err()); - for too_large in [(MAX_TABSIZE + 1).to_string(), usize::MAX.to_string()] { - assert_eq!( - Err(format!("invalid tabsize Β«{too_large}Β»")), - parse_params( - [ - os("diff"), - os(&format!("--tabsize={too_large}")), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); - } - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - tabsize: MAX_TABSIZE, - ..Default::default() - }), - parse_params( - [ - os("diff"), - os(&format!("--tabsize={MAX_TABSIZE}")), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); } - #[test] - fn width() { - for args in [ - &["-W", "100"][..], - &["-W100"], - &["--width", "100"], - &["--width=100"], - ] { - let cmd_args = std::iter::once("diff") - .chain(args.iter().copied()) - .chain(["foo", "bar"]); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - width: 100, - ..Default::default() - }), - parse_params(cmd_args.map(os).peekable()) - ); - } - for (args, error) in [ - (&["-W"][..], "option '-W' requires an argument"), - (&["--width"], "option '--width' requires an argument"), - (&["-W", "0"], "invalid width Β«0Β»"), - (&["-W0"], "invalid width Β«0Β»"), - (&["--width=0"], "invalid width Β«0Β»"), - (&["--width", "0"], "invalid width Β«0Β»"), - (&["-W", "abc"], "invalid width Β«abcΒ»"), - (&["--width=abc"], "invalid width Β«abcΒ»"), - ] { - let cmd_args = std::iter::once("diff") - .chain(["foo", "bar"]) - .chain(args.iter().copied()); - assert_eq!( - Err(error.to_string()), - parse_params(cmd_args.map(os).peekable()) - ); - } + fn operands(from: &str, to: &str) -> Params { + Params { + executable: os("diff"), + from: os(from), + to: os(to), + ..Default::default() + } + } + fn foo_bar() -> Params { + operands("foo", "bar") + } + + #[rstest] + #[case::basics(&["foo", "bar"], foo_bar())] + #[case::normal(&["--normal", "foo", "bar"], foo_bar())] + #[case::ed_short(&["-e", "foo", "bar"], Params { format: Format::Ed, ..foo_bar() })] + #[case::ed_long(&["--ed", "foo", "bar"], Params { format: Format::Ed, ..foo_bar() })] + #[case::context_short(&["-c", "foo", "bar"], Params { format: Format::Context, ..foo_bar() })] + #[case::context_long(&["--context", "foo", "bar"], Params { format: Format::Context, ..foo_bar() })] + #[case::context_long_empty(&["--context=", "foo", "bar"], Params { format: Format::Context, ..foo_bar() })] + #[case::context_attached( + &["-c42", "foo", "bar"], + Params { format: Format::Context, context_count: 42, ..foo_bar() }, + )] + #[case::context_upper_attached( + &["-C42", "foo", "bar"], + Params { format: Format::Context, context_count: 42, ..foo_bar() }, + )] + #[case::context_upper_separate( + &["-C", "42", "foo", "bar"], + Params { format: Format::Context, context_count: 42, ..foo_bar() }, + )] + #[case::context_long_count( + &["--context=42", "foo", "bar"], + Params { format: Format::Context, context_count: 42, ..foo_bar() }, + )] + #[case::context_count_prefix( + &["-42c", "foo", "bar"], + Params { format: Format::Context, context_count: 42, ..foo_bar() }, + )] + #[case::context_count_54( + &["-c54", "foo", "bar"], + Params { format: Format::Context, context_count: 54, ..foo_bar() }, + )] + #[case::unified_short(&["-u", "foo", "bar"], Params { format: Format::Unified, ..foo_bar() })] + #[case::unified_long(&["--unified", "foo", "bar"], Params { format: Format::Unified, ..foo_bar() })] + #[case::unified_long_empty(&["--unified=", "foo", "bar"], Params { format: Format::Unified, ..foo_bar() })] + #[case::unified_attached( + &["-u42", "foo", "bar"], + Params { format: Format::Unified, context_count: 42, ..foo_bar() }, + )] + #[case::unified_upper_attached( + &["-U42", "foo", "bar"], + Params { format: Format::Unified, context_count: 42, ..foo_bar() }, + )] + #[case::unified_upper_separate( + &["-U", "42", "foo", "bar"], + Params { format: Format::Unified, context_count: 42, ..foo_bar() }, + )] + #[case::unified_long_count( + &["--unified=42", "foo", "bar"], + Params { format: Format::Unified, context_count: 42, ..foo_bar() }, + )] + #[case::unified_count_prefix( + &["-42u", "foo", "bar"], + Params { format: Format::Unified, context_count: 42, ..foo_bar() }, + )] + #[case::unified_count_54( + &["-u54", "foo", "bar"], + Params { format: Format::Unified, context_count: 54, ..foo_bar() }, + )] + #[case::unified_upper_count_54( + &["-U54", "foo", "bar"], + Params { format: Format::Unified, context_count: 54, ..foo_bar() }, + )] + #[case::unified_upper_separate_count_54( + &["-U", "54", "foo", "bar"], + Params { format: Format::Unified, context_count: 54, ..foo_bar() }, + )] + #[case::report_identical_files_short( + &["-s", "foo", "bar"], + Params { report_identical_files: true, ..foo_bar() }, + )] + #[case::report_identical_files_long( + &["--report-identical-files", "foo", "bar"], + Params { report_identical_files: true, ..foo_bar() }, + )] + #[case::brief_short(&["-q", "foo", "bar"], Params { brief: true, ..foo_bar() })] + #[case::brief_long(&["--brief", "foo", "bar"], Params { brief: true, ..foo_bar() })] + #[case::text_short(&["-a", "old.bin", "new.bin"], Params { text: true, ..operands("old.bin", "new.bin") })] + #[case::text_long(&["--text", "old.bin", "new.bin"], Params { text: true, ..operands("old.bin", "new.bin") })] + #[case::expand_tabs_short(&["-t", "foo", "bar"], Params { expand_tabs: true, ..foo_bar() })] + #[case::expand_tabs_long(&["--expand-tabs", "foo", "bar"], Params { expand_tabs: true, ..foo_bar() })] + #[case::ignore_tab_expansion_short(&["-E", "foo", "bar"], Params { ignore_tab_expansion: true, ..foo_bar() })] + #[case::ignore_tab_expansion_long( + &["--ignore-tab-expansion", "foo", "bar"], + Params { ignore_tab_expansion: true, ..foo_bar() }, + )] + #[case::tabsize_separate(&["--tabsize", "42", "foo", "bar"], Params { tabsize: 42, ..foo_bar() })] + #[case::tabsize_equals(&["--tabsize=42", "foo", "bar"], Params { tabsize: 42, ..foo_bar() })] + #[case::width_short_separate(&["-W", "100", "foo", "bar"], Params { width: 100, ..foo_bar() })] + #[case::width_short_attached(&["-W100", "foo", "bar"], Params { width: 100, ..foo_bar() })] + #[case::width_long_separate(&["--width", "100", "foo", "bar"], Params { width: 100, ..foo_bar() })] + #[case::width_long_equals(&["--width=100", "foo", "bar"], Params { width: 100, ..foo_bar() })] + #[case::width_suffix_is_an_operand(&["xyz--width=5", "foo"], operands("xyz--width=5", "foo"))] + #[case::labels( + &["--label", "old", "-Lnew", "foo", "bar"], + Params { from_label: Some(os("old")), to_label: Some(os("new")), ..foo_bar() }, + )] + #[case::double_dash(&["--", "-g", "-h"], operands("-g", "-h"))] + #[case::stdin_to(&["foo", "-"], operands("foo", "-"))] + #[case::stdin_from(&["-", "bar"], operands("-", "bar"))] + #[case::stdin_both(&["-", "-"], operands("-", "-"))] + fn valid(#[case] args: &[&str], #[case] expected: Params) { + assert_eq!(parse(args), Ok(expected)); + } + + #[rstest] + #[case::context_separate_count(&["-c", "42", "foo", "bar"])] + #[case::context_equals_count(&["-c=42", "foo", "bar"])] + #[case::context_equals_empty(&["-c=", "foo", "bar"])] + #[case::context_upper_no_count(&["-C", "foo", "bar"])] + #[case::context_upper_equals_count(&["-C=42", "foo", "bar"])] + #[case::context_upper_equals_empty(&["-C=", "foo", "bar"])] + #[case::context_long_attached(&["--context42", "foo", "bar"])] + #[case::context_long_separate(&["--context", "42", "foo", "bar"])] + #[case::context_upper_count_prefix(&["-42C", "foo", "bar"])] + #[case::unified_separate_count(&["-u", "42", "foo", "bar"])] + #[case::unified_equals_count(&["-u=42", "foo", "bar"])] + #[case::unified_equals_empty(&["-u=", "foo", "bar"])] + #[case::unified_upper_no_count(&["-U", "foo", "bar"])] + #[case::unified_upper_equals_count(&["-U=42", "foo", "bar"])] + #[case::unified_upper_equals_empty(&["-U=", "foo", "bar"])] + #[case::unified_long_attached(&["--unified42", "foo", "bar"])] + #[case::unified_long_separate(&["--unified", "42", "foo", "bar"])] + #[case::unified_upper_count_prefix(&["-42U", "foo", "bar"])] + #[case::tabsize_takes_operand(&["--tabsize", "foo", "bar"])] + #[case::tabsize_empty(&["--tabsize=", "foo", "bar"])] + #[case::tabsize_not_a_number(&["--tabsize=r2", "foo", "bar"])] + #[case::tabsize_negative(&["--tabsize=-1", "foo", "bar"])] + #[case::tabsize_overflow(&["--tabsize=92233720368547758088", "foo", "bar"])] + #[case::extra_stdin_operand(&["foo", "bar", "-"])] + #[case::three_stdin_operands(&["-", "-", "-"])] + #[case::no_operand(&[])] + #[case::one_operand(&["foo"])] + #[case::unknown_option(&["-g", "foo", "bar"])] + #[case::unknown_option_one_operand(&["-g", "bar"])] + #[case::unknown_option_alone(&["-g"])] + #[case::conflicting_unified_context(&["-u", "-c", "foo", "bar"])] + #[case::conflicting_unified_ed(&["-u", "-e", "foo", "bar"])] + #[case::conflicting_context_unified(&["-c", "-u", "foo", "bar"])] + #[case::conflicting_context_unified_count(&["-c", "-U42", "foo", "bar"])] + #[case::conflicting_unified_normal(&["-u", "--normal", "foo", "bar"])] + #[case::conflicting_normal_ed(&["--normal", "-e", "foo", "bar"])] + #[case::conflicting_context_normal(&["--context", "--normal", "foo", "bar"])] + #[case::color_unknown_option(&["--colorful", "foo", "bar"])] + #[case::color_empty(&["--color=", "foo", "bar"])] + #[case::color_invalid(&["--color=yes", "foo", "bar"])] + #[case::starting_file_no_argument(&["foo", "bar", "-S"])] + fn invalid(#[case] args: &[&str]) { + assert!(parse(args).is_err()); } + #[test] - fn labels() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("bar"), - from_label: Some(os("old")), - to_label: Some(os("new")), - ..Default::default() - }), - parse_params( - [ - os("diff"), - os("--label"), - os("old"), - os("-Lnew"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) - ); + fn empty() { + assert!(parse_params([].iter().cloned().peekable()).is_err()); + } + + #[rstest] + #[case::tabsize_no_argument(&["foo", "bar", "--tabsize"], "option '--tabsize' requires an argument")] + #[case::width_short_no_argument(&["foo", "bar", "-W"], "option '-W' requires an argument")] + #[case::width_long_no_argument(&["foo", "bar", "--width"], "option '--width' requires an argument")] + #[case::width_short_separate_zero(&["foo", "bar", "-W", "0"], "invalid width Β«0Β»")] + #[case::width_short_attached_zero(&["foo", "bar", "-W0"], "invalid width Β«0Β»")] + #[case::width_long_equals_zero(&["foo", "bar", "--width=0"], "invalid width Β«0Β»")] + #[case::width_long_separate_zero(&["foo", "bar", "--width", "0"], "invalid width Β«0Β»")] + #[case::width_short_not_a_number(&["foo", "bar", "-W", "abc"], "invalid width Β«abcΒ»")] + #[case::width_long_not_a_number(&["foo", "bar", "--width=abc"], "invalid width Β«abcΒ»")] + #[case::too_many_labels( + &["--label=a", "-L", "b", "-Lc", "foo", "bar"], + "too many file label options", + )] + #[case::extra_operand( + &["foo", "bar", "baz"], + "diff: extra operand 'baz'\ndiff: Try 'diff --help' for more information.", + )] + #[case::extra_stdin_operand( + &["-", "-", "-"], + "diff: extra operand '-'\ndiff: Try 'diff --help' for more information.", + )] + #[case::extra_operand_after_double_dash( + &["--", "foo", "bar", "baz"], + "diff: extra operand 'baz'\ndiff: Try 'diff --help' for more information.", + )] + #[case::extra_operand_around_double_dash( + &["foo", "--", "bar", "baz"], + "diff: extra operand 'baz'\ndiff: Try 'diff --help' for more information.", + )] + #[case::function_line_trailing_backslash(&["-F", "oops\\", "foo", "bar"], "'oops\\': Trailing backslash")] + fn error_message(#[case] args: &[&str], #[case] expected: &str) { + assert_eq!(parse(args), Err(expected.to_string())); + } + + #[rstest] + #[case::max_plus_one(MAX_TABSIZE + 1)] + #[case::usize_max(usize::MAX)] + fn tabsize_too_large(#[case] tabsize: usize) { assert_eq!( - Err("too many file label options".to_string()), - parse_params( - [ - os("diff"), - os("--label=a"), - os("-L"), - os("b"), - os("-Lc"), - os("foo"), - os("bar") - ] - .iter() - .cloned() - .peekable() - ) + Err(format!("invalid tabsize Β«{tabsize}Β»")), + parse(&[&format!("--tabsize={tabsize}"), "foo", "bar"]) ); } + #[test] - fn width_suffix_is_an_operand() { + fn tabsize_max() { assert_eq!( Ok(Params { - executable: os("diff"), - from: os("xyz--width=5"), - to: os("foo"), - ..Default::default() + tabsize: MAX_TABSIZE, + ..foo_bar() }), - parse_params( - [os("diff"), os("xyz--width=5"), os("foo")] - .iter() - .cloned() - .peekable() - ) + parse(&[&format!("--tabsize={MAX_TABSIZE}"), "foo", "bar"]) ); } + #[cfg(unix)] #[test] fn width_non_utf8_is_not_an_option() { @@ -1292,255 +891,87 @@ mod tests { assert_eq!(params.from, os("foo")); assert_eq!(params.to, os("bar")); } - #[test] - fn double_dash() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("-g"), - to: os("-h"), - ..Default::default() - }), - parse_params( - [os("diff"), os("--"), os("-g"), os("-h")] - .iter() - .cloned() - .peekable() - ) - ); - } - #[test] - fn default_to_stdin() { - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("foo"), - to: os("-"), - ..Default::default() - }), - parse_params([os("diff"), os("foo"), os("-")].iter().cloned().peekable()) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("-"), - to: os("bar"), - ..Default::default() - }), - parse_params([os("diff"), os("-"), os("bar")].iter().cloned().peekable()) - ); - assert_eq!( - Ok(Params { - executable: os("diff"), - from: os("-"), - to: os("-"), - ..Default::default() - }), - parse_params([os("diff"), os("-"), os("-")].iter().cloned().peekable()) - ); - assert!(parse_params( - [os("diff"), os("foo"), os("bar"), os("-")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!(parse_params( - [os("diff"), os("-"), os("-"), os("-")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - } - #[test] - fn extra_operand_is_an_error() { - for args in [ - &["diff", "foo", "bar", "baz"][..], - &["diff", "-", "-", "-"], - &["diff", "--", "foo", "bar", "baz"], - &["diff", "foo", "--", "bar", "baz"], - ] { - assert_eq!( - parse_params(args.iter().map(|x| os(x)).peekable()).err(), - Some(format!( - "diff: extra operand '{0}'\ndiff: Try 'diff --help' for more information.", - args[args.len() - 1] - )), - "{args:?}" - ); - } - } - #[test] - fn missing_arguments() { - assert!(parse_params([os("diff")].iter().cloned().peekable()).is_err()); - assert!(parse_params([os("diff"), os("foo")].iter().cloned().peekable()).is_err()); - } - #[test] - fn unknown_argument() { - assert!(parse_params( - [os("diff"), os("-g"), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - assert!( - parse_params([os("diff"), os("-g"), os("bar")].iter().cloned().peekable()).is_err() - ); - assert!(parse_params([os("diff"), os("-g")].iter().cloned().peekable()).is_err()); - } - #[test] - fn empty() { - assert!(parse_params([].iter().cloned().peekable()).is_err()); - } - #[test] - fn conflicting_output_styles() { - for (arg1, arg2) in [ - ("-u", "-c"), - ("-u", "-e"), - ("-c", "-u"), - ("-c", "-U42"), - ("-u", "--normal"), - ("--normal", "-e"), - ("--context", "--normal"), - ] { - assert!(parse_params( - [os("diff"), os(arg1), os(arg2), os("foo"), os("bar")] - .iter() - .cloned() - .peekable() - ) - .is_err()); - } - } - - #[test] - fn color_options() { - let parse = |args: &[&str]| { - let args = std::iter::once("diff") - .chain(args.iter().copied()) - .chain(["foo", "bar"]); - parse_params(args.map(os).peekable()) - }; - assert_eq!(parse(&["--color"]).unwrap().color, ColorWhen::Auto); - assert_eq!(parse(&["--color=never"]).unwrap().color, ColorWhen::Never); - let params = parse(&["--palette", "ad=35", "--color=always"]).unwrap(); - assert_eq!(params.color, ColorWhen::Always); - assert_eq!(params.palette.as_deref(), Some("ad=35")); - assert_eq!( - parse(&["--palette=hd=4"]).unwrap().palette.as_deref(), - Some("hd=4") - ); - for option in ["--colorful", "--color=", "--color=yes"] { - assert!(parse(&[option]).is_err(), "{option}"); - } - } - #[test] - fn function_lines() { - let patterns = |patterns: &[&str]| -> Vec { - patterns - .iter() - .map(|pattern| Bre::new(pattern).unwrap()) - .collect() - }; - let parse = |args: &[&str]| { - let args = std::iter::once("diff") + #[rstest] + #[case::auto(&["--color"], ColorWhen::Auto)] + #[case::never(&["--color=never"], ColorWhen::Never)] + #[case::always_after_palette(&["--palette", "ad=35", "--color=always"], ColorWhen::Always)] + fn color(#[case] args: &[&str], #[case] expected: ColorWhen) { + let args = [args, &["foo", "bar"]].concat(); + assert_eq!(parse(&args).unwrap().color, expected); + } + + #[rstest] + #[case::separate(&["--palette", "ad=35", "--color=always"], "ad=35")] + #[case::equals(&["--palette=hd=4"], "hd=4")] + fn palette(#[case] args: &[&str], #[case] expected: &str) { + let args = [args, &["foo", "bar"]].concat(); + assert_eq!(parse(&args).unwrap().palette.as_deref(), Some(expected)); + } + + #[rstest] + #[case::show_c_function(&["-p"], Format::Context, &[C_FUNCTION_PATTERN])] + #[case::show_c_function_unified(&["-u", "-p"], Format::Unified, &[C_FUNCTION_PATTERN])] + #[case::several_patterns( + &["-F", "^fn", "-Fx", "--show-function-line=^#", "-e"], + Format::Ed, + &["^fn", "x", "^#"], + )] + // -F alone selects no output format. + #[case::no_format(&["-F", "^fn"], Format::Normal, &["^fn"])] + fn function_lines(#[case] args: &[&str], #[case] format: Format, #[case] patterns: &[&str]) { + let args = [args, &["foo", "bar"]].concat(); + let params = parse(&args).unwrap(); + assert_eq!(params.format, format); + let patterns: Vec = patterns + .iter() + .map(|pattern| Bre::new(pattern).unwrap()) + .collect(); + assert_eq!(params.function_line_patterns, patterns); + } + + #[rstest] + #[case::between_operands(&["-u", "old", "-r", "new"], &["-u", "-r"])] + // An option argument equal to an operand stays with its option. + #[case::argument_equal_to_operand(&["-F", "new", "old", "new"], &["-F", "new"])] + #[case::double_dash(&["-q", "--", "-old", "new"], &["-q", "--"])] + #[case::after_stdin(&["-", "new", "-t"], &["-t"])] + fn option_arguments(#[case] args: &[&str], #[case] expected: &[&str]) { + let (_, options) = super::parse_params( + std::iter::once("diff") .chain(args.iter().copied()) - .chain(["foo", "bar"]); - parse_params(args.map(os).peekable()) - }; - let params = parse(&["-p"]).unwrap(); - assert_eq!(params.format, Format::Context); - assert_eq!( - params.function_line_patterns, - patterns(&[C_FUNCTION_PATTERN]) - ); - - let params = parse(&["-u", "-p"]).unwrap(); - assert_eq!(params.format, Format::Unified); - - let params = parse(&["-F", "^fn", "-Fx", "--show-function-line=^#", "-e"]).unwrap(); - assert_eq!(params.format, Format::Ed); - assert_eq!(params.function_line_patterns, patterns(&["^fn", "x", "^#"])); - - // -F alone selects no output format. - assert_eq!(parse(&["-F", "^fn"]).unwrap().format, Format::Normal); - + .map(os) + .peekable(), + ) + .unwrap(); assert_eq!( - parse(&["-F", "oops\\"]), - Err("'oops\\': Trailing backslash".to_string()) + options, + expected.iter().copied().map(os).collect::>() ); } - #[test] - fn option_arguments() { - let options = |args: &[&str]| { - let (_, options) = - super::parse_params(args.iter().copied().map(os).peekable()).unwrap(); - options - }; - assert_eq!( - options(&["diff", "-u", "old", "-r", "new"]), - [os("-u"), os("-r")] - ); - // An option argument equal to an operand stays with its option. - assert_eq!( - options(&["diff", "-F", "new", "old", "new"]), - [os("-F"), os("new")] - ); - assert_eq!( - options(&["diff", "-q", "--", "-old", "new"]), - [os("-q"), os("--")] - ); - assert_eq!(options(&["diff", "-", "new", "-t"]), [os("-t")]); + #[rstest] + #[case::short_separate(&["-S", "mid"])] + #[case::short_attached(&["-Smid"])] + #[case::long_equals(&["--starting-file=mid"])] + #[case::long_separate(&["--starting-file", "mid"])] + fn starting_file(#[case] args: &[&str]) { + let args = [args, &["foo", "bar"]].concat(); + let params = parse(&args).unwrap(); + assert_eq!(params.starting_file, Some(os("mid"))); + assert_eq!(params.from, os("foo")); } - #[test] - fn starting_file() { - for args in [ - &["-S", "mid"][..], - &["-Smid"], - &["--starting-file=mid"], - &["--starting-file", "mid"], - ] { - let args = std::iter::once("diff") - .chain(args.iter().copied()) - .chain(["foo", "bar"]); - let params = parse_params(args.map(os).peekable()).unwrap(); - assert_eq!(params.starting_file, Some(os("mid"))); - assert_eq!(params.from, os("foo")); - } - assert!(parse_params( - [os("diff"), os("foo"), os("bar"), os("-S")] - .into_iter() - .peekable() - ) - .is_err()); - } - #[test] - fn ignore_file_name_case() { - // The last of --ignore-file-name-case and --no-ignore-file-name-case - // wins. - for (args, expected) in [ - (&[][..], false), - (&["--ignore-file-name-case"], true), - (&["--no-ignore-file-name-case"], false), - ( - &["--ignore-file-name-case", "--no-ignore-file-name-case"], - false, - ), - ( - &["--no-ignore-file-name-case", "--ignore-file-name-case"], - true, - ), - ] { - let args = std::iter::once("diff") - .chain(args.iter().copied()) - .chain(["foo", "bar"]); - let params = parse_params(args.map(os).peekable()).unwrap(); - assert_eq!(params.ignore_file_name_case, expected); - } + // The last of --ignore-file-name-case and --no-ignore-file-name-case + // wins. + #[rstest] + #[case::default(&[], false)] + #[case::ignore(&["--ignore-file-name-case"], true)] + #[case::no_ignore(&["--no-ignore-file-name-case"], false)] + #[case::ignore_then_no_ignore(&["--ignore-file-name-case", "--no-ignore-file-name-case"], false)] + #[case::no_ignore_then_ignore(&["--no-ignore-file-name-case", "--ignore-file-name-case"], true)] + fn ignore_file_name_case(#[case] args: &[&str], #[case] expected: bool) { + let args = [args, &["foo", "bar"]].concat(); + assert_eq!(parse(&args).unwrap().ignore_file_name_case, expected); } } diff --git a/src/side_diff.rs b/src/side_diff.rs index 5252f1f3..9c0fbe06 100644 --- a/src/side_diff.rs +++ b/src/side_diff.rs @@ -371,101 +371,39 @@ mod tests { const DEF_TAB_SIZE: usize = 4; use super::*; + use rstest::rstest; mod format_tabs_and_spaces { use super::*; - const CONFIG_E_T: Config = Config { - sdiff_half_width: 60, - tab_size: DEF_TAB_SIZE, - expanded: true, - sdiff_column_two_offset: 0, - separator_pos: 0, - }; - - const CONFIG_E_F: Config = Config { - sdiff_half_width: 60, - tab_size: DEF_TAB_SIZE, - expanded: false, - sdiff_column_two_offset: 0, - separator_pos: 0, - }; - - #[test] - fn test_format_tabs_and_spaces_expanded_false() { - let mut buf = vec![]; - format_tabs_and_spaces(0, 5, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b' ']); - } - - #[test] - fn test_format_tabs_and_spaces_expanded_true() { - let mut buf = vec![]; - format_tabs_and_spaces(0, 5, &CONFIG_E_T, &mut buf).unwrap(); - assert_eq!(buf, vec![b' '; 5]); - } - - #[test] - fn test_format_tabs_and_spaces_from_greater_than_to() { - let mut buf = vec![]; - format_tabs_and_spaces(6, 5, &CONFIG_E_F, &mut buf).unwrap(); - assert!(buf.is_empty()); - } - - #[test] - fn test_format_from_non_zero_position() { - let mut buf = vec![]; - format_tabs_and_spaces(2, 7, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b' ', b' ', b' ']); - } - - #[test] - fn test_multiple_full_tabs_needed() { - let mut buf = vec![]; - format_tabs_and_spaces(0, 12, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b'\t', b'\t']); - } - - #[test] - fn test_uneven_tab_boundary_with_spaces() { - let mut buf = vec![]; - format_tabs_and_spaces(3, 10, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b'\t', b' ', b' ']); - } - - #[test] - fn test_expanded_true_with_offset() { - let mut buf = vec![]; - format_tabs_and_spaces(3, 9, &CONFIG_E_T, &mut buf).unwrap(); - assert_eq!(buf, vec![b' '; 6]); - } - - #[test] - fn test_exact_tab_boundary_from_midpoint() { - let mut buf = vec![]; - format_tabs_and_spaces(4, 8, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t']); - } - - #[test] - fn test_mixed_tabs_and_spaces_edge_case() { - let mut buf = vec![]; - format_tabs_and_spaces(5, 9, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b' ']); - } - - #[test] - fn test_minimal_gap_with_tab() { - let mut buf = vec![]; - format_tabs_and_spaces(7, 8, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t']); - } - - #[test] - fn test_expanded_false_with_tab_at_end() { + #[rstest] + #[case::expanded_false(0, 5, false, b"\t ")] + #[case::expanded_true(0, 5, true, b" ")] + #[case::from_greater_than_to(6, 5, false, b"")] + #[case::from_non_zero_position(2, 7, false, b"\t ")] + #[case::multiple_full_tabs_needed(0, 12, false, b"\t\t\t")] + #[case::uneven_tab_boundary_with_spaces(3, 10, false, b"\t\t ")] + #[case::expanded_true_with_offset(3, 9, true, b" ")] + #[case::exact_tab_boundary_from_midpoint(4, 8, false, b"\t")] + #[case::mixed_tabs_and_spaces_edge_case(5, 9, false, b"\t ")] + #[case::minimal_gap_with_tab(7, 8, false, b"\t")] + #[case::expanded_false_with_tab_at_end(6, 8, false, b"\t")] + fn format( + #[case] from: usize, + #[case] to: usize, + #[case] expanded: bool, + #[case] expected: &[u8], + ) { + let config = Config { + sdiff_half_width: 60, + tab_size: DEF_TAB_SIZE, + expanded, + sdiff_column_two_offset: 0, + separator_pos: 0, + }; let mut buf = vec![]; - format_tabs_and_spaces(6, 8, &CONFIG_E_F, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t']); + format_tabs_and_spaces(from, to, &config, &mut buf).unwrap(); + assert_eq!(buf, expected); } } @@ -482,107 +420,126 @@ mod tests { } } - #[test] - fn test_empty_line_left_expanded_false() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - process_half_line(b"", 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf.len(), 5); - assert_eq!(buf, vec![b'\t', b'\t', b' ', b' ', b' ']); - } - - #[test] - fn test_tabs_unexpanded() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - process_half_line(b"\tabc", 8, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b'a', b'b', b'c', b'\t', b' ']); - } - - #[test] - fn test_utf8_multibyte() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = "πŸ˜‰πŸ˜‰πŸ˜‰".as_bytes(); - process_half_line(s, 3, false, false, &config, &mut buf).unwrap(); - let mut r = vec![]; - r.write_all("πŸ˜‰\t".as_bytes()).unwrap(); - assert_eq!(buf, r) - } - - #[test] - fn test_newline_handling() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - process_half_line(b"abc\ndef", 5, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, vec![b'a', b'b', b'c', b'\t', b' ', b' ']); - } - - #[test] - fn test_carriage_return() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - process_half_line(b"\rxyz", 5, true, false, &config, &mut buf).unwrap(); - let mut r = vec![b'\r']; - r.extend(vec![b'\t'; 15]); - r.extend(vec![b'x', b'y', b'z']); - assert_eq!(buf, r); - } - - #[test] - fn test_exact_width_fit() { - let config = create_test_config(true, DEF_TAB_SIZE); + #[rstest] + #[case::empty_line_left_expanded_false(b"", 10, false, false, false, b"\t\t ")] + #[case::tabs_unexpanded(b"\tabc", 8, false, false, false, b"\tabc\t ")] + #[case::utf8_multibyte("πŸ˜‰πŸ˜‰πŸ˜‰".as_bytes(), 3, false, false, false, "πŸ˜‰\t".as_bytes())] + #[case::newline_handling(b"abc\ndef", 5, false, false, false, b"abc\t ")] + #[case::carriage_return( + b"\rxyz", + 5, + true, + false, + false, + &[b"\r".as_slice(), &[b'\t'; 15], b"xyz"].concat() + )] + #[case::exact_width_fit(b"abcd", 4, false, false, true, b"abcd ")] + // ISO-8859-1 + #[case::non_utf8_bytes(b"caf\xE9", 5, false, false, false, b"caf\xE9 ")] + // UTF-32LE, 4 bytes per char: 'c', 'a', 'f', 'Γ©' + #[case::non_utf8_bytes_ignore_padding_bytes( + b"c\0\0\0a\0\0\0f\0\0\0\xE9\0\0\0", + 6, + false, + false, + false, + b"c\0\0\0a\0\0\0f\0\0\0\xE9\0\0\0 " + )] + // GB18030: \xA8\x80 is 'Γ©', the cut breaks its encoding + #[case::non_utf8_non_preserve_ascii_bytes_cut( + b"caf\xA8\x80", + 4, + false, + false, + false, + b"caf\xA8 " + )] + #[case::mixed_tabs_spaces(b"\t \t", 10, false, false, false, b"\t \t ")] + #[case::overflow_multibyte("ζ—₯本θͺž".as_bytes(), 5, false, false, false, "ζ—₯本 ".as_bytes())] + #[case::white_space_gutter(b"abc", 3, false, true, false, b"abc\t ")] + #[case::expanded_true(b"abc", 10, false, false, true, b"abc ")] + #[case::expanded_true_with_gutter(b"abc", 10, false, true, true, b"abc ")] + #[case::width0_chars(b"abc\0\x0B\x07\x0C", 4, false, false, false, b"abc\0\x0B\x07\x0C\t ")] + #[case::left_empty_white_space_gutter(b"", 9, false, true, false, b"\t\t\t")] + #[case::s_size_eq_max_width_p1(b"abcdefghij", 10, false, false, false, b"abcdefghij ")] + #[case::mixed_tabs_and_spaces_inversion(b" \t \t ", 10, false, false, false, b" \t \t ")] + #[case::expanded_with_tabs(b" \t \t ", 10, false, false, true, b" ")] + #[case::expanded_with_tabs_and_space_gutter( + b" \t \t ", + 10, + false, + true, + true, + b" " + )] + #[case::zero_width_unicode_chars( + "\u{200B}".as_bytes(), + 10, + false, + false, + false, + "\u{200B}\t\t ".as_bytes() + )] + #[case::multiple_carriage_returns( + b"\r\r", + 10, + false, + false, + false, + &[b"\r".as_slice(), &[b'\t'; 15], b"\r", &[b'\t'; 17], b" "].concat() + )] + #[case::multiple_carriage_returns_is_right_true( + b"\r\r", + 10, + true, + false, + false, + &[b"\r".as_slice(), &[b'\t'; 15], b"\r", &[b'\t'; 15]].concat() + )] + #[case::mixed_invalid_utf8_with_valid( + b"abc\xFF\xFEdef", + 10, + false, + false, + false, + b"abc\xFF\xFEdef " + )] + #[case::max_width_zero(b"foo bar", 0, false, false, false, b" ")] + #[case::line_only_with_tabs(b"\t\t\t", 10, false, false, false, b"\t\t ")] + #[case::tabs_expanded(b"\t\t\t", 12, false, false, true, &b" ".repeat(13))] + #[case::mixed_tabs(b"a\tb\tc\t", 10, false, false, false, b"a\tb\tc ")] + #[case::mixed_tabs_with_gutter(b"a\tb\tc\t", 10, false, true, false, b"a\tb\tc\t ")] + #[case::mixed_tabs_expanded(b"a\tb\tc\t", 10, false, false, true, b"a b c ")] + #[case::mixed_tabs_expanded_with_gutter( + b"a\tb\tc\t", + 10, + false, + true, + true, + b"a b c " + )] + #[case::break_if_invalid_max_width(b"a\tb\tc\t", 61, false, true, true, b"")] + #[case::new_line(b"abc", 10, false, false, false, b"abc\t\t ")] + fn output( + #[case] line: &[u8], + #[case] max_width: usize, + #[case] is_right: bool, + #[case] white_space_gutter: bool, + #[case] expanded: bool, + #[case] expected: &[u8], + ) { + let config = create_test_config(expanded, DEF_TAB_SIZE); let mut buf = vec![]; - process_half_line(b"abcd", 4, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf.len(), 5); - assert_eq!(buf, b"abcd ".to_vec()); - } - - #[test] - fn test_non_utf8_bytes() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - // ISO-8859-1 process_half_line( - &[0x63, 0x61, 0x66, 0xE9], - 5, - false, - false, + line, + max_width, + is_right, + white_space_gutter, &config, &mut buf, ) .unwrap(); - assert_eq!(&buf, &[0x63, 0x61, 0x66, 0xE9, b' ', b' ']); - assert!(String::from_utf8(buf).is_err()); - } - - #[test] - fn test_non_utf8_bytes_ignore_padding_bytes() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - - let utf32le_bytes = [ - 0x63, 0x00, 0x00, 0x00, // 'c' - 0x61, 0x00, 0x00, 0x00, // 'a' - 0x66, 0x00, 0x00, 0x00, // 'f' - 0xE9, 0x00, 0x00, 0x00, // 'Γ©' - ]; - // utf8 little endiand 32 bits (or 4 bytes per char) - process_half_line(&utf32le_bytes, 6, false, false, &config, &mut buf).unwrap(); - let mut r = utf32le_bytes.to_vec(); - r.extend(vec![b' '; 3]); - assert_eq!(buf, r); - } - - #[test] - fn test_non_utf8_non_preserve_ascii_bytes_cut() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - - let gb18030 = b"\x63\x61\x66\xA8\x80"; // some random chinese encoding - // ^ Γ© char, start multi byte - process_half_line(gb18030, 4, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"\x63\x61\x66\xA8 "); // break the encoding of 'Γ©' letter + assert_eq!(buf, expected); } #[test] @@ -592,233 +549,6 @@ mod tests { process_half_line(b"xyz", 5, true, true, &config, &mut buf).unwrap(); assert_eq!(buf.len(), 3); } - - #[test] - fn test_mixed_tabs_spaces() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - process_half_line(b"\t \t", 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b' ', b' ', b'\t', b' ', b' ', b' ']); - } - - #[test] - fn test_overflow_multibyte() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = "ζ—₯本θͺž".as_bytes(); - process_half_line(s, 5, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, "ζ—₯本 ".as_bytes()); - } - - #[test] - fn test_white_space_gutter() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc"; - process_half_line(s, 3, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abc\t "); - } - - #[test] - fn test_expanded_true() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abc ") - } - - #[test] - fn test_expanded_true_with_gutter() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc"; - process_half_line(s, 10, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abc ") - } - - #[test] - fn test_width0_chars() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc\0\x0B\x07\x0C"; - process_half_line(s, 4, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abc\0\x0B\x07\x0C\t ") - } - - #[test] - fn test_left_empty_white_space_gutter() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b""; - process_half_line(s, 9, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b"\t\t\t"); - } - - #[test] - fn test_s_size_eq_max_width_p1() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abcdefghij"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abcdefghij "); - } - - #[test] - fn test_mixed_tabs_and_spaces_inversion() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b" \t \t "; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b" \t \t "); - } - - #[test] - fn test_expanded_with_tabs() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b" \t \t "; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b" "); - } - - #[test] - fn test_expanded_with_tabs_and_space_gutter() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b" \t \t "; - process_half_line(s, 10, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b" "); - } - - #[test] - fn test_zero_width_unicode_chars() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = "\u{200B}".as_bytes(); - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, "\u{200B}\t\t ".as_bytes()); - } - - #[test] - fn test_multiple_carriage_returns() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"\r\r"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - let mut r = vec![b'\r']; - r.extend(vec![b'\t'; 15]); - r.push(b'\r'); - r.extend(vec![b'\t'; 15]); - r.extend(vec![b'\t'; 2]); - r.extend(vec![b' '; 3]); - assert_eq!(buf, r); - } - - #[test] - fn test_multiple_carriage_returns_is_right_true() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"\r\r"; - process_half_line(s, 10, true, false, &config, &mut buf).unwrap(); - let mut r = vec![b'\r']; - r.extend(vec![b'\t'; 15]); - r.push(b'\r'); - r.extend(vec![b'\t'; 15]); - assert_eq!(buf, r); - } - - #[test] - fn test_mixed_invalid_utf8_with_valid() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc\xFF\xFEdef"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert!(String::from_utf8(s.to_vec()).is_err()); - assert_eq!(buf, b"abc\xFF\xFEdef "); - } - - #[test] - fn test_max_width_zero() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"foo bar"; - process_half_line(s, 0, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, vec![b' ']); - } - - #[test] - fn test_line_only_with_tabs() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"\t\t\t"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, vec![b'\t', b'\t', b' ', b' ', b' ']) - } - - #[test] - fn test_tabs_expanded() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"\t\t\t"; - process_half_line(s, 12, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b" ".repeat(13)); - } - - #[test] - fn test_mixed_tabs() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"a\tb\tc\t"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"a\tb\tc "); - } - - #[test] - fn test_mixed_tabs_with_gutter() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"a\tb\tc\t"; - process_half_line(s, 10, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b"a\tb\tc\t "); - } - - #[test] - fn test_mixed_tabs_expanded() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"a\tb\tc\t"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"a b c "); - } - - #[test] - fn test_mixed_tabs_expanded_with_gutter() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"a\tb\tc\t"; - process_half_line(s, 10, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b"a b c "); - } - - #[test] - fn test_break_if_invalid_max_width() { - let config = create_test_config(true, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"a\tb\tc\t"; - process_half_line(s, 61, false, true, &config, &mut buf).unwrap(); - assert_eq!(buf, b""); - assert_eq!(buf.len(), 0); - } - - #[test] - fn test_new_line() { - let config = create_test_config(false, DEF_TAB_SIZE); - let mut buf = vec![]; - let s = b"abc"; - process_half_line(s, 10, false, false, &config, &mut buf).unwrap(); - assert_eq!(buf, b"abc\t\t "); - } } mod push_output { @@ -832,130 +562,68 @@ mod tests { } } - fn create_test_config_def() -> Config { - Config::default() - } - - #[test] - fn test_left_empty_right_not_added() { - let config = create_test_config_def(); - let left_ln = b""; - let right_ln = b"bar"; - let symbol = b'>'; - let mut buf = vec![]; - push_output(&left_ln[..], &right_ln[..], symbol, &mut buf, &config).unwrap(); - assert_eq!(buf, b"\t\t\t\t\t\t\t >\tbar\n"); - } - - #[test] - fn test_right_empty_left_not_del() { - let config = create_test_config_def(); - let left_ln = b"bar"; - let right_ln = b""; - let symbol = b'>'; - let mut buf = vec![]; - push_output(&left_ln[..], &right_ln[..], symbol, &mut buf, &config).unwrap(); - assert_eq!(buf, b"bar\t\t\t\t\t\t\t >\n"); - } - - #[test] - fn test_both_empty() { - let config = create_test_config_def(); - let left_ln = b""; - let right_ln = b""; - let symbol = b' '; - let mut buf = vec![]; - push_output(&left_ln[..], &right_ln[..], symbol, &mut buf, &config).unwrap(); - assert_eq!(buf, b"\n"); - } - - #[test] - fn test_output_cut_with_maximization() { - let config = create_test_config_def(); - let left_ln = b"a".repeat(62); - let right_ln = b"a".repeat(62); - let symbol = b' '; - let mut buf = vec![]; - push_output(&left_ln[..], &right_ln[..], symbol, &mut buf, &config).unwrap(); - assert_eq!(buf.len(), 61 * 2 + 2); - assert_eq!(&buf[0..61], vec![b'a'; 61]); - assert_eq!(&buf[61..62], b"\t"); - let mut end = b"a".repeat(61); - end.push(b'\n'); - assert_eq!(&buf[62..], end); - } - - #[test] - fn test_both_lines_non_empty_with_space_symbol_max_tabs() { - let config = create_test_config_def(); - let left_ln = b"left"; - let right_ln = b"right"; - let symbol = b' '; - let mut buf = vec![]; - push_output(left_ln, right_ln, symbol, &mut buf, &config).unwrap(); - let expected_left = "left\t\t\t\t\t\t\t\t"; - let expected_right = "right"; - assert_eq!(buf, format!("{expected_left}{expected_right}\n").as_bytes()); - } - - #[test] - fn test_non_space_symbol_with_padding() { - let config = create_test_config_def(); - let left_ln = b"data"; - let right_ln = b""; - let symbol = b'<'; // impossible case, just to use different symbol - let mut buf = vec![]; - push_output(left_ln, right_ln, symbol, &mut buf, &config).unwrap(); - assert_eq!(buf, "data\t\t\t\t\t\t\t <\n".as_bytes()); - } - - #[test] - fn test_lines_exceeding_half_width() { - let config = create_test_config_def(); - let left_ln = vec![b'a'; 100]; - let left_ln = left_ln.as_slice(); - let right_ln = vec![b'b'; 100]; - let right_ln = right_ln.as_slice(); - let symbol = b' '; - let mut buf = vec![]; - push_output(left_ln, right_ln, symbol, &mut buf, &config).unwrap(); - let expected_left = "a".repeat(61); - let expected_right = "b".repeat(61); - assert_eq!(buf.len(), 61 + 1 + 61 + 1); - assert_eq!(&buf[0..61], expected_left.as_bytes()); - assert_eq!(buf[61], b'\t'); - assert_eq!(&buf[62..123], expected_right.as_bytes()); - assert_eq!(&buf[123..], b"\n"); - } - - #[test] - fn test_tabs_in_lines_expanded() { - let mut config = create_test_config_def(); - config.expanded = true; - let left_ln = b"\tleft"; - let right_ln = b"\tright"; - let symbol = b' '; - let mut buf = vec![]; - push_output(left_ln, right_ln, symbol, &mut buf, &config).unwrap(); - let expected_left = " left".to_string() + &" ".repeat(61 - 12); - let expected_right = " right"; - assert_eq!( - buf, - format!("{}{}{}\n", expected_left, " ", expected_right).as_bytes() - ); - } - - #[test] - fn test_unicode_characters() { - let config = create_test_config_def(); - let left_ln = "Ñéíóú".as_bytes(); - let right_ln = "πŸ˜€πŸ˜ƒπŸ˜„".as_bytes(); - let symbol = b' '; + #[rstest] + #[case::left_empty_right_not_added("", "bar", b'>', false, "\t\t\t\t\t\t\t >\tbar\n")] + #[case::right_empty_left_not_del("bar", "", b'>', false, "bar\t\t\t\t\t\t\t >\n")] + #[case::both_empty("", "", b' ', false, "\n")] + #[case::output_cut_with_maximization( + &"a".repeat(62), + &"a".repeat(62), + b' ', + false, + &format!("{0}\t{0}\n", "a".repeat(61)) + )] + #[case::both_lines_non_empty_with_space_symbol_max_tabs( + "left", + "right", + b' ', + false, + "left\t\t\t\t\t\t\t\tright\n" + )] + // impossible case, just to use different symbol + #[case::non_space_symbol_with_padding( + "data", + "", + b'<', + false, + "data\t\t\t\t\t\t\t <\n" + )] + #[case::lines_exceeding_half_width( + &"a".repeat(100), + &"b".repeat(100), + b' ', + false, + &format!("{}\t{}\n", "a".repeat(61), "b".repeat(61)) + )] + #[case::tabs_in_lines_expanded( + "\tleft", + "\tright", + b' ', + true, + &format!("{:<61} {}\n", " left", " right") + )] + #[case::unicode_characters("Ñéíóú", "πŸ˜€πŸ˜ƒπŸ˜„", b' ', false, "Ñéíóú\t\t\t\t\t\t\t\tπŸ˜€πŸ˜ƒπŸ˜„\n")] + fn output( + #[case] left_ln: &str, + #[case] right_ln: &str, + #[case] symbol: u8, + #[case] expanded: bool, + #[case] expected: &str, + ) { + let config = Config { + expanded, + ..Config::default() + }; let mut buf = vec![]; - push_output(left_ln, right_ln, symbol, &mut buf, &config).unwrap(); - let expected_left = "Ñéíóú\t\t\t\t\t\t\t\t"; - let expected_right = "πŸ˜€πŸ˜ƒπŸ˜„"; - assert_eq!(buf, format!("{expected_left}{expected_right}\n").as_bytes()); + push_output( + left_ln.as_bytes(), + right_ln.as_bytes(), + symbol, + &mut buf, + &config, + ) + .unwrap(); + assert_eq!(buf, expected.as_bytes()); } } @@ -983,29 +651,83 @@ mod tests { vec.windows(pattern.len()).filter(|s| s == &pattern).count() } - fn calc_lines(input: &Vec) -> usize { - let mut lines_counter = 0; - - for c in input { - if c == &b'\n' { - lines_counter += 1; - } - } - - lines_counter - } - - #[test] - fn test_equal_lines() { + fn calc_lines(input: &[u8]) -> usize { + input.iter().filter(|&&c| c == b'\n').count() + } + + #[rstest] + #[case::equal_lines("equal", "equal", 1, 0, 0, &[("equal", 2)])] + #[case::different_lines("eq", "ne", 2, 1, 1, &[("eq", 1), ("ne", 1)])] + #[case::added_line("", "new line", 1, 0, 1, &[("new line", 1)])] + #[case::removed_line("old line", "", 1, 1, 0, &[("old line", 1)])] + #[case::multiple_changes("line1\nline2\nline3", "line1\nmodified\nline4", 5, 2, 2, &[])] + #[case::unicode_and_special_chars( + "Γ‘\t€", + "€\t😊", + 2, + 1, + 1, + &[("Γ‘", 1), ("€", 2), ("😊", 1)] + )] + #[case::mixed_whitespace(" \tspaces", "\t\t tabs", 2, 1, 1, &[("spaces", 1), ("tabs", 1)])] + #[case::partially_matching_lines("match\nchange", "match\nupdated", 3, 1, 1, &[("match", 2)])] + #[case::interleaved_add_remove( + "A\nB\nC\nD", + "B\nX\nD\nY", + 7, + 3, + 3, + &[("A", 1), ("X", 1), ("Y", 1)] + )] + #[case::swapped_lines("1\n2\n3\n4", "4\n3\n2\n1", 7, 3, 3, &[])] + #[case::gap_between_changes( + "Start\nKeep1\nRemove\nKeep2\nEnd", + "Start\nNew1\nKeep1\nKeep2\nNew2\nEnd", + 7, + 1, + 2, + &[("Remove", 1), ("New1", 1), ("New2", 1)] + )] + #[case::mixed_operations_complex( + "Same\nOld1\nSameMid\nOld2\nSameEnd", + "Same\nNew1\nSameMid\nNew2\nNew3\nSameEnd", + 8, + 2, + 3, + &[] + )] + #[case::insert_remove_middle( + "Header\nContent1\nFooter", + "Header\nContent2\nFooter", + 4, + 1, + 1, + &[("Content1", 1), ("Content2", 1)] + )] + #[case::multiple_adjacent_changes("A\nB\nC\nD\nE", "A\nX\nY\nD\nZ", 8, 3, 3, &[])] + fn output( + #[case] from_file: &str, + #[case] to_file: &str, + #[case] lines: usize, + #[case] removed: usize, + #[case] added: usize, + #[case] words: &[(&str, usize)], + ) { let params = generate_params(); - let from_file = b"equal"; - let to_file = b"equal"; let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - assert_eq!(calc_lines(&output), 1); - assert!(!output.contains(&b'<')); - assert!(!output.contains(&b'>')); - assert_eq!(contains_string(&output, "equal"), 2) + diff( + from_file.as_bytes(), + to_file.as_bytes(), + &mut output, + ¶ms, + ); + + assert_eq!(calc_lines(&output), lines); + assert_eq!(contains_string(&output, "<"), removed); + assert_eq!(contains_string(&output, ">"), added); + for (word, count) in words { + assert_eq!(contains_string(&output, word), *count, "{word:?}"); + } } // Regression for #269: the `-y` marker must sit at the gutter middle at any width. @@ -1028,269 +750,41 @@ mod tests { ); } - #[test] - fn test_different_lines() { - let params = generate_params(); - let from_file = b"eq"; - let to_file = b"ne"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - assert_eq!(calc_lines(&output), 2); - assert!(output.contains(&b'>')); - assert!(output.contains(&b'<')); - assert_eq!(contains_string(&output, "eq"), 1); - assert_eq!(contains_string(&output, "ne"), 1); - } - - #[test] - fn test_added_line() { - let params = generate_params(); - let from_file = b""; - let to_file = b"new line"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 1); - assert_eq!(contains_string(&output, ">"), 1); - assert_eq!(contains_string(&output, "new line"), 1); - } - - #[test] - fn test_removed_line() { - let params = generate_params(); - let from_file = b"old line"; - let to_file = b""; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 1); - assert_eq!(contains_string(&output, "<"), 1); - assert_eq!(contains_string(&output, "old line"), 1); - } - - #[test] - fn test_multiple_changes() { - let params = generate_params(); - let from_file = b"line1\nline2\nline3"; - let to_file = b"line1\nmodified\nline4"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 5); - assert_eq!(contains_string(&output, "<"), 2); - assert_eq!(contains_string(&output, ">"), 2); - } - - #[test] - fn test_unicode_and_special_chars() { - let params = generate_params(); - let from_file = "Γ‘\t€".as_bytes(); - let to_file = "€\t😊".as_bytes(); - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert!(String::from_utf8_lossy(&output).contains("Γ‘")); - assert!(String::from_utf8_lossy(&output).contains("€")); - assert!(String::from_utf8_lossy(&output).contains("😊")); - assert_eq!(contains_string(&output, "<"), 1); - assert_eq!(contains_string(&output, ">"), 1); - } - - #[test] - fn test_mixed_whitespace() { - let params = generate_params(); - let from_file = b" \tspaces"; - let to_file = b"\t\t tabs"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert!(output.contains(&b'<')); - assert!(output.contains(&b'>')); - assert!(String::from_utf8_lossy(&output).contains("spaces")); - assert!(String::from_utf8_lossy(&output).contains("tabs")); - } - #[test] fn test_empty_files() { let params = generate_params(); - let from_file = b""; - let to_file = b""; let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - + diff(b"", b"", &mut output, ¶ms); assert_eq!(output, vec![]); } - - #[test] - fn test_partially_matching_lines() { - let params = generate_params(); - let from_file = b"match\nchange"; - let to_file = b"match\nupdated"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 3); - assert_eq!(contains_string(&output, "match"), 2); - assert_eq!(contains_string(&output, "<"), 1); - assert_eq!(contains_string(&output, ">"), 1); - } - - #[test] - fn test_interleaved_add_remove() { - let params = generate_params(); - let from_file = b"A\nB\nC\nD"; - let to_file = b"B\nX\nD\nY"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 7); - assert_eq!(contains_string(&output, "A"), 1); - assert_eq!(contains_string(&output, "X"), 1); - assert_eq!(contains_string(&output, "Y"), 1); - assert_eq!(contains_string(&output, "<"), 3); - assert_eq!(contains_string(&output, ">"), 3); - } - - #[test] - fn test_swapped_lines() { - let params = generate_params(); - let from_file = b"1\n2\n3\n4"; - let to_file = b"4\n3\n2\n1"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 7); - assert_eq!(contains_string(&output, "<"), 3); - assert_eq!(contains_string(&output, ">"), 3); - } - - #[test] - fn test_gap_between_changes() { - let params = generate_params(); - let from_file = b"Start\nKeep1\nRemove\nKeep2\nEnd"; - let to_file = b"Start\nNew1\nKeep1\nKeep2\nNew2\nEnd"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 7); - assert_eq!(contains_string(&output, "Remove"), 1); - assert_eq!(contains_string(&output, "New1"), 1); - assert_eq!(contains_string(&output, "New2"), 1); - assert_eq!(contains_string(&output, "<"), 1); - assert_eq!(contains_string(&output, ">"), 2); - } - - #[test] - fn test_mixed_operations_complex() { - let params = generate_params(); - let from_file = b"Same\nOld1\nSameMid\nOld2\nSameEnd"; - let to_file = b"Same\nNew1\nSameMid\nNew2\nNew3\nSameEnd"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 8); - assert_eq!(contains_string(&output, "<"), 2); - assert_eq!(contains_string(&output, ">"), 3); - } - - #[test] - fn test_insert_remove_middle() { - let params = generate_params(); - let from_file = b"Header\nContent1\nFooter"; - let to_file = b"Header\nContent2\nFooter"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 4); - assert_eq!(contains_string(&output, "Content1"), 1); - assert_eq!(contains_string(&output, "Content2"), 1); - assert_eq!(contains_string(&output, "<"), 1); - assert_eq!(contains_string(&output, ">"), 1); - } - - #[test] - fn test_multiple_adjacent_changes() { - let params = generate_params(); - let from_file = b"A\nB\nC\nD\nE"; - let to_file = b"A\nX\nY\nD\nZ"; - let mut output = vec![]; - diff(from_file, to_file, &mut output, ¶ms); - - assert_eq!(calc_lines(&output), 8); - assert_eq!(contains_string(&output, "<"), 3); - assert_eq!(contains_string(&output, ">"), 3); - } } mod config { use super::*; - fn create_config(full_width: usize, tab_size: usize, expanded: bool) -> Config { - Config::new(full_width, tab_size, expanded) - } - - #[test] - fn test_full_width_80_tab_4() { - let config = create_config(80, 4, false); - assert_eq!(config.sdiff_half_width, 37); - assert_eq!(config.sdiff_column_two_offset, 40); - assert_eq!(config.separator_pos, 38); - } - - #[test] - fn test_full_width_40_tab_8() { - let config = create_config(40, 8, true); - assert_eq!(config.sdiff_half_width, 16); - assert_eq!(config.sdiff_column_two_offset, 24); - assert_eq!(config.separator_pos, 19); // (16 +24 -1) /2 = 19.5 - } - - #[test] - fn test_full_width_30_tab_2() { - let config = create_config(30, 2, false); - assert_eq!(config.sdiff_half_width, 13); - assert_eq!(config.sdiff_column_two_offset, 16); - assert_eq!(config.separator_pos, 14); - } - - #[test] - fn test_small_width_10_tab_4() { - let config = create_config(10, 4, false); - assert_eq!(config.sdiff_half_width, 2); - assert_eq!(config.sdiff_column_two_offset, 8); - assert_eq!(config.separator_pos, 4); - } - - #[test] - fn test_minimal_width_3_tab_4() { - let config = create_config(3, 4, false); - assert_eq!(config.sdiff_half_width, 0); - assert_eq!(config.sdiff_column_two_offset, 3); - assert_eq!(config.separator_pos, 1); - } - - #[test] - fn test_odd_width_7_tab_3() { - let config = create_config(7, 3, false); - assert_eq!(config.sdiff_half_width, 1); - assert_eq!(config.sdiff_column_two_offset, 6); - assert_eq!(config.separator_pos, 3); - } - - #[test] - fn test_max_tab_size() { - // `tab_size + GUTTER_WIDTH_MIN` must not overflow `isize`. - let config = create_config(130, crate::params::MAX_TABSIZE, false); - assert_eq!(config.sdiff_half_width, 0); - assert_eq!(config.sdiff_column_two_offset, 130); - } - - #[test] - fn test_tab_size_larger_than_width() { - let config = create_config(5, 10, false); - assert_eq!(config.sdiff_half_width, 0); - assert_eq!(config.sdiff_column_two_offset, 5); - assert_eq!(config.separator_pos, 2); + #[rstest] + #[case::full_width_80_tab_4(80, 4, false, 37, 40, 38)] + // (16 + 24 - 1) / 2 = 19.5 + #[case::full_width_40_tab_8(40, 8, true, 16, 24, 19)] + #[case::full_width_30_tab_2(30, 2, false, 13, 16, 14)] + #[case::small_width_10_tab_4(10, 4, false, 2, 8, 4)] + #[case::minimal_width_3_tab_4(3, 4, false, 0, 3, 1)] + #[case::odd_width_7_tab_3(7, 3, false, 1, 6, 3)] + // `tab_size + GUTTER_WIDTH_MIN` must not overflow `isize`. + #[case::max_tab_size(130, crate::params::MAX_TABSIZE, false, 0, 130, 64)] + #[case::tab_size_larger_than_width(5, 10, false, 0, 5, 2)] + fn new( + #[case] full_width: usize, + #[case] tab_size: usize, + #[case] expanded: bool, + #[case] half_width: usize, + #[case] column_two_offset: usize, + #[case] separator_pos: usize, + ) { + let config = Config::new(full_width, tab_size, expanded); + assert_eq!(config.sdiff_half_width, half_width); + assert_eq!(config.sdiff_column_two_offset, column_two_offset); + assert_eq!(config.separator_pos, separator_pos); } } } diff --git a/src/unified_diff.rs b/src/unified_diff.rs index ae72461d..f5ca7256 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -426,6 +426,7 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { mod tests { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; use crate::utils::testcmds::PATCH_CMD; @@ -901,78 +902,49 @@ mod tests { } } - #[test] - fn test_stop_early() { + #[rstest] + #[case::full( + false, + "a\nd\nc\n", + "--- foo\tTIMESTAMP\n+++ bar\tTIMESTAMP\n@@ -1,3 +1,3 @@\n a\n-b\n+d\n c\n" + )] + #[case::brief(true, "a\nd\nc\n", "--- foo\tTIMESTAMP\n+++ bar\tTIMESTAMP\n")] + #[case::full_identical(false, "a\nb\nc\n", "")] + #[case::brief_identical(true, "a\nb\nc\n", "")] + fn test_stop_early(#[case] brief: bool, #[case] to: &str, #[case] expected: &str) { use crate::assert_diff_eq; - let from_filename = "foo"; - let from = ["a", "b", "c", ""].join("\n"); - let to_filename = "bar"; - let to = ["a", "d", "c", ""].join("\n"); - - let diff_full = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - ..Default::default() - }, - ); - - let expected_full = [ - "--- foo\tTIMESTAMP", - "+++ bar\tTIMESTAMP", - "@@ -1,3 +1,3 @@", - " a", - "-b", - "+d", - " c", - "", - ] - .join("\n"); - assert_diff_eq!(diff_full, expected_full); - - let diff_brief = diff( - from.as_bytes(), - to.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - brief: true, - ..Default::default() - }, - ); - - let expected_brief = ["--- foo\tTIMESTAMP", "+++ bar\tTIMESTAMP", ""].join("\n"); - assert_diff_eq!(diff_brief, expected_brief); - - let nodiff_full = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - ..Default::default() - }, - ); - assert!(nodiff_full.is_empty()); - - let nodiff_brief = diff( - from.as_bytes(), - from.as_bytes(), - &Params { - from: from_filename.into(), - to: to_filename.into(), - brief: true, - ..Default::default() - }, - ); - assert!(nodiff_brief.is_empty()); + let params = Params { + from: "foo".into(), + to: "bar".into(), + brief, + ..Default::default() + }; + let output = diff(b"a\nb\nc\n", to.as_bytes(), ¶ms); + assert_diff_eq!(output, expected); } - #[test] - fn test_hunk_merging() { + #[rstest] + // Changes separated by up to twice the context size share one hunk. + #[case::changes_share_hunk( + "a\nb\nc\nd\ne\nf\n", + "a\nB\nc\nd\nE\nf\n", + "@@ -1,6 +1,6 @@\n a\n-b\n+B\n c\n d\n-e\n+E\n f\n" + )] + // One more unchanged line between them splits the hunk. + #[case::changes_split_hunks( + "a\nb\nc\nd\ne\nf\ng\n", + "a\nB\nc\nd\ne\nF\ng\n", + "@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n@@ -5,3 +5,3 @@\n e\n-f\n+F\n g\n" + )] + // An insertion before a nearby change gives the two sides different + // line counts; the hunks must still be merged (issue #268). + #[case::insertion_before_change( + "milk\neggs\nbread\nbutter\napples\n", + "milk\neggs\nyogurt\nbread\nhoney\napples\n", + "@@ -2,4 +2,5 @@\n eggs\n+yogurt\n bread\n-butter\n+honey\n apples\n" + )] + fn test_hunk_merging(#[case] from: &str, #[case] to: &str, #[case] hunks: &str) { use crate::assert_diff_eq; let params = Params { @@ -981,67 +953,7 @@ mod tests { context_count: 1, ..Default::default() }; - - // Changes separated by up to twice the context size share one hunk. - let from = ["a", "b", "c", "d", "e", "f", ""].join("\n"); - let to = ["a", "B", "c", "d", "E", "f", ""].join("\n"); - let expected = [ - "--- foo\tTIMESTAMP", - "+++ bar\tTIMESTAMP", - "@@ -1,6 +1,6 @@", - " a", - "-b", - "+B", - " c", - " d", - "-e", - "+E", - " f", - "", - ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - - // One more unchanged line between them splits the hunk. - let from = ["a", "b", "c", "d", "e", "f", "g", ""].join("\n"); - let to = ["a", "B", "c", "d", "e", "F", "g", ""].join("\n"); - let expected = [ - "--- foo\tTIMESTAMP", - "+++ bar\tTIMESTAMP", - "@@ -1,3 +1,3 @@", - " a", - "-b", - "+B", - " c", - "@@ -5,3 +5,3 @@", - " e", - "-f", - "+F", - " g", - "", - ] - .join("\n"); - let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); - assert_diff_eq!(output, expected); - - // An insertion before a nearby change gives the two sides different - // line counts; the hunks must still be merged (issue #268). - let from = ["milk", "eggs", "bread", "butter", "apples", ""].join("\n"); - let to = ["milk", "eggs", "yogurt", "bread", "honey", "apples", ""].join("\n"); - let expected = [ - "--- foo\tTIMESTAMP", - "+++ bar\tTIMESTAMP", - "@@ -2,4 +2,5 @@", - " eggs", - "+yogurt", - " bread", - "-butter", - "+honey", - " apples", - "", - ] - .join("\n"); + let expected = format!("--- foo\tTIMESTAMP\n+++ bar\tTIMESTAMP\n{hunks}"); let output = diff(from.as_bytes(), to.as_bytes(), ¶ms); assert_diff_eq!(output, expected); } diff --git a/src/utils.rs b/src/utils.rs index d866c968..6d6d1395 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -527,68 +527,52 @@ mod tests { mod expand_tabs { use super::*; use pretty_assertions::assert_eq; - - fn expand(line: &[u8], tabsize: usize, marker: &[u8]) -> Vec { + use rstest::rstest; + + #[rstest] + #[case::no_tabs(b"foo barr baz", 8, b"", b"foo barr baz")] + #[case::tabsize_8(b"foo\tbarr\tbaz", 8, b"", b"foo barr baz")] + #[case::tabsize_5(b"foo\tbarr\tbaz", 5, b"", b"foo barr baz")] + #[case::tabsize_2(b"foo\tbarr\tbaz", 2, b"", b"foo barr baz")] + #[case::multibyte_chars("foo\tΓ©pΓ©e\tbaz".as_bytes(), 8, b"", "foo Γ©pΓ©e baz".as_bytes())] + #[case::emoji("foo\tπŸ˜‰\tbaz".as_bytes(), 5, b"", "foo πŸ˜‰ baz".as_bytes())] + // Note: The Woman Scientist emoji (πŸ‘©β€πŸ”¬) is a ZWJ sequence combining + // the Woman emoji (πŸ‘©) and the Microscope emoji (πŸ”¬). On supported platforms + // it is displayed as a single emoji and has a print size of 2 columns. + // Terminal emulators tend to not support this, and display the two emojis + // side by side, thus accounting for a print size of 4 columns, but the + // unicode_width crate reports a correct size of 2. + #[case::zwj_sequence("foo\tπŸ‘©β€πŸ”¬\tbaz".as_bytes(), 6, b"", "foo πŸ‘©β€πŸ”¬ baz".as_bytes())] + // [240, 240, 152, 137] is an invalid UTF-8 sequence, so it is handled as 4 bytes + #[case::invalid_utf8( + &[240, 240, 152, 137, 9, 102, 111, 111], + 8, + b"", + &[240, 240, 152, 137, 32, 32, 32, 32, 102, 111, 111] + )] + // Only the invalid byte counts as a column, not the whole chunk. + #[case::invalid_byte_before_valid_char(b"\xff\xc3\xa9\tx", 4, b"< ", b"\xff\xc3\xa9 x")] + // A carriage return restarts the line behind the marker again. + #[case::carriage_return(b"ab\rc\td", 8, b"< ", b"ab\r< c d")] + #[case::two_carriage_returns(b"ab\r\r\tc", 4, b"< ", b"ab\r< \r< c")] + #[case::trailing_carriage_return(b"ab\r", 8, b"< ", b"ab\r")] + #[case::carriage_return_then_tab(b"x\r\ty\r", 4, b"< ", b"x\r< y\r")] + // A backspace moves one column back, but not before the start. + #[case::backspace(b"abc\x08d\te", 8, b"< ", b"abc\x08d e")] + #[case::backspaces_at_start(b"\x08\x08x\ty", 8, b"< ", b"x y")] + #[case::backspace_at_start(b"\x08x", 8, b"< ", b"x")] + // Other control characters, C1 ones included, take no room. + #[case::control_chars(b"a\x01\x7f\x1bb\tc", 8, b"< ", b"a\x01\x7f\x1bb c")] + #[case::c1_control_char("a\u{80}b\tc".as_bytes(), 4, b"< ", "a\u{80}b c".as_bytes())] + fn expansion( + #[case] line: &[u8], + #[case] tabsize: usize, + #[case] marker: &[u8], + #[case] expected: &[u8], + ) { let mut output = Vec::new(); assert!(do_expand_tabs(&mut output, line, tabsize, marker).is_ok()); - output - } - - fn assert_tab_expansion(line: &str, tabsize: usize, expected: &str) { - assert_eq!(expand(line.as_bytes(), tabsize, b""), expected.as_bytes()); - } - - #[test] - fn basics() { - assert_tab_expansion("foo barr baz", 8, "foo barr baz"); - assert_tab_expansion("foo\tbarr\tbaz", 8, "foo barr baz"); - assert_tab_expansion("foo\tbarr\tbaz", 5, "foo barr baz"); - assert_tab_expansion("foo\tbarr\tbaz", 2, "foo barr baz"); - } - - #[test] - fn multibyte_chars() { - assert_tab_expansion("foo\tΓ©pΓ©e\tbaz", 8, "foo Γ©pΓ©e baz"); - assert_tab_expansion("foo\tπŸ˜‰\tbaz", 5, "foo πŸ˜‰ baz"); - - // Note: The Woman Scientist emoji (πŸ‘©β€πŸ”¬) is a ZWJ sequence combining - // the Woman emoji (πŸ‘©) and the Microscope emoji (πŸ”¬). On supported platforms - // it is displayed as a single emoji and has a print size of 2 columns. - // Terminal emulators tend to not support this, and display the two emojis - // side by side, thus accounting for a print size of 4 columns, but the - // unicode_width crate reports a correct size of 2. - assert_tab_expansion("foo\tπŸ‘©β€πŸ”¬\tbaz", 6, "foo πŸ‘©β€πŸ”¬ baz"); - } - - #[test] - fn invalid_utf8() { - // [240, 240, 152, 137] is an invalid UTF-8 sequence, so it is handled as 4 bytes - assert_eq!( - expand(&[240, 240, 152, 137, 9, 102, 111, 111], 8, b""), - &[240, 240, 152, 137, 32, 32, 32, 32, 102, 111, 111] - ); - // Only the invalid byte counts as a column, not the whole chunk. - assert_tab_expansion_bytes(b"\xff\xc3\xa9\tx", 4, b"\xff\xc3\xa9 x"); - } - - fn assert_tab_expansion_bytes(line: &[u8], tabsize: usize, expected: &[u8]) { - assert_eq!(expand(line, tabsize, b"< "), expected); - } - - #[test] - fn control_chars() { - // A carriage return restarts the line behind the marker again. - assert_tab_expansion_bytes(b"ab\rc\td", 8, b"ab\r< c d"); - assert_tab_expansion_bytes(b"ab\r\r\tc", 4, b"ab\r< \r< c"); - assert_tab_expansion_bytes(b"ab\r", 8, b"ab\r"); - assert_tab_expansion_bytes(b"x\r\ty\r", 4, b"x\r< y\r"); - // A backspace moves one column back, but not before the start. - assert_tab_expansion_bytes(b"abc\x08d\te", 8, b"abc\x08d e"); - assert_tab_expansion_bytes(b"\x08\x08x\ty", 8, b"x y"); - assert_tab_expansion_bytes(b"\x08x", 8, b"x"); - // Other control characters, C1 ones included, take no room. - assert_tab_expansion_bytes(b"a\x01\x7f\x1bb\tc", 8, b"a\x01\x7f\x1bb c"); - assert_tab_expansion_bytes("a\u{80}b\tc".as_bytes(), 4, "a\u{80}b c".as_bytes()); + assert_eq!(output, expected); } #[test] @@ -609,74 +593,74 @@ mod tests { mod quoting { use super::*; use pretty_assertions::assert_eq; - - fn quoted_name(name: &[u8]) -> String { - String::from_utf8(quote_file_name(name).into_owned()).unwrap() - } - - fn quoted_arg(arg: &str) -> String { - String::from_utf8(quote_shell_argument(arg.as_bytes()).into_owned()).unwrap() + use rstest::rstest; + + #[rstest] + #[case::plain(b"src/main.rs", "src/main.rs")] + #[case::shell_specials(b"why?*$'#~", "why?*$'#~")] + #[case::space(b"two words", r#""two words""#)] + #[case::double_quotes(b"say \"hi\"", r#""say \"hi\"""#)] + #[case::control_escapes(b"\x07\x08\t\n\x0b\x0c\r", r#""\a\b\t\n\v\f\r""#)] + #[case::octal_escape(b"\x1bx\x7f", "\"\\033x\x7f\"")] + #[case::non_ascii("caf\u{e9}".as_bytes(), r#""caf\303\251""#)] + #[case::invalid_utf8(b"\xfe", r#""\376""#)] + fn file_names(#[case] name: &[u8], #[case] expected: &str) { + assert_eq!(quoted_name(name), expected); } #[test] - fn file_names() { - assert_eq!(quoted_name(b"src/main.rs"), "src/main.rs"); - assert_eq!(quoted_name(b"why?*$'#~"), "why?*$'#~"); - assert_eq!(quoted_name(b"two words"), r#""two words""#); - assert_eq!(quoted_name(b"say \"hi\""), r#""say \"hi\"""#); + fn file_names_with_backslashes() { if cfg!(windows) { assert_eq!(quoted_name(b"C:\\temp"), r"C:\temp"); assert_eq!(quoted_name(b"C:\\my docs"), r#""C:\my docs""#); } else { assert_eq!(quoted_name(b"C:\\temp"), r#""C:\\temp""#); } - assert_eq!( - quoted_name(b"\x07\x08\t\n\x0b\x0c\r"), - r#""\a\b\t\n\v\f\r""# - ); - assert_eq!(quoted_name(b"\x1bx\x7f"), "\"\\033x\x7f\""); - assert_eq!(quoted_name("caf\u{e9}".as_bytes()), r#""caf\303\251""#); - assert_eq!(quoted_name(b"\xfe"), r#""\376""#); } - #[test] - fn shell_arguments() { - assert_eq!(quoted_arg("-u"), "-u"); - assert_eq!(quoted_arg("a,b:c@d%e+f{g}h]/i.j"), "a,b:c@d%e+f{g}h]/i.j"); - assert_eq!(quoted_arg("x~#"), "x~#"); - assert_eq!(quoted_arg("~x"), "'~x'"); - assert_eq!(quoted_arg("#x"), "'#x'"); - assert_eq!(quoted_arg("^fn (main|init)"), "'^fn (main|init)'"); - assert_eq!(quoted_arg("--width=9"), "'--width=9'"); - assert_eq!(quoted_arg(""), "''"); - assert_eq!(quoted_arg("don't"), "\"don't\""); - assert_eq!(quoted_arg("don't $pay"), "'don'\\''t $pay'"); + fn quoted_name(name: &[u8]) -> String { + String::from_utf8(quote_file_name(name).into_owned()).unwrap() } - #[test] - fn single_quotes() { - assert_eq!(single_quote(b"plain"), b"'plain'"); - assert_eq!(single_quote(b"it's"), br"'it'\''s'"); - assert_eq!(single_quote(b""), b"''"); + #[rstest] + #[case::option("-u", "-u")] + #[case::safe_punctuation("a,b:c@d%e+f{g}h]/i.j", "a,b:c@d%e+f{g}h]/i.j")] + #[case::tilde_and_hash_inside("x~#", "x~#")] + #[case::leading_tilde("~x", "'~x'")] + #[case::leading_hash("#x", "'#x'")] + #[case::regex("^fn (main|init)", "'^fn (main|init)'")] + #[case::equals_sign("--width=9", "'--width=9'")] + #[case::empty("", "''")] + #[case::single_quote("don't", "\"don't\"")] + #[case::single_quote_and_dollar("don't $pay", "'don'\\''t $pay'")] + fn shell_arguments(#[case] arg: &str, #[case] expected: &str) { + let quoted = String::from_utf8(quote_shell_argument(arg.as_bytes()).into_owned()); + assert_eq!(quoted.unwrap(), expected); + } + + #[rstest] + #[case::plain(b"plain", b"'plain'")] + #[case::single_quote(b"it's", br"'it'\''s'")] + #[case::empty(b"", b"''")] + fn single_quotes(#[case] text: &[u8], #[case] expected: &[u8]) { + assert_eq!(single_quote(text), expected); } } mod write_line { use super::*; use pretty_assertions::assert_eq; + use rstest::rstest; - fn assert_line_written(line: &str, expand_tabs: bool, tabsize: usize, expected: &str) { + #[rstest] + #[case::no_tabs("foo bar baz", false, "foo bar baz")] + #[case::tab_kept("foo bar\tbaz", false, "foo bar\tbaz")] + #[case::tab_expanded("foo bar\tbaz", true, "foo bar baz")] + fn basics(#[case] line: &str, #[case] expand_tabs: bool, #[case] expected: &str) { let mut output: Vec = Vec::new(); - assert!(do_write_line(&mut output, line.as_bytes(), expand_tabs, tabsize, b"").is_ok()); + assert!(do_write_line(&mut output, line.as_bytes(), expand_tabs, 8, b"").is_ok()); assert_eq!(output, expected.as_bytes()); } - - #[test] - fn basics() { - assert_line_written("foo bar baz", false, 8, "foo bar baz"); - assert_line_written("foo bar\tbaz", false, 8, "foo bar\tbaz"); - assert_line_written("foo bar\tbaz", true, 8, "foo bar baz"); - } } mod modification_time {