Skip to content

Commit d002490

Browse files
committed
Generate code to reduce duplicate boilerplate code for testing
1 parent 598fe1f commit d002490

File tree

6 files changed

+126
-55
lines changed

6 files changed

+126
-55
lines changed

spdlog/build.rs

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,61 @@
1+
use std::{
2+
env,
3+
error::Error,
4+
fs,
5+
path::{Path, PathBuf},
6+
};
7+
18
use rustc_version::{version_meta, Channel};
29

3-
fn main() {
4-
// Set cfg flags depending on release channel
5-
let channel = match version_meta().unwrap().channel {
10+
fn main() -> Result<(), Box<dyn Error>> {
11+
set_cfg_channel()?;
12+
generate_code_test_utils()?;
13+
Ok(())
14+
}
15+
16+
// Set cfg flags depending on release channel
17+
fn set_cfg_channel() -> Result<(), Box<dyn Error>> {
18+
let channel = match version_meta()?.channel {
619
Channel::Stable => "CHANNEL_STABLE",
720
Channel::Beta => "CHANNEL_BETA",
821
Channel::Nightly => "CHANNEL_NIGHTLY",
922
Channel::Dev => "CHANNEL_DEV",
1023
};
11-
println!("cargo:rustc-cfg={}", channel)
24+
println!("cargo:rustc-cfg={}", channel);
25+
Ok(())
26+
}
27+
28+
// Generate test utils for unit tests, integration tests and doc tests
29+
//
30+
// Workaround for the rustdoc bug https://github.com/rust-lang/rust/issues/67295
31+
fn generate_code_test_utils() -> Result<(), Box<dyn Error>> {
32+
let out_dir = PathBuf::from(env::var("OUT_DIR")?).join("test_utils");
33+
if !out_dir.is_dir() {
34+
fs::create_dir(&out_dir)?;
35+
}
36+
37+
let input = fs::read_to_string("src/test_utils/common.rs")?;
38+
39+
write_generated_code(
40+
out_dir.join("common_for_doc_test.rs"),
41+
format!("mod test_utils {{\n{}\n}}", input)
42+
.lines()
43+
.map(|line| format!("# {}\n", line))
44+
.collect::<String>(),
45+
)?;
46+
write_generated_code(
47+
out_dir.join("common_for_unit_test.rs"),
48+
input.replace("spdlog::", "crate::"),
49+
)?;
50+
51+
Ok(())
52+
}
53+
54+
fn write_generated_code(
55+
path: impl AsRef<Path>,
56+
contents: impl AsRef<[u8]>,
57+
) -> Result<(), Box<dyn Error>> {
58+
println!("cargo:rerun-if-changed={}", path.as_ref().display());
59+
fs::write(path, contents)?;
60+
Ok(())
1261
}

spdlog/src/formatter/pattern_formatter/mod.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,10 @@ use crate::{
7171
/// ```
7272
/// # use spdlog::formatter::{pattern, PatternFormatter};
7373
/// use spdlog::info;
74-
#[doc = include_str!("../../include/doc/test_utils.rs")]
74+
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
7575
///
7676
/// let formatter = PatternFormatter::new(pattern!("[{level}] {payload}"));
77-
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
77+
/// # let (doctest, sink) = test_utils::echo_logger_from_formatter(
7878
/// # Box::new(formatter),
7979
/// # None
8080
/// # );
@@ -97,9 +97,9 @@ use crate::{
9797
/// # formatter::{pattern, PatternFormatter},
9898
/// # info,
9999
/// # };
100-
#[doc = include_str!("../../include/doc/test_utils.rs")]
100+
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
101101
/// let formatter = PatternFormatter::new(pattern!("[{{escaped}}] {payload}"));
102-
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
102+
/// # let (doctest, sink) = test_utils::echo_logger_from_formatter(
103103
/// # Box::new(formatter),
104104
/// # None
105105
/// # );
@@ -126,9 +126,9 @@ use crate::{
126126
/// # formatter::{pattern, PatternFormatter},
127127
/// # info,
128128
/// # };
129-
#[doc = include_str!("../../include/doc/test_utils.rs")]
129+
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
130130
/// let formatter = PatternFormatter::new(pattern!("{^[{level}]} {payload}"));
131-
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
131+
/// # let (doctest, sink) = test_utils::echo_logger_from_formatter(
132132
/// # Box::new(formatter),
133133
/// # None
134134
/// # );
@@ -155,7 +155,7 @@ use crate::{
155155
/// formatter::{pattern, Pattern, PatternContext, PatternFormatter},
156156
/// Record, StringBuf, info
157157
/// };
158-
#[doc = include_str!("../../include/doc/test_utils.rs")]
158+
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
159159
///
160160
/// #[derive(Default, Clone)]
161161
/// struct MyPattern;
@@ -175,7 +175,7 @@ use crate::{
175175
/// {$mypat} => MyPattern::default,
176176
/// );
177177
/// let formatter = PatternFormatter::new(pat);
178-
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
178+
/// # let (doctest, sink) = test_utils::echo_logger_from_formatter(
179179
/// # Box::new(formatter),
180180
/// # None
181181
/// # );
@@ -213,7 +213,7 @@ use crate::{
213213
/// # prelude::*,
214214
/// # Record, StringBuf,
215215
/// # };
216-
#[doc = include_str!("../../include/doc/test_utils.rs")]
216+
#[doc = include_str!(concat!(env!("OUT_DIR"), "/test_utils/common_for_doc_test.rs"))]
217217
/// static NEXT_ID: AtomicU32 = AtomicU32::new(0);
218218
///
219219
/// #[derive(Clone)]
@@ -244,7 +244,7 @@ use crate::{
244244
/// {$mypat} => MyPattern::new,
245245
/// );
246246
/// let formatter = PatternFormatter::new(pat);
247-
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
247+
/// # let (doctest, sink) = test_utils::echo_logger_from_formatter(
248248
/// # Box::new(formatter),
249249
/// # None
250250
/// # );

spdlog/src/include/doc/test_utils.rs

Lines changed: 0 additions & 41 deletions
This file was deleted.

spdlog/src/test_utils/common.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Test utils for unit tests, integration tests and doc tests
2+
//
3+
// In this file, you can only use public items from spdlog-rs, as this file will
4+
// be used from integration tests and doc tests.
5+
//
6+
// This file will be handled in `build.rs` for code generation to workaround the
7+
// rustdoc bug https://github.com/rust-lang/rust/issues/67295
8+
9+
use std::sync::Arc;
10+
11+
use spdlog::{
12+
formatter::{Formatter, Pattern, PatternFormatter},
13+
prelude::*,
14+
sink::WriteSink,
15+
};
16+
17+
#[must_use]
18+
pub fn echo_logger_from_pattern(
19+
pattern: impl Pattern + Clone + 'static,
20+
name: Option<&'static str>,
21+
) -> (Logger, Arc<WriteSink<Vec<u8>>>) {
22+
echo_logger_from_formatter(Box::new(PatternFormatter::new(pattern)), name)
23+
}
24+
25+
#[must_use]
26+
pub fn echo_logger_from_formatter(
27+
formatter: Box<dyn Formatter>,
28+
name: Option<&'static str>,
29+
) -> (Logger, Arc<WriteSink<Vec<u8>>>) {
30+
let sink = Arc::new(
31+
WriteSink::builder()
32+
.formatter(formatter)
33+
.target(Vec::new())
34+
.build()
35+
.unwrap(),
36+
);
37+
38+
let mut builder = Logger::builder();
39+
40+
builder.sink(sink.clone());
41+
if let Some(name) = name {
42+
builder.name(name);
43+
}
44+
45+
(builder.build().unwrap(), sink)
46+
}

spdlog/src/test_utils/mod.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
mod unit_test;
2+
pub(crate) use unit_test::*;
3+
4+
#[allow(dead_code)]
5+
mod common {
6+
include!(concat!(
7+
env!("OUT_DIR"),
8+
"/test_utils/common_for_unit_test.rs"
9+
));
10+
}
11+
#[allow(unused_imports)]
12+
pub(crate) use common::*;

spdlog/src/test_utils.rs renamed to spdlog/src/test_utils/unit_test.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
// Test utils for unit tests only
2+
//
3+
// In this file, you can use public or private items from spdlog-rs as you wish,
4+
// as they will be used from unit tests only.
5+
16
use std::{env, fmt::Write, fs, path::PathBuf, thread::sleep, time::Duration};
27

38
use crate::{

0 commit comments

Comments
 (0)