From d2af261f67210073b059e6a891e1afcda6a79ff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Rodrigues=20Miguel?= Date: Mon, 5 Apr 2021 01:14:27 -0300 Subject: [PATCH] Fix `cargo test` tests --- src/cli.rs | 99 ++------------------------------------- src/error.rs | 23 ++++----- src/test.rs | 129 ++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 113 insertions(+), 138 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 9aa040d..672836c 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -66,8 +66,9 @@ pub fn parse_args_from(mut args: Vec) -> crate::Result { let mut files: Vec = args.into_iter().map(PathBuf::from).collect(); if files.len() < 2 { - panic!("The compress subcommands demands at least 2 arguments, see usage:......."); + return Err(crate::Error::MissingArgumentsForCompression); } + // Safety: we checked that args.len() >= 2 let compressed_output_path = files.pop().unwrap(); @@ -102,98 +103,4 @@ pub fn parse_args_from(mut args: Vec) -> crate::Result { }; Ok(parsed_args) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn gen_args(text: &str) -> Vec { - let args = text.split_whitespace(); - args.map(OsString::from).collect() - } - - // // util for test the argument parsing - // macro_rules! test { - // ($expected_command:expr, $input_text:expr) => {{ - // assert_eq!( - // $expected_command, - // oof::try_arg_parsing($input_text.split_whitespace()) - // ) - // }}; - // } - - macro_rules! parse { - ($input_text:expr) => {{ - let args = gen_args($input_text); - parse_args_from(args).unwrap() - }}; - } - - #[test] - // The absolute flags that ignore all the other argparsing rules are --help and --version - fn test_absolute_flags() { - let expected = Command::ShowHelp; - assert_eq!(expected, parse!("").command); - assert_eq!(expected, parse!("-h").command); - assert_eq!(expected, parse!("--help").command); - assert_eq!(expected, parse!("aaaaaaaa --help -o -e aaa").command); - assert_eq!(expected, parse!("aaaaaaaa -h").command); - assert_eq!(expected, parse!("--help compress aaaaaaaa").command); - assert_eq!(expected, parse!("compress --help").command); - assert_eq!(expected, parse!("--version --help").command); - assert_eq!(expected, parse!("aaaaaaaa -v aaaa -h").command); - - let expected = Command::ShowVersion; - assert_eq!(expected, parse!("ouch --version").command); - assert_eq!(expected, parse!("ouch a --version b").command); - } - - #[test] - fn test_arg_parsing_compress_subcommand() { - let files = ["a", "b", "c"].iter().map(PathBuf::from).collect(); - - let expected = Command::Compress { - files, - compressed_output_path: "d".into(), - }; - assert_eq!(expected, parse!("compress a b c d").command); - } - - #[test] - fn test_arg_parsing_decompress_subcommand() { - let files: Vec<_> = ["a", "b", "c"].iter().map(PathBuf::from).collect(); - - let expected = Command::Decompress { - files: files.clone(), - output_folder: None, - }; - assert_eq!(expected, parse!("a b c").command); - - let expected = Command::Decompress { - files, - output_folder: Some("folder".into()), - }; - assert_eq!(expected, parse!("a b c --output folder").command); - assert_eq!(expected, parse!("a b --output folder c").command); - assert_eq!(expected, parse!("a --output folder b c").command); - assert_eq!(expected, parse!("--output folder a b c").command); - } - - // #[test] - // fn test_arg_parsing_decompress_subcommand() { - // let files: Vec = ["a", "b", "c"].iter().map(PathBuf::from).collect(); - - // let expected = Ok(Command::Decompress { - // files: files.clone(), - // }); - // test!(expected, "ouch a b c"); - - // let files: Vec = ["a", "b", "c", "d"].iter().map(PathBuf::from).collect(); - - // let expected = Ok(Command::Decompress { - // files: files.clone(), - // }); - // test!(expected, "ouch a b c d"); - // } -} +} \ No newline at end of file diff --git a/src/error.rs b/src/error.rs index 1ffd474..7752981 100644 --- a/src/error.rs +++ b/src/error.rs @@ -15,22 +15,14 @@ pub enum Error { InvalidZipArchive(&'static str), PermissionDenied, UnsupportedZipArchive(&'static str), - // InputsMustBeDecompressible(PathBuf), InternalError, CompressingRootFolder, + MissingArgumentsForCompression, WalkdirError, } pub type Result = std::result::Result; -// impl std::error::Error for Error { -// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { -// // TODO: get rid of PartialEq and Eq in self::Error in order to -// // correctly use `source`. -// None -// } -// } - impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) @@ -42,19 +34,18 @@ impl fmt::Display for Error { match self { Error::MissingExtensionError(filename) => { write!(f, "{} ", "[ERROR]".red())?; + // TODO: show MIME type of the unsupported file write!(f, "cannot compress to \'{}\', likely because it has an unsupported (or missing) extension.", filename) } - // Error::InputsMustBeDecompressible(file) => { - // write!(f, "{} ", "[ERROR]".red())?; - // write!(f, "file '{:?}' is not decompressible", file) - // } Error::WalkdirError => { // Already printed in the From block write!(f, "") } Error::FileNotFound(file) => { write!(f, "{} ", "[ERROR]".red())?; - // TODO: check if file == "" + if file == &PathBuf::from("") { + return write!(f, "file not found!"); + } write!(f, "file {:?} not found!", file) } Error::CompressingRootFolder => { @@ -73,6 +64,10 @@ impl fmt::Display for Error { "rsync".green() ) } + Error::MissingArgumentsForCompression => { + write!(f, "{} ", "[ERROR]".red())?; + write!(f,"The compress subcommands demands at least 2 arguments, see usage: ") + } Error::InternalError => { write!(f, "{} ", "[ERROR]".red())?; write!(f, "You've reached an internal error! This really should not have happened.\nPlease file an issue at {}", "https://github.com/vrmiguel/ouch".green()) diff --git a/src/test.rs b/src/test.rs index 322606d..ebc32f8 100644 --- a/src/test.rs +++ b/src/test.rs @@ -1,39 +1,112 @@ -// TODO: remove tests of CompressionFormat::try_from since that's no longer used anywhere +use std::{fs, path::Path}; -// use std::{ -// convert::TryFrom, -// ffi::{OsStr, OsString}, -// fs, -// path::Path, -// }; +#[allow(dead_code)] +// ouch's command-line logic uses fs::canonicalize on its inputs so we cannot +// use made-up files for testing. +// make_dummy_file therefores creates a small temporary file to bypass fs::canonicalize errors +fn make_dummy_file<'a, P>(path: P) -> crate::Result<()> +where + P: AsRef + 'a, +{ + fs::write(path.as_ref(), &[2, 3, 4, 5, 6, 7, 8, 9, 10])?; + Ok(()) +} -// use crate::{ -// cli::Command, -// extension::{CompressionFormat, CompressionFormat::*, Extension}, -// file::File, -// }; +#[allow(dead_code)] +fn make_dummy_files<'a, P>(paths: &[P]) -> crate::Result<()> +where + P: AsRef + 'a, +{ + let _ = paths + .iter() + .map(make_dummy_file) + .map(Result::unwrap) + .collect::>(); + Ok(()) +} -// // Helper -// fn gen_args(text: &str) -> Vec { -// let args = text.split_whitespace(); -// args.map(OsString::from).collect() -// } +#[cfg(test)] +mod tests { + use super::{make_dummy_files}; + use crate::cli; + use crate::cli::Command; + use std::{ffi::OsString, fs, path::PathBuf}; + + fn gen_args(text: &str) -> Vec { + let args = text.split_whitespace(); + args.map(OsString::from).collect() + } + + macro_rules! parse { + ($input_text:expr) => {{ + let args = gen_args($input_text); + cli::parse_args_from(args).unwrap() + }}; + } + + #[test] + // The absolute flags that ignore all the other argparsing rules are --help and --version + fn test_absolute_flags() { + let expected = Command::ShowHelp; + assert_eq!(expected, parse!("").command); + assert_eq!(expected, parse!("-h").command); + assert_eq!(expected, parse!("--help").command); + assert_eq!(expected, parse!("aaaaaaaa --help -o -e aaa").command); + assert_eq!(expected, parse!("aaaaaaaa -h").command); + assert_eq!(expected, parse!("--help compress aaaaaaaa").command); + assert_eq!(expected, parse!("compress --help").command); + assert_eq!(expected, parse!("--version --help").command); + assert_eq!(expected, parse!("aaaaaaaa -v aaaa -h").command); + + let expected = Command::ShowVersion; + assert_eq!(expected, parse!("ouch --version").command); + assert_eq!(expected, parse!("ouch a --version b").command); + } + + #[test] + fn test_arg_parsing_compress_subcommand() -> crate::Result<()> { + + let files = vec!["a", "b", "c"]; + make_dummy_files(&*files)?; + let files= files.iter().map(fs::canonicalize).map(Result::unwrap).collect(); + + let expected = Command::Compress { + files, + compressed_output_path: "d".into(), + }; + assert_eq!(expected, parse!("compress a b c d").command); + + fs::remove_file("a")?; + fs::remove_file("b")?; + fs::remove_file("c")?; + Ok(()) + } + + #[test] + fn test_arg_parsing_decompress_subcommand() { + let files: Vec<_> = ["a", "b", "c"].iter().map(PathBuf::from).collect(); + + let expected = Command::Decompress { + files: files.clone(), + output_folder: None, + }; + assert_eq!(expected, parse!("a b c").command); + + let expected = Command::Decompress { + files, + output_folder: Some("folder".into()), + }; + assert_eq!(expected, parse!("a b c --output folder").command); + assert_eq!(expected, parse!("a b --output folder c").command); + assert_eq!(expected, parse!("a --output folder b c").command); + assert_eq!(expected, parse!("--output folder a b c").command); + } +} // #[cfg(test)] // mod cli { // use super::*; -// // ouch's command-line logic uses fs::canonicalize on its inputs so we cannot -// // use made-up files for testing. -// // make_dummy_file therefores creates a small temporary file to bypass fs::canonicalize errors -// fn make_dummy_file<'a, P>(path: P) -> crate::Result<()> -// where -// P: AsRef + 'a, -// { -// fs::write(path.as_ref(), &[2, 3, 4, 5, 6, 7, 8, 9, 10])?; -// Ok(()) -// } - // #[test] // fn decompress_files_into_folder() -> crate::Result<()> { // make_dummy_file("file.zip")?;