Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Appender tests #360

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ fnv = "1.0"
humantime = { version = "2.1", optional = true }
log = { version = "0.4.20", features = ["std"] }
log-mdc = { version = "0.1", optional = true }
serde = { version = "1.0", optional = true, features = ["derive"] }
serde = { version = "1.0.196", optional = true, features = ["derive"] }
serde-value = { version = "0.7", optional = true }
thread-id = { version = "4", optional = true }
typemap-ors = { version = "1.0.0", optional = true }
serde_json = { version = "1.0", optional = true }
serde_yaml = { version = "0.9", optional = true }
toml = { version = "0.8", optional = true }
toml = { version = "<0.8.10", optional = true }
parking_lot = { version = "0.12.0", optional = true }
rand = { version = "0.8", optional = true}
thiserror = "1.0.15"
Expand All @@ -88,6 +88,7 @@ streaming-stats = "0.2.3"
humantime = "2.1"
tempfile = "3.8"
mock_instant = "0.3"
serde_test = "1.0.176"

[[example]]
name = "json_logger"
Expand Down
114 changes: 114 additions & 0 deletions src/append/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,117 @@ impl Deserialize for ConsoleAppenderDeserializer {
Ok(Box::new(appender.build()))
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::encode::Write;

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

// Build a std out appender
let appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stdout)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

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

// No op, but test coverage :)
appender.flush();
}

#[test]
fn test_appender_builder() {
// Build a std out appender
let _appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stdout)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

// Build a std err appender
let _appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stderr)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

// Build a default encoder appender
let _appender = ConsoleAppender::builder()
.tty_only(true)
.target(Target::Stderr)
.build();
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are we testing here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've had recent experience where just creating the object would have discovered a bug causing segmentation faults. In that case it was the cleanup that occurs afterwards that caused the fault. Here we hit all aspects of the builder to ensure they don't enter an invalid state


#[test]
#[cfg(feature = "config_parsing")]
fn test_config_deserializer() {
use crate::{config::Deserializers, encode::EncoderConfig};
use serde_value::Value;
use std::collections::BTreeMap;
let deserializer = ConsoleAppenderDeserializer;

let targets = vec![ConfigTarget::Stdout, ConfigTarget::Stderr];

for target in targets {
let console_cfg = ConsoleAppenderConfig {
target: Some(target),
encoder: Some(EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(BTreeMap::new()),
}),
tty_only: Some(true),
};
assert!(deserializer
.deserialize(console_cfg, &Deserializers::default())
.is_ok());
}
}

fn write_test(mut writer: WriterLock) {
use std::io::Write;

assert_eq!(writer.write(b"Write log\n").unwrap(), 10);
assert!(writer.set_style(&Style::new()).is_ok());
assert!(writer.write_all(b"Write All log\n").is_ok());
assert!(writer.write_fmt(format_args!("{} \n", "normal")).is_ok());
assert!(writer.flush().is_ok());
}

#[test]
fn test_tty_writer() {
// Note that this fails in GitHub Actions and therefore does not
// show as covered.
let w = match ConsoleWriter::stdout() {
Some(w) => w,
None => return,
};

let tty = Writer::Tty(w);
assert!(tty.is_tty());

write_test(tty.lock());
}

#[test]
fn test_raw_writer() {
let raw = Writer::Raw(StdWriter::stdout());
assert!(!raw.is_tty());
write_test(raw.lock());
}
}
61 changes: 57 additions & 4 deletions src/append/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ mod test {
use super::*;

#[test]
fn create_directories() {
fn test_create_directories() {
let tempdir = tempfile::tempdir().unwrap();

FileAppender::builder()
Expand All @@ -173,11 +173,64 @@ mod test {
}

#[test]
fn append_false() {
fn test_append_trait() {
use log::Level;

let tempdir = tempfile::tempdir().unwrap();
FileAppender::builder()
.append(false)
let appender = FileAppender::builder()
.build(tempdir.path().join("foo.log"))
.unwrap();

log_mdc::insert("foo", "bar");
let res = appender.append(
&Record::builder()
.level(Level::Debug)
.target("target")
.module_path(Some("module_path"))
.file(Some("file"))
.line(Some(100))
.args(format_args!("{}", "message"))
.build(),
);
assert!(res.is_ok());

appender.flush();
}

#[test]
fn test_appender_builder() {
let append_choices = vec![true, false];
let tempdir = tempfile::tempdir().unwrap();

for do_append in append_choices {
// No actionable test
FileAppender::builder()
.append(do_append)
.build(tempdir.path().join("foo.log"))
.unwrap();
}
}

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

let tempdir = tempfile::tempdir().unwrap();
let file_cfg = FileAppenderConfig {
path: tempdir.path().join("foo.log").to_str().unwrap().to_owned(),
encoder: Some(EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(BTreeMap::new()),
}),
append: Some(true),
};

let deserializer = FileAppenderDeserializer;

let res = deserializer.deserialize(file_cfg, &Deserializers::default());
assert!(res.is_ok());
}
}
60 changes: 59 additions & 1 deletion src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,15 @@ impl<'de> Deserialize<'de> for AppenderConfig {

#[cfg(test)]
mod test {
#[cfg(feature = "config_parsing")]
use super::*;

#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
use std::env::{set_var, var};

#[test]
#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
fn expand_env_vars_tests() {
fn test_expand_env_vars() {
set_var("HELLO_WORLD", "GOOD BYE");
#[cfg(not(target_os = "windows"))]
let test_cases = vec![
Expand Down Expand Up @@ -250,4 +253,59 @@ mod test {
assert_eq!(res, expected)
}
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_config_deserialize() {
use std::collections::BTreeMap;

use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
use serde_value::Value;

use crate::filter::FilterConfig;

let appender = AppenderConfig {
kind: "file".to_owned(),
filters: vec![FilterConfig {
kind: "threshold".to_owned(),
config: Value::Map({
let mut map = BTreeMap::new();
map.insert(
Value::String("level".to_owned()),
Value::String("error".to_owned()),
);
map
}),
}],
config: Value::Map(BTreeMap::new()),
};

let mut cfg = vec![
Token::Struct {
name: "AppenderConfig",
len: 3,
},
Token::Str("kind"),
Token::Str("file"),
Token::Str("filters"),
Token::Seq { len: Some(1) },
Token::Struct {
name: "FilterConfig",
len: 2,
},
Token::Str("kind"),
Token::Str("threshold"),
Token::Str("level"),
Token::Str("error"),
Token::StructEnd,
Token::SeqEnd,
Token::StructEnd,
];

assert_de_tokens(&appender, &cfg);

// Intentional typo on expected field
cfg[1] = Token::Str("kid");
assert_de_tokens_error::<AppenderConfig>(&cfg, "missing field `kind`");
}
}
Loading
Loading