Skip to content

Commit

Permalink
Add more test utils to reduce boilerplate code
Browse files Browse the repository at this point in the history
  • Loading branch information
SpriteOvO committed Jul 13, 2023
1 parent 36bc937 commit 4fad447
Show file tree
Hide file tree
Showing 14 changed files with 163 additions and 149 deletions.
33 changes: 16 additions & 17 deletions spdlog/benches/compare_with_cpp_spdlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ use spdlog::{
};
use test::black_box;

include!(concat!(
env!("OUT_DIR"),
"/test_utils/common_for_integration_test.rs"
));
use test_utils::*;

static LOGS_PATH: Lazy<PathBuf> = Lazy::new(|| {
let path = common::BENCH_LOGS_PATH.join("compare_with_cpp_spdlog");
fs::create_dir_all(&path).unwrap();
Expand All @@ -35,21 +41,20 @@ fn bench_threaded_logging(threads: usize, iters: usize) {
info!("Multi threaded: {} threads, {} messages", threads, iters);
info!("**********************************************************************");

let logger = Logger::builder()
.sink(Arc::new(
let logger = build_test_logger(|b| {
b.sink(Arc::new(
FileSink::builder()
.path(LOGS_PATH.join("FileSink.log"))
.truncate(true)
.build()
.unwrap(),
))
.name("basic_mt")
.build()
.unwrap();
});
bench_mt(logger, threads, iters);

let logger = Logger::builder()
.sink(Arc::new(
let logger = build_test_logger(|b| {
b.sink(Arc::new(
RotatingFileSink::builder()
.base_path(LOGS_PATH.join("RotatingFileSink_FileSize.log"))
.rotation_policy(RotationPolicy::FileSize(FILE_SIZE))
Expand All @@ -58,28 +63,22 @@ fn bench_threaded_logging(threads: usize, iters: usize) {
.unwrap(),
))
.name("rotating_mt")
.build()
.unwrap();
});
bench_mt(logger, threads, iters);

let logger = Logger::builder()
.sink(Arc::new(
let logger = build_test_logger(|b| {
b.sink(Arc::new(
RotatingFileSink::builder()
.base_path(LOGS_PATH.join("RotatingFileSink_Daily.log"))
.rotation_policy(RotationPolicy::Daily { hour: 0, minute: 0 })
.build()
.unwrap(),
))
.name("daily_mt")
.build()
.unwrap();
});
bench_mt(logger, threads, iters);

let logger = Logger::builder()
.name("level-off")
.level_filter(LevelFilter::Off)
.build()
.unwrap();
let logger = build_test_logger(|b| b.name("level-off").level_filter(LevelFilter::Off));
bench_mt(logger, threads, iters);
}

Expand Down
46 changes: 19 additions & 27 deletions spdlog/benches/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ use std::{cell::RefCell, sync::Arc};
use spdlog::{
formatter::{pattern, Formatter, FullFormatter, Pattern, PatternFormatter},
prelude::*,
sink::{Sink, WriteSink},
sink::Sink,
Record, StringBuf,
};
use test::Bencher;

include!(concat!(
env!("OUT_DIR"),
"/test_utils/common_for_integration_test.rs"
));
use test_utils::*;

#[derive(Clone)]
struct BenchSink<F> {
formatter: F,
Expand Down Expand Up @@ -61,7 +67,7 @@ impl<F: Formatter> Sink for BenchSink<F> {

fn bench_formatter(bencher: &mut Bencher, formatter: impl Formatter + 'static) {
let bench_sink = Arc::new(BenchSink::new(formatter));
let logger = Logger::builder().sink(bench_sink).build().unwrap();
let logger = build_test_logger(|b| b.sink(bench_sink));

bencher.iter(|| info!(logger: logger, "payload"));
}
Expand All @@ -79,34 +85,20 @@ fn bench_1_full_formatter(bencher: &mut Bencher) {
fn bench_2_full_pattern(bencher: &mut Bencher) {
let pattern = pattern!("[{date} {time}.{millisecond}] [{level}] {payload}{eol}");

let full_formatter = Arc::new(
WriteSink::builder()
.formatter(Box::new(FullFormatter::new()))
.target(Vec::new())
.build()
.unwrap(),
);

let full_pattern = Arc::new(
WriteSink::builder()
.formatter(Box::new(PatternFormatter::new(pattern.clone())))
.target(Vec::new())
.build()
.unwrap(),
);

let combination = Logger::builder()
.sink(full_formatter.clone())
.sink(full_pattern.clone())
.build()
.unwrap();
let full_formatter = Arc::new(StringSink::with(|b| {
b.formatter(Box::new(FullFormatter::new()))
}));

let full_pattern = Arc::new(StringSink::with(|b| {
b.formatter(Box::new(PatternFormatter::new(pattern.clone())))
}));

let combination =
build_test_logger(|b| b.sink(full_formatter.clone()).sink(full_pattern.clone()));

info!(logger: combination, "test payload");

assert_eq!(
String::from_utf8(full_formatter.clone_target()).unwrap(),
String::from_utf8(full_pattern.clone_target()).unwrap()
);
assert_eq!(full_formatter.clone_string(), full_pattern.clone_string());

bench_pattern(bencher, pattern)
}
Expand Down
20 changes: 11 additions & 9 deletions spdlog/benches/spdlog_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ use spdlog::{
};
use test::Bencher;

include!(concat!(
env!("OUT_DIR"),
"/test_utils/common_for_integration_test.rs"
));
use test_utils::*;

required_multi_thread_feature!();

static LOGS_PATH: Lazy<PathBuf> = Lazy::new(|| {
Expand Down Expand Up @@ -74,11 +80,10 @@ impl Mode {
fn bench_any(bencher: &mut Bencher, mode: Mode, sink: Arc<dyn Sink>) {
sink.set_error_handler(Some(|err| panic!("an error occurred: {err}")));

let mut logger_builder = Logger::builder();
logger_builder
.error_handler(mode.error_handler())
.sink(mode.final_sink(sink));
let logger = logger_builder.build().unwrap();
let logger = build_test_logger(|b| {
b.error_handler(mode.error_handler())
.sink(mode.final_sink(sink))
});

bencher.iter(|| info!(logger: logger, bench_log_message!()))
}
Expand Down Expand Up @@ -133,10 +138,7 @@ fn bench_4_rotating_daily(bencher: &mut Bencher) {

#[bench]
fn bench_5_level_off(bencher: &mut Bencher) {
let logger = Logger::builder()
.level_filter(LevelFilter::Off)
.build()
.unwrap();
let logger = build_test_logger(|b| b.level_filter(LevelFilter::Off));

bencher.iter(|| info!(logger: logger, bench_log_message!()))
}
4 changes: 4 additions & 0 deletions spdlog/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ fn generate_code_test_utils() -> Result<(), Box<dyn Error>> {
.map(|line| format!("# {}\n", line))
.collect::<String>(),
)?;
write_generated_code(
out_dir.join("common_for_integration_test.rs"),
format!("#[allow(dead_code)]\nmod test_utils {{\n{}\n}}", input),
)?;
write_generated_code(
out_dir.join("common_for_unit_test.rs"),
input.replace("spdlog::", "crate::"),
Expand Down
10 changes: 5 additions & 5 deletions spdlog/src/formatter/pattern_formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ use crate::{
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// # String::from_utf8(sink.clone_target()).unwrap(),
/// # sink.clone_string(),
/// /* Output */ "[info] Interesting log message"
/// # );
/// ```
Expand All @@ -106,7 +106,7 @@ use crate::{
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// # String::from_utf8(sink.clone_target()).unwrap(),
/// # sink.clone_string(),
/// /* Output */ "[{escaped}] Interesting log message"
/// # );
/// ```
Expand Down Expand Up @@ -135,7 +135,7 @@ use crate::{
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// # String::from_utf8(sink.clone_target()).unwrap(),
/// # sink.clone_string(),
/// /* Output */ "[info] Interesting log message"
/// // ^^^^^^ <- style range
/// # );
Expand Down Expand Up @@ -182,7 +182,7 @@ use crate::{
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// # String::from_utf8(sink.clone_target()).unwrap(),
/// # sink.clone_string(),
/// /* Output */ "[info] Interesting log message - My own pattern"
/// # );
/// ```
Expand Down Expand Up @@ -251,7 +251,7 @@ use crate::{
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// # String::from_utf8(sink.clone_target()).unwrap(),
/// # sink.clone_string(),
/// /* Output */ "[info] Interesting log message - 0 1 2"
/// # );
/// ```
Expand Down
7 changes: 1 addition & 6 deletions spdlog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -726,12 +726,7 @@ mod tests {
fn test_default_logger() {
let test_sink = Arc::new(CounterSink::new());

let test_logger = Arc::new(
test_logger_builder()
.sink(test_sink.clone())
.build()
.unwrap(),
);
let test_logger = Arc::new(build_test_logger(|b| b.sink(test_sink.clone())));
let empty_logger = Arc::new(Logger::builder().build().unwrap());

set_default_logger(empty_logger.clone());
Expand Down
5 changes: 2 additions & 3 deletions spdlog/src/log_crate_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,8 @@ mod tests {
log::set_max_level(log::LevelFilter::Debug);

let sink = Arc::new(CounterSink::new());
crate::log_crate_proxy().set_logger(Some(Arc::new(
test_logger_builder().sink(sink.clone()).build().unwrap(),
)));
crate::log_crate_proxy()
.set_logger(Some(Arc::new(build_test_logger(|b| b.sink(sink.clone())))));

assert_eq!(sink.log_count(), 0);

Expand Down
23 changes: 7 additions & 16 deletions spdlog/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,11 +302,12 @@ impl Logger {
/// # Examples
///
/// ```
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
/// # use std::sync::Arc;
/// # use spdlog::{prelude::*, sink::WriteSink};
/// # use spdlog::prelude::*;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let test_sink = Arc::new(WriteSink::builder().target(vec![]).build().unwrap());
/// # let test_sink = Arc::new(test_utils::StringSink::new());
/// let old: Arc<Logger> = /* ... */
/// # Arc::new(Logger::builder().build().unwrap());
/// // Fork from an existing logger and add a new sink.
Expand All @@ -318,9 +319,9 @@ impl Logger {
///
/// # info!(logger: new, "first line");
/// info!(logger: new, "this record will be written to `new_sink`");
/// # assert_eq!(String::from_utf8(test_sink.clone_target()).unwrap().lines().count(), 2);
/// # assert_eq!(test_sink.clone_string().lines().count(), 2);
/// info!(logger: old, "this record will not be written to `new_sink`");
/// # assert_eq!(String::from_utf8(test_sink.clone_target()).unwrap().lines().count(), 2);
/// # assert_eq!(test_sink.clone_string().lines().count(), 2);
/// # Ok(()) }
/// ```
pub fn fork_with<F>(self: &Arc<Self>, modifier: F) -> Result<Arc<Self>>
Expand Down Expand Up @@ -789,12 +790,7 @@ mod tests {
#[test]
fn fork_logger() {
let test_sink = (Arc::new(CounterSink::new()), Arc::new(CounterSink::new()));
let logger = Arc::new(
test_logger_builder()
.sink(test_sink.0.clone())
.build()
.unwrap(),
);
let logger = Arc::new(build_test_logger(|b| b.sink(test_sink.0.clone())));

assert!(logger.name().is_none());
assert_eq!(test_sink.0.log_count(), 0);
Expand Down Expand Up @@ -847,12 +843,7 @@ mod tests {
.is_none());

let test_sink = (Arc::new(CounterSink::new()), Arc::new(CounterSink::new()));
let old = Arc::new(
test_logger_builder()
.sink(test_sink.0.clone())
.build()
.unwrap(),
);
let old = Arc::new(build_test_logger(|b| b.sink(test_sink.0.clone())));
old.set_flush_period(Some(Duration::from_secs(1)));
std::thread::sleep(Duration::from_millis(1250));

Expand Down
21 changes: 9 additions & 12 deletions spdlog/src/sink/async_sink/async_pool_sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,17 +239,16 @@ mod tests {
fn default_thread_pool() {
let counter_sink = Arc::new(CounterSink::new());
let build_logger = || {
Logger::builder()
.sink(Arc::new(
build_test_logger(|b| {
b.sink(Arc::new(
AsyncPoolSink::builder()
.sink(counter_sink.clone())
.build()
.unwrap(),
))
.level_filter(LevelFilter::All)
.flush_level_filter(LevelFilter::MoreSevereEqual(Level::Error))
.build()
.unwrap()
})
};

assert_eq!(counter_sink.log_count(), 0);
Expand Down Expand Up @@ -288,8 +287,8 @@ mod tests {
fn custom_thread_pool() {
let counter_sink = Arc::new(CounterSink::new());
let thread_pool = Arc::new(ThreadPool::builder().build().unwrap());
let logger = Logger::builder()
.sink(Arc::new(
let logger = build_test_logger(|b| {
b.sink(Arc::new(
AsyncPoolSink::builder()
.sink(counter_sink.clone())
.thread_pool(thread_pool)
Expand All @@ -298,8 +297,7 @@ mod tests {
))
.level_filter(LevelFilter::All)
.flush_level_filter(LevelFilter::MoreSevereEqual(Level::Error))
.build()
.unwrap();
});

assert_eq!(counter_sink.log_count(), 0);
assert_eq!(counter_sink.flush_count(), 0);
Expand All @@ -326,8 +324,8 @@ mod tests {
// The default thread pool is not used here to avoid race when tests are run in
// parallel.
let thread_pool = Arc::new(ThreadPool::builder().build().unwrap());
let logger = Logger::builder()
.sink(Arc::new(
let logger = build_test_logger(|b| {
b.sink(Arc::new(
AsyncPoolSink::builder()
.sink(counter_sink.clone())
.thread_pool(thread_pool)
Expand All @@ -336,8 +334,7 @@ mod tests {
))
.level_filter(LevelFilter::All)
.flush_level_filter(LevelFilter::MoreSevereEqual(Level::Warn))
.build()
.unwrap();
});

assert_eq!(counter_sink.log_count(), 0);
assert_eq!(counter_sink.flush_count(), 0);
Expand Down
Loading

0 comments on commit 4fad447

Please sign in to comment.