Skip to content

Commit

Permalink
test: continuing
Browse files Browse the repository at this point in the history
  • Loading branch information
bconn98 committed Feb 25, 2024
1 parent 43973fb commit d145eb8
Show file tree
Hide file tree
Showing 3 changed files with 339 additions and 46 deletions.
236 changes: 196 additions & 40 deletions src/append/rolling_file/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,17 +367,53 @@ impl Deserialize for RollingFileAppenderDeserializer {

#[cfg(test)]
mod test {
use std::{
fs::File,
io::{Read, Write},
};

use super::*;
use crate::append::rolling_file::policy::Policy;

#[cfg(feature = "config_parsing")]
use serde_test::{assert_de_tokens, Token};

#[test]
#[cfg(feature = "config_parsing")]
fn test_policy_derser() {
use super::*;
use serde_value::Value;
use std::collections::BTreeMap;

assert_de_tokens(
&Policy {
kind: "compound".to_owned(),
config: Value::Map(BTreeMap::new()),
},
&[
Token::Struct {
name: "Policy",
len: 1,
},
Token::Str("kind"),
Token::Str("compound"),
Token::StructEnd,
],
);

assert_de_tokens(
&Policy {
kind: "compound".to_owned(),
config: Value::Map(BTreeMap::new()),
},
&[
Token::Struct {
name: "Policy",
len: 0,
},
Token::StructEnd,
],
);
}

#[test]
#[cfg(feature = "yaml_format")]
fn deserialize() {
fn test_deserialize_appenders() {
use crate::config::{Deserializers, RawConfig};

let dir = tempfile::tempdir().unwrap();
Expand Down Expand Up @@ -418,9 +454,21 @@ appenders:
}

#[derive(Debug)]
struct NopPolicy;
struct NopPostPolicy;

impl Policy for NopPostPolicy {
fn process(&self, _: &mut LogFile) -> anyhow::Result<()> {
Ok(())
}
fn is_pre_process(&self) -> bool {
false
}
}

#[derive(Debug)]
struct NopPrePolicy;

impl Policy for NopPolicy {
impl Policy for NopPrePolicy {
fn process(&self, _: &mut LogFile) -> anyhow::Result<()> {
Ok(())
}
Expand All @@ -430,48 +478,156 @@ appenders:
}

#[test]
fn append() {
fn test_append() {
use log::Level;

let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("append.log");
RollingFileAppender::builder()
let appender = RollingFileAppender::builder()
.append(true)
.build(&path, Box::new(NopPolicy))
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build(&path, Box::new(NopPrePolicy))
.unwrap();
assert!(path.exists());
File::create(&path).unwrap().write_all(b"hello").unwrap();

RollingFileAppender::builder()

let level = Level::Debug;
let target = "target";
let module_path = "module_path";
let file = "file";
let line = 100;
let message = "message";
log_mdc::insert("foo", "bar");

assert!(appender.append(
&Record::builder()
.level(level)
.target(target)
.module_path(Some(module_path))
.file(Some(file))
.line(Some(line))
.args(format_args!("{}", message))
.build()
).is_ok());

let appender = RollingFileAppender::builder()
.append(true)
.build(&path, Box::new(NopPolicy))
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build(&path, Box::new(NopPostPolicy))
.unwrap();
let mut contents = vec![];
File::open(&path)
.unwrap()
.read_to_end(&mut contents)
.unwrap();
assert_eq!(contents, b"hello");

assert!(appender.append(
&Record::builder()
.level(level)
.target(target)
.module_path(Some(module_path))
.file(Some(file))
.line(Some(line))
.args(format_args!("{}", message))
.build()
).is_ok());
}

#[test]
fn truncate() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("truncate.log");
RollingFileAppender::builder()
.append(false)
.build(&path, Box::new(NopPolicy))
.unwrap();
assert!(path.exists());
File::create(&path).unwrap().write_all(b"hello").unwrap();
fn test_logfile() {
let file = tempfile::tempdir().unwrap();
let file = file.path().join("foo.log");
let _ = std::fs::File::create(&file).unwrap();
let mut logfile = LogFile {
writer: &mut None,
path: file.as_path(),
len: 0,
};

RollingFileAppender::builder()
.append(false)
.build(&path, Box::new(NopPolicy))
.unwrap();
let mut contents = vec![];
File::open(&path)
.unwrap()
.read_to_end(&mut contents)
.unwrap();
assert_eq!(contents, b"");
assert_eq!(logfile.path(), file.as_path());
assert_eq!(logfile.len_estimate(), 0);

// No actions to take here, the writer becomes inaccessible but theres
// no getter to verify
logfile.roll();
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_deserializer() {
use super::*;
use crate::config::Deserializers;
use serde_value::Value;
use std::collections::BTreeMap;

let file = tempfile::tempdir().unwrap();
let file = file.path().join("foo.log");

let append_cfg = RollingFileAppenderConfig {
path: file.as_os_str().to_str().unwrap().to_owned(),
append: Some(true),
encoder: Some(EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(BTreeMap::new()),
}),
policy: Policy {
kind: "compound".to_owned(),
config: Value::Map({
let mut map = BTreeMap::new();
map.insert(
Value::String("trigger".to_owned()),
Value::Map({
let mut map = BTreeMap::new();
map.insert(
Value::String("kind".to_owned()),
Value::String("size".to_owned()),
);
map.insert(
Value::String("limit".to_owned()),
Value::String("1mb".to_owned()),
);
map
}),
);
map.insert(
Value::String("roller".to_owned()),
Value::Map({
let mut map = BTreeMap::new();
map.insert(
Value::String("kind".to_owned()),
Value::String("fixed_window".to_owned()),
);
map.insert(Value::String("base".to_owned()), Value::I32(1));
map.insert(Value::String("count".to_owned()), Value::I32(5));
map.insert(
Value::String("pattern".to_owned()),
Value::String("logs/test.{}.log".to_owned()),
);
map
}),
);
map
}),
},
};

let deserializer = RollingFileAppenderDeserializer;

let res = deserializer.deserialize(append_cfg, &Deserializers::default());
assert!(res.is_ok());
}

#[test]
fn test_logwriter() {
let file = tempfile::tempdir().unwrap();
let dir = file.path();
let file_path = dir.join("writer.log");
let file = File::create(&file_path).unwrap();
let buf_writer = BufWriter::new(file);
let mut log_writer = LogWriter {
file: buf_writer,
len: 0,
};

let contents = fs::read_to_string(&file_path).unwrap();
assert!(contents.is_empty());
assert_eq!(log_writer.write(b"test").unwrap(), 4);
assert!(log_writer.flush().is_ok());
let contents = fs::read_to_string(file_path).unwrap();
assert!(contents.contains("test"));
}
}
120 changes: 120 additions & 0 deletions src/append/rolling_file/policy/compound/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,123 @@ impl Deserialize for CompoundPolicyDeserializer {
Ok(Box::new(CompoundPolicy::new(trigger, roller)))
}
}

#[cfg(test)]
mod test {
use self::{roll::delete::DeleteRoller, trigger::size::SizeTrigger};

use super::*;

#[cfg(feature = "config_parsing")]
use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};

#[test]
#[cfg(feature = "config_parsing")]
fn test_trigger_deser() {
assert_de_tokens(
&Trigger {
kind: "size".to_owned(),
config: Value::Map({
let mut map = BTreeMap::new();
map.insert(Value::String("limit".to_owned()), Value::U64(1024));
map
}),
},
&[
Token::Struct {
name: "Trigger",
len: 2,
},
Token::Str("kind"),
Token::Str("size"),
Token::Str("limit"),
Token::U64(1024),
Token::StructEnd,
],
);

assert_de_tokens_error::<Trigger>(
&[
Token::Struct {
name: "Trigger",
len: 1,
},
Token::Str("knd"),
Token::Str("size"),
Token::StructEnd,
],
"missing field `kind`",
);
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_roller_deser() {
assert_de_tokens(
&Roller {
kind: "delete".to_owned(),
config: Value::Map(BTreeMap::new()),
},
&[
Token::Struct {
name: "Roller",
len: 1,
},
Token::Str("kind"),
Token::Str("delete"),
Token::StructEnd,
],
);

assert_de_tokens_error::<Roller>(
&[
Token::Struct {
name: "Roller",
len: 1,
},
Token::Str("knd"),
Token::Str("delete"),
Token::StructEnd,
],
"missing field `kind`",
);
}

#[test]
fn test_pre_process() {
let trigger = SizeTrigger::new(1024);
let roller = DeleteRoller::new();
let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));

assert!(!policy.is_pre_process());
}

#[test]
fn test_process() {
let trigger = SizeTrigger::new(1024);
let roller = DeleteRoller::new();
let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));

// Test don't roll
let file = tempfile::tempdir().unwrap();
let file = file.path().join("foo.log");
let _ = std::fs::File::create(&file).unwrap();
let mut logfile = LogFile {
writer: &mut None,
path: file.as_path(),
len: 0,
};
assert!(policy.process(&mut logfile).is_ok());

// Test roll
let file = tempfile::tempdir().unwrap();
let file = file.path().join("foo2.log");
let _ = std::fs::File::create(&file).unwrap();
let mut logfile = LogFile {
writer: &mut None,
path: file.as_path(),
len: 2048,
};
assert!(policy.process(&mut logfile).is_ok());
}
}
Loading

0 comments on commit d145eb8

Please sign in to comment.