Skip to content

Commit

Permalink
add cli test
Browse files Browse the repository at this point in the history
  • Loading branch information
s1rius committed Aug 13, 2023
1 parent f0acf0c commit dc03108
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 100 deletions.
4 changes: 2 additions & 2 deletions examples/hello_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ fn read_log_file_rewrite() {

let mut writer = BufWriter::new(plaintext_log);

let mut compression = EZLogger::create_compress(&log_config);
let mut cryptor = EZLogger::create_cryptor(&log_config).unwrap();
let mut compression = ezlog::create_compress(&log_config);
let mut cryptor = ezlog::create_cryptor(&log_config).unwrap();
let header = Header::decode(&mut cursor).unwrap();
ezlog::decode::decode_body_and_write(
&mut cursor,
Expand Down
13 changes: 10 additions & 3 deletions ezlog-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
[package]
name = "ezlog-cli"
version = "0.2.0-beta.2"
version = "0.2.0-beta.4"
edition = "2021"
description = "EZLog command line tool"
homepage = "https://github.com/s1rius/ezlog"
repository = "https://github.com/s1rius/ezlog"
license = "MIT OR Apache-2.0"
keywords = ["ezlog", "cli"]
exclude = ["/resources"]

[dependencies]
ezlog = { version = "0.2.0-beta.2", path = "../ezlog-core", features = ["decode"] }
clap = { version = "4.0.8", features = ["derive"] }
clap = { version = "4.3.21", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json = "1.0"
anyhow = "1.0.72"
assert_cmd = "2.0.12"
escargot = "0.5.8"

[dev-dependencies]
dirs = "5.0"
Binary file added ezlog-cli/resources/test/test.mmap
Binary file not shown.
121 changes: 71 additions & 50 deletions ezlog-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,11 @@ use std::{
path::PathBuf,
};

use anyhow::Context;
use clap::Parser;
pub use ezlog::*;
use serde::{Deserialize, Serialize};

macro_rules! unwrap_or_return {
( $e:expr, $e1:expr ) => {
match $e {
Ok(x) => x,
Err(e) => {
$e1;
println!("{}", e);
return;
}
}
};
}

macro_rules! some_or_return {
( $e:expr, $e1:expr ) => {
match $e {
Some(x) => x,
None => {
$e1;
return;
}
}
};
}

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Cli {
Expand Down Expand Up @@ -72,7 +48,7 @@ struct Config {
nonce: String,
}

pub fn main() {
pub fn main() -> anyhow::Result<()> {
let cli = Cli::parse();

if cli.debug {
Expand All @@ -81,28 +57,34 @@ pub fn main() {
println!("{:?}", cli);
}

let input = some_or_return!(cli.input.as_deref(), println!("-i input file must set"));
let input = cli
.input
.as_deref()
.with_context(|| "-i input file must be set".to_string())?;

let input_file = unwrap_or_return!(
OpenOptions::new().read(true).open(input),
println!("-i input file open error")
);
let input_file = OpenOptions::new()
.read(true)
.write(true)
.open(input)
.with_context(|| "input file must valid".to_string())?;

let output = some_or_return!(cli.output.as_deref(), println!("-o output file must set"));
let output = cli
.output
.as_deref()
.with_context(|| "-o output file must be set".to_string())?;

let output_file = unwrap_or_return!(
OpenOptions::new().write(true).create(true).open(output),
println!("-o output file create error")
);
let output_file = OpenOptions::new()
.write(true)
.create(true)
.open(output)
.with_context(|| "output file create error".to_string())?;

let mut buf = Vec::<u8>::new();
let mut reader = BufReader::new(input_file);
reader.read_to_end(&mut buf).unwrap();
let mut cursor = Cursor::new(buf);
let header = unwrap_or_return!(
ezlog::Header::decode(&mut cursor),
println!("log file can not be recognized")
);
let header =
ezlog::Header::decode(&mut cursor).with_context(|| "header decode error".to_string())?;

if cli.debug {
println!();
Expand All @@ -119,10 +101,8 @@ pub fn main() {
.read_to_string(&mut json)
.is_ok()
{
let config: Config = unwrap_or_return!(
serde_json::from_str(&json),
println!("parse config json error")
);
let config: Config = serde_json::from_str(&json)
.with_context(|| "config file is not valid".to_string())?;
key = config.key.as_bytes().to_vec();
nonce = config.nonce.as_bytes().to_vec();

Expand Down Expand Up @@ -152,11 +132,9 @@ pub fn main() {
.cipher_nonce(nonce)
.build();

let compression = EZLogger::create_compress(&config);
let decryptor = unwrap_or_return!(
EZLogger::create_cryptor(&config),
println!("create cryptor error")
);
let compression = ezlog::create_compress(&config);
let decryptor =
ezlog::create_cryptor(&config).with_context(|| "create cryptor error".to_string())?;

let mut plain_text_write = BufWriter::new(output_file);

Expand All @@ -169,11 +147,54 @@ pub fn main() {
&header,
)
.unwrap();
Ok(())
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use assert_cmd::prelude::{OutputAssertExt, OutputOkExt};

#[test]
fn test_help() {
escargot::CargoBuild::new()
.bin("ezlog-cli")
.current_release()
.current_target()
.run()
.unwrap()
.command()
.arg("--help")
.unwrap().assert().success();
}

#[test]
fn test_decode() {}
fn test_decode() {
let bin_under_test = escargot::CargoBuild::new()
.bin("ezlog-cli")
.current_release()
.current_target()
.run()
.unwrap();

let mut input_file = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
input_file.push("resources/test/test.mmap");

let mut output_file = dirs::cache_dir().unwrap();
output_file.push("1.log");

let cmd = bin_under_test
.command()
.arg("-i")
.arg(input_file.into_os_string())
.arg("-o")
.arg(output_file.into_os_string())
.arg("-k")
.arg("an example very very secret key.")
.arg("-n")
.arg("unique nonce")
.unwrap();
cmd.assert().success();
}
}
2 changes: 2 additions & 0 deletions ezlog-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ pub use self::init::InitBuilder;
pub use self::init::MsgHandler;
pub use self::logger::EZLogger;
pub use self::logger::Header;
pub use self::logger::create_cryptor;
pub use self::logger::create_compress;
pub use self::recorder::EZRecord;
pub use self::recorder::EZRecordBuilder;

Expand Down
90 changes: 45 additions & 45 deletions ezlog-core/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,49 @@ pub(crate) fn encode_content(mut buf: Vec<u8>) -> Result<Vec<u8>> {
Ok(chunk)
}

#[allow(deprecated)]
pub fn create_cryptor(config: &EZLogConfig) -> Result<Option<Box<dyn Cryptor>>> {
if let Some(key) = &config.cipher_key {
if let Some(nonce) = &config.cipher_nonce {
#[warn(unreachable_patterns)]
match config.cipher {
#[cfg(feature = "decode")]
CipherKind::AES128GCM => {
let encryptor = Aes128Gcm::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
#[cfg(feature = "decode")]
CipherKind::AES256GCM => {
let encryptor = Aes256Gcm::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::AES128GCMSIV => {
let encryptor = Aes128GcmSiv::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::AES256GCMSIV => {
let encryptor = Aes256GcmSiv::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::NONE => Ok(None),
unknown => Err(LogError::Crypto(format!("unknown cryption {}", unknown))),
}
} else {
Ok(None)
}
} else {
Ok(None)
}
}

pub fn create_compress(config: &EZLogConfig) -> Option<Box<dyn Compress>> {
match config.compress {
CompressKind::ZLIB => Some(Box::new(ZlibCodec::new(&config.compress_level))),
CompressKind::NONE => None,
CompressKind::UNKNOWN => None,
}
}

pub struct EZLogger {
pub(crate) config: Rc<EZLogConfig>,
pub(crate) appender: EZAppender,
Expand All @@ -53,8 +96,8 @@ impl EZLogger {
let rc_conf = Rc::new(config);
let mut appender = EZAppender::new(Rc::clone(&rc_conf))?;
appender.check_config_rolling(&rc_conf)?;
let compression = EZLogger::create_compress(&rc_conf);
let cryptor = EZLogger::create_cryptor(&rc_conf)?;
let compression = create_compress(&rc_conf);
let cryptor = create_cryptor(&rc_conf)?;

Ok(Self {
config: Rc::clone(&rc_conf),
Expand All @@ -64,49 +107,6 @@ impl EZLogger {
})
}

#[allow(deprecated)]
pub fn create_cryptor(config: &EZLogConfig) -> Result<Option<Box<dyn Cryptor>>> {
if let Some(key) = &config.cipher_key {
if let Some(nonce) = &config.cipher_nonce {
#[warn(unreachable_patterns)]
match config.cipher {
#[cfg(feature = "decode")]
CipherKind::AES128GCM => {
let encryptor = Aes128Gcm::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
#[cfg(feature = "decode")]
CipherKind::AES256GCM => {
let encryptor = Aes256Gcm::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::AES128GCMSIV => {
let encryptor = Aes128GcmSiv::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::AES256GCMSIV => {
let encryptor = Aes256GcmSiv::new(key, nonce)?;
Ok(Some(Box::new(encryptor)))
}
CipherKind::NONE => Ok(None),
unknown => Err(LogError::Crypto(format!("unknown cryption {}", unknown))),
}
} else {
Ok(None)
}
} else {
Ok(None)
}
}

pub fn create_compress(config: &EZLogConfig) -> Option<Box<dyn Compress>> {
match config.compress {
CompressKind::ZLIB => Some(Box::new(ZlibCodec::new(&config.compress_level))),
CompressKind::NONE => None,
CompressKind::UNKNOWN => None,
}
}

pub(crate) fn append(&mut self, record: &EZRecord) -> Result<()> {
if record.content().len() > self.config.max_size as usize / 2 {
let mut e: Option<LogError> = None;
Expand Down

0 comments on commit dc03108

Please sign in to comment.