Skip to content

Commit

Permalink
tests: add encode tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bconn98 committed Mar 3, 2024
1 parent 049e2cc commit ce794b3
Show file tree
Hide file tree
Showing 7 changed files with 535 additions and 47 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
34 changes: 28 additions & 6 deletions src/encode/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,15 @@ impl JsonEncoder {

impl Encode for JsonEncoder {
fn encode(&self, w: &mut dyn Write, record: &Record) -> anyhow::Result<()> {
self.encode_inner(w, Local::now(), record)
#[cfg(test)]
let time = DateTime::parse_from_rfc3339("2016-03-20T14:22:20.644420340-08:00")
.unwrap()
.with_timezone(&Local);

#[cfg(not(test))]
let time = Local::now();

self.encode_inner(w, time, record)
}
}

Expand Down Expand Up @@ -168,13 +176,17 @@ impl Deserialize for JsonEncoderDeserializer {
mod test {
#[cfg(feature = "chrono")]
use chrono::{DateTime, Local};
use log::Level;
use log::{Level, Record};

use super::*;

#[cfg(feature = "config_parsing")]
use crate::config::Deserializers;

use crate::encode::writer::simple::SimpleWriter;

#[test]
fn default() {
fn test_json_encode() {
let time = DateTime::parse_from_rfc3339("2016-03-20T14:22:20.644420340-08:00")
.unwrap()
.with_timezone(&Local);
Expand All @@ -184,16 +196,15 @@ mod test {
let file = "file";
let line = 100;
let message = "message";
let thread = "encode::json::test::default";
let thread = "encode::json::test::test_json_encode";
log_mdc::insert("foo", "bar");

let encoder = JsonEncoder::new();

let mut buf = vec![];
encoder
.encode_inner(
.encode(
&mut SimpleWriter(&mut buf),
time,
&Record::builder()
.level(level)
.target(target)
Expand Down Expand Up @@ -221,4 +232,15 @@ mod test {
);
assert_eq!(expected, String::from_utf8(buf).unwrap().trim());
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_cfg_deserializer() {
let json_cfg = JsonEncoderConfig { _p: () };

let deserializer = JsonEncoderDeserializer;

let res = deserializer.deserialize(json_cfg, &Deserializers::default());
assert!(res.is_ok());
}
}
77 changes: 77 additions & 0 deletions src/encode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,80 @@ impl<'a, W: Write + ?Sized> Write for &'a mut W {
<W as Write>::set_style(*self, style)
}
}

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

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

let pattern = "[{d(%Y-%m-%dT%H:%M:%S%.6f)} {h({l}):<5.5} {M}] {m}{n}".to_owned();

let mut config = BTreeMap::new();
config.insert(Value::String("pattern".to_owned()), Value::String(pattern));

let encoder_cfg = EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(config),
};

assert_de_tokens(
&encoder_cfg,
&[
Token::Struct {
name: "EncoderConfig",
len: 2,
},
Token::Str("kind"),
Token::Str("pattern"),
Token::Str("pattern"),
Token::Str("[{d(%Y-%m-%dT%H:%M:%S%.6f)} {h({l}):<5.5} {M}] {m}{n}"),
Token::StructEnd,
],
);

// No pattern defined, should fail to deserializez into a map
assert_de_tokens_error::<EncoderConfig>(
&[
Token::Struct {
name: "EncoderConfig",
len: 2,
},
Token::Str("kind"),
Token::Str("pattern"),
Token::Str("pattern"),
Token::StructEnd,
],
"deserialization did not expect this token: StructEnd",
);
}

#[test]
#[cfg(feature = "console_writer")]
fn test_set_console_writer_style() {
use super::*;
use crate::encode::writer::console::ConsoleWriter;

let w = match ConsoleWriter::stdout() {
Some(w) => w,
None => return,
};
let mut w = w.lock();

assert!(w
.set_style(
Style::new()
.text(Color::Red)
.background(Color::Blue)
.intense(true),
)
.is_ok());

w.set_style(&Style::new()).unwrap();
}
}
Loading

0 comments on commit ce794b3

Please sign in to comment.