tests: Add tests for extension extraction

This commit is contained in:
Vinícius Rodrigues Miguel 2021-03-19 15:18:32 -03:00
parent e04aba8d53
commit 73398c2d50
7 changed files with 182 additions and 181 deletions

View File

@ -1,4 +1,4 @@
use std::{convert::TryFrom, ffi::OsStr, path::PathBuf, vec::Vec}; use std::{convert::TryFrom, path::PathBuf, vec::Vec};
use clap::{Arg, Values}; use clap::{Arg, Values};
use colored::Colorize; use colored::Colorize;
@ -61,88 +61,78 @@ pub fn get_matches() -> clap::ArgMatches<'static> {
// holy spaghetti code // holy spaghetti code
impl TryFrom<clap::ArgMatches<'static>> for Command { impl TryFrom<clap::ArgMatches<'static>> for Command {
type Error = error::Error; type Error = error::Error;
fn try_from(matches: clap::ArgMatches<'static>) -> error::OuchResult<Command> { fn try_from(matches: clap::ArgMatches<'static>) -> error::OuchResult<Command> {
let process_decompressible_input = |input_files: Values| {
let input_files =
input_files.map(|filename| (filename, CompressionExtension::try_from(filename)));
let process_decompressible_input = |input_files: Values| { for file in input_files.clone() {
let input_files = input_files if let (file, Err(_)) = file {
.map(|filename| (filename, CompressionExtension::try_from(filename))); // eprintln!("{}: file '{}' is not decompressible.", "error".red(), file);
return Err(error::Error::InputsMustHaveBeenDecompressible(file.into()));
for file in input_files.clone() {
if let (file, Err(_)) = file {
// eprintln!("{}: file '{}' is not decompressible.", "error".red(), file);
return Err(error::Error::InputsMustHaveBeenDecompressible(file.into()));
}
}
Ok(input_files
.map(|(filename, extension)|
(PathBuf::from(filename), extension.unwrap())
)
.collect::<Vec<_>>())
};
// Possibilities:
// * Case 1: output not supplied, therefore try to infer output by checking if all input files are decompressible
// * Case 2: output supplied
let output_was_supplied = matches.is_present("output");
let input_files = matches
.values_of("input")
.unwrap(); // Safe to unwrap since input is an obligatory argument
if output_was_supplied {
let output_file = matches
.value_of("output")
.unwrap(); // Safe unwrap since we've established that output was supplied
let output_file_extension = CompressionExtension::try_from(output_file);
let output_is_compressible = output_file_extension.is_ok();
if output_is_compressible {
println!("{}: trying to compress input files into '{}'", "info".yellow(), output_file);
let input_files = input_files.map(PathBuf::from).collect();
return Ok(
Command {
command_type: CommandType::Compression(input_files),
output: Some(File::WithExtension(
(output_file.into(), output_file_extension.unwrap())
))
}
);
}
else {
// Checking if input files are decompressible
let input_files = process_decompressible_input(input_files)?;
println!("{}: attempting to decompress input files into {}", "info".yellow(), output_file);
return Ok(
Command {
command_type: CommandType::Decompression(input_files),
output: Some(File::WithoutExtension(output_file.into()))
}
);
} }
} else {
// else: output file not supplied
// Case 1: all input files are decompressible
// Case 2: error
let input_files = process_decompressible_input(input_files)?;
return Ok(
Command {
command_type: CommandType::Decompression(input_files),
output: None
}
);
} }
Ok(input_files
.map(|(filename, extension)| (PathBuf::from(filename), extension.unwrap()))
.collect::<Vec<_>>())
};
// Possibilities:
// * Case 1: output not supplied, therefore try to infer output by checking if all input files are decompressible
// * Case 2: output supplied
let output_was_supplied = matches.is_present("output");
let input_files = matches.values_of("input").unwrap(); // Safe to unwrap since input is an obligatory argument
if output_was_supplied {
let output_file = matches.value_of("output").unwrap(); // Safe unwrap since we've established that output was supplied
let output_file_extension = CompressionExtension::try_from(output_file);
let output_is_compressible = output_file_extension.is_ok();
if output_is_compressible {
println!(
"{}: trying to compress input files into '{}'",
"info".yellow(),
output_file
);
let input_files = input_files.map(PathBuf::from).collect();
return Ok(Command {
command_type: CommandType::Compression(input_files),
output: Some(File::WithExtension((
output_file.into(),
output_file_extension.unwrap(),
))),
});
} else {
// Checking if input files are decompressible
let input_files = process_decompressible_input(input_files)?;
println!(
"{}: attempting to decompress input files into {}",
"info".yellow(),
output_file
);
return Ok(Command {
command_type: CommandType::Decompression(input_files),
output: Some(File::WithoutExtension(output_file.into())),
});
}
} else {
// else: output file not supplied
// Case 1: all input files are decompressible
// Case 2: error
let input_files = process_decompressible_input(input_files)?;
return Ok(Command {
command_type: CommandType::Decompression(input_files),
output: None,
});
} }
} }
}

View File

@ -1,4 +1,4 @@
use std::{fmt, path::PathBuf}; use std::fmt;
use colored::Colorize; use colored::Colorize;
@ -6,9 +6,10 @@ use colored::Colorize;
pub enum Error { pub enum Error {
UnknownExtensionError(String), UnknownExtensionError(String),
MissingExtensionError(String), MissingExtensionError(String),
// TODO: get rid of this error variant
InvalidUnicode, InvalidUnicode,
InvalidInput, InvalidInput,
InputsMustHaveBeenDecompressible(String) InputsMustHaveBeenDecompressible(String),
} }
// This should be placed somewhere else // This should be placed somewhere else

0
src/evaluator.rs Normal file
View File

View File

@ -43,6 +43,9 @@ impl TryFrom<&PathBuf> for CompressionExtension {
match ext { match ext {
"zip" => Ok(Zip), "zip" => Ok(Zip),
"tar" => Ok(Tar), "tar" => Ok(Tar),
"gz" => Ok(Gzip),
"bz" => Ok(Bzip),
"lzma" => Ok(Lzma),
other => Err(error::Error::UnknownExtensionError(other.into())), other => Err(error::Error::UnknownExtensionError(other.into())),
} }
} }

View File

@ -1,43 +1,9 @@
use std::{convert::TryFrom, path::PathBuf, str::FromStr}; use std::path::PathBuf;
use crate::error::Error as OuchError;
use crate::error;
use crate::extensions::CompressionExtension; use crate::extensions::CompressionExtension;
// pub type File = (PathBuf, CompressionExtension);
// #[derive(Debug)]
// pub struct FileWithExtension {
// pub extension: CompressionExtension,
// pub filename: PathBuf,
// }
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug)]
pub enum File { pub enum File {
WithExtension((PathBuf, CompressionExtension)), WithExtension((PathBuf, CompressionExtension)),
WithoutExtension(PathBuf) WithoutExtension(PathBuf),
} }
// impl TryFrom<String> for FileWithExtension {
// type Error = OuchError;
// fn try_from(filename: String) -> error::OuchResult<Self> {
// // Safe to unwrap (infallible operation)
// let filename = PathBuf::from_str(&filename).unwrap();
// let os_str = match filename.extension() {
// Some(os_str) => os_str,
// None => return Err(OuchError::MissingExtensionError(filename.to_string_lossy().to_string())),
// };
// let extension = match CompressionExtension::try_from(os_str.into()) {
// Ok(ext) => ext,
// Err(err) => return Err(err),
// };
// Ok(Self {
// filename,
// extension,
// })
// }
// }

View File

@ -1,15 +1,13 @@
use std::{convert::TryFrom, fs::File}; use std::convert::TryFrom;
use cli::get_matches;
mod cli; mod cli;
mod file;
mod extensions;
mod error; mod error;
mod extensions;
mod file;
mod test; mod test;
mod evaluator;
fn main() { fn main() {
// Just testing // Just testing
// let args: Vec<String> = std::env::args().collect(); // let args: Vec<String> = std::env::args().collect();
@ -20,7 +18,7 @@ fn main() {
// Ok((reader, compression)) => {}, // Ok((reader, compression)) => {},
// Err(err) => {} // Err(err) => {}
// } // }
// let (mut reader, compression) = niffler::sniff(Box::new(&file[..])).unwrap(); // let (mut reader, compression) = niffler::sniff(Box::new(&file[..])).unwrap();
// match compression { // match compression {
@ -35,12 +33,13 @@ fn main() {
// dbg!(compression); // dbg!(compression);
let matches = get_matches(); let matches = cli::get_matches();
match cli::Command::try_from(matches) { match cli::Command::try_from(matches) {
Ok(vals) => { dbg!(vals); }, Ok(vals) => {
dbg!(vals);
}
Err(err) => { Err(err) => {
print!("{}\n", err); print!("{}\n", err);
} }
} }
} }

View File

@ -1,38 +1,23 @@
use std::{convert::TryFrom};
#[cfg(test)] #[cfg(test)]
mod cli { mod cli {
use std::convert::TryFrom;
use crate::cli::clap_app; use crate::cli::clap_app;
use crate::cli::Command; use crate::cli::Command;
use crate::file::File;
use crate::cli::CommandType::*; use crate::cli::CommandType::*;
use crate::extensions::CompressionExtension::*;
use crate::error::OuchResult; use crate::error::OuchResult;
use crate::extensions::CompressionExtension::*;
use crate::file::File;
use std::convert::TryFrom;
#[test] #[test]
fn decompress_files_into_folder() -> OuchResult<()> { fn decompress_files_into_folder() -> OuchResult<()> {
let matches = clap_app(). let matches = clap_app().get_matches_from(vec!["ouch", "-i", "file.zip", "-o", "folder/"]);
get_matches_from(
vec!["ouch", "-i", "file.zip", "-o", "folder/"]
);
let command_from_matches = Command::try_from(matches)?; let command_from_matches = Command::try_from(matches)?;
assert_eq!( assert_eq!(
command_from_matches, command_from_matches,
Command { Command {
command_type: Decompression( command_type: Decompression(vec![("file.zip".into(), Zip,),],),
vec![
(
"file.zip".into(),
Zip,
),
],
),
output: Some(File::WithoutExtension("folder".into())), output: Some(File::WithoutExtension("folder".into())),
} }
); );
@ -42,27 +27,16 @@ mod cli {
#[test] #[test]
fn decompress_files() -> OuchResult<()> { fn decompress_files() -> OuchResult<()> {
let matches = clap_app(). let matches = clap_app().get_matches_from(vec!["ouch", "-i", "file.zip", "file.tar"]);
get_matches_from(
vec!["ouch", "-i", "file.zip", "file.tar"]
);
let command_from_matches = Command::try_from(matches)?; let command_from_matches = Command::try_from(matches)?;
assert_eq!( assert_eq!(
command_from_matches, command_from_matches,
Command { Command {
command_type: Decompression( command_type: Decompression(vec![
vec![ ("file.zip".into(), Zip,),
( ("file.tar".into(), Tar,),
"file.zip".into(), ],),
Zip,
),
(
"file.tar".into(),
Tar,
),
],
),
output: None, output: None,
} }
); );
@ -72,15 +46,27 @@ mod cli {
#[test] #[test]
fn compress_files() -> OuchResult<()> { fn compress_files() -> OuchResult<()> {
let matches = clap_app(). let matches = clap_app().get_matches_from(vec![
get_matches_from( "ouch",
vec!["ouch", "-i", "file", "file2.jpeg", "file3.ok", "-o", "file.tar"] "-i",
); "file",
"file2.jpeg",
"file3.ok",
"-o",
"file.tar",
]);
let command_from_matches = Command::try_from(matches)?; let command_from_matches = Command::try_from(matches)?;
assert_eq!( assert_eq!(
command_from_matches, command_from_matches,
Command { command_type: Compression(vec!["file".into(), "file2.jpeg".into(), "file3.ok".into()]), output: Some(File::WithExtension(("file.tar".into(), Tar))) } Command {
command_type: Compression(vec![
"file".into(),
"file2.jpeg".into(),
"file3.ok".into()
]),
output: Some(File::WithExtension(("file.tar".into(), Tar)))
}
); );
Ok(()) Ok(())
@ -89,24 +75,18 @@ mod cli {
#[cfg(test)] #[cfg(test)]
mod cli_errors { mod cli_errors {
use std::convert::TryFrom; use std::convert::TryFrom;
use crate::cli::clap_app; use crate::cli::clap_app;
use crate::cli::Command; use crate::cli::Command;
use crate::file::File;
use crate::cli::CommandType::*;
use crate::extensions::CompressionExtension::*;
use crate::error::OuchResult;
use crate::error::Error; use crate::error::Error;
use crate::error::OuchResult;
#[test] #[test]
fn compress_files() -> OuchResult<()> { fn compress_files() -> OuchResult<()> {
let matches = clap_app(). let matches =
get_matches_from( clap_app().get_matches_from(vec!["ouch", "-i", "a_file", "file2.jpeg", "file3.ok"]);
vec!["ouch", "-i", "a_file", "file2.jpeg", "file3.ok"]
);
let res = Command::try_from(matches); let res = Command::try_from(matches);
assert_eq!( assert_eq!(
@ -116,4 +96,66 @@ mod cli_errors {
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod extension_extraction {
use crate::error::OuchResult;
use crate::extensions::CompressionExtension;
use std::{convert::TryFrom, path::PathBuf, str::FromStr};
#[test]
fn zip() -> OuchResult<()> {
let path = PathBuf::from_str("filename.tar.zip").unwrap();
assert_eq!(
CompressionExtension::try_from(&path)?,
CompressionExtension::Zip
);
Ok(())
}
#[test]
fn tar() -> OuchResult<()> {
let path = PathBuf::from_str("pictures.tar").unwrap();
assert_eq!(
CompressionExtension::try_from(&path)?,
CompressionExtension::Tar
);
Ok(())
}
#[test]
fn gz() -> OuchResult<()> {
let path = PathBuf::from_str("passwords.tar.gz").unwrap();
assert_eq!(
CompressionExtension::try_from(&path)?,
CompressionExtension::Gzip
);
Ok(())
}
#[test]
fn lzma() -> OuchResult<()> {
let path = PathBuf::from_str("mygame.tar.lzma").unwrap();
assert_eq!(
CompressionExtension::try_from(&path)?,
CompressionExtension::Lzma
);
Ok(())
}
#[test]
fn bz() -> OuchResult<()> {
let path = PathBuf::from_str("songs.tar.bz").unwrap();
assert_eq!(
CompressionExtension::try_from(&path)?,
CompressionExtension::Bzip
);
Ok(())
}
}