Skip to content

Commit 36174d1

Browse files
committed
rust: kunit: support KUnit-mapped assert! macros in #[test]s
The KUnit `#[test]` support that landed recently is very basic and does not map the `assert*!` macros into KUnit like the doctests do, so they panic at the moment. Thus implement the custom mapping in a similar way to doctests, reusing the infrastructure there. In Rust 1.88.0, the `file()` method in `Span` may be stable [1]. However, it was changed recently (from `SourceFile`), so we need to do something different in previous versions. Thus create a helper for it and use it to get the path. With this, a failing test suite like: #[kunit_tests(my_test_suite)] mod tests { use super::*; #[test] fn my_first_test() { assert_eq!(42, 43); } #[test] fn my_second_test() { assert!(42 >= 43); } } will properly map back to KUnit, printing something like: [ 1.924325] KTAP version 1 [ 1.924421] # Subtest: my_test_suite [ 1.924506] # speed: normal [ 1.924525] 1..2 [ 1.926385] # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251 [ 1.926385] Expected 42 == 43 to be true, but is false [ 1.928026] # my_first_test.speed: normal [ 1.928075] not ok 1 my_first_test [ 1.928723] # my_second_test: ASSERTION FAILED at rust/kernel/lib.rs:256 [ 1.928723] Expected 42 >= 43 to be true, but is false [ 1.929834] # my_second_test.speed: normal [ 1.929868] not ok 2 my_second_test [ 1.930032] # my_test_suite: pass:0 fail:2 skip:0 total:2 [ 1.930153] # Totals: pass:0 fail:2 skip:0 total Link: rust-lang/rust#140514 [1] Reviewed-by: David Gow <davidgow@google.com> Acked-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20250502215133.1923676-2-ojeda@kernel.org [ Required `KUNIT=y` like for doctests. Used the `cfg_attr` from the TODO comment and clarified its comment now that the stabilization is in beta and thus quite likely stable in Rust 1.88.0. Simplified the `new_body` code by introducing a new variable. Added `#[allow(clippy::incompatible_msrv)]`. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 4bf7b97 commit 36174d1

File tree

6 files changed

+57
-7
lines changed

6 files changed

+57
-7
lines changed

init/Kconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ config LD_CAN_USE_KEEP_IN_OVERLAY
140140
config RUSTC_HAS_COERCE_POINTEE
141141
def_bool RUSTC_VERSION >= 108400
142142

143+
config RUSTC_HAS_SPAN_FILE
144+
def_bool RUSTC_VERSION >= 108800
145+
143146
config RUSTC_HAS_UNNECESSARY_TRANSMUTES
144147
def_bool RUSTC_VERSION >= 108800
145148

rust/Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,8 @@ quiet_cmd_rustc_procmacro = $(RUSTC_OR_CLIPPY_QUIET) P $@
404404
-Clink-args='$(call escsq,$(KBUILD_PROCMACROLDFLAGS))' \
405405
--emit=dep-info=$(depfile) --emit=link=$@ --extern proc_macro \
406406
--crate-type proc-macro \
407-
--crate-name $(patsubst lib%.$(libmacros_extension),%,$(notdir $@)) $<
407+
--crate-name $(patsubst lib%.$(libmacros_extension),%,$(notdir $@)) \
408+
@$(objtree)/include/generated/rustc_cfg $<
408409

409410
# Procedural macros can only be used with the `rustc` that compiled it.
410411
$(obj)/$(libmacros_name): $(src)/macros/lib.rs FORCE

rust/kernel/kunit.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,6 @@ mod tests {
323323

324324
#[test]
325325
fn rust_test_kunit_example_test() {
326-
#![expect(clippy::eq_op)]
327326
assert_eq!(1 + 1, 2);
328327
}
329328

rust/macros/helpers.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,20 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
8686
}
8787
None
8888
}
89+
90+
pub(crate) fn file() -> String {
91+
#[cfg(not(CONFIG_RUSTC_HAS_SPAN_FILE))]
92+
{
93+
proc_macro::Span::call_site()
94+
.source_file()
95+
.path()
96+
.to_string_lossy()
97+
.into_owned()
98+
}
99+
100+
#[cfg(CONFIG_RUSTC_HAS_SPAN_FILE)]
101+
#[allow(clippy::incompatible_msrv)]
102+
{
103+
proc_macro::Span::call_site().file()
104+
}
105+
}

rust/macros/kunit.rs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
5757
}
5858
}
5959

60-
// Add `#[cfg(CONFIG_KUNIT)]` before the module declaration.
61-
let config_kunit = "#[cfg(CONFIG_KUNIT)]".to_owned().parse().unwrap();
60+
// Add `#[cfg(CONFIG_KUNIT="y")]` before the module declaration.
61+
let config_kunit = "#[cfg(CONFIG_KUNIT=\"y\")]".to_owned().parse().unwrap();
6262
tokens.insert(
6363
0,
6464
TokenTree::Group(Group::new(Delimiter::None, config_kunit)),
@@ -98,6 +98,8 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
9898
// ```
9999
let mut kunit_macros = "".to_owned();
100100
let mut test_cases = "".to_owned();
101+
let mut assert_macros = "".to_owned();
102+
let path = crate::helpers::file();
101103
for test in &tests {
102104
let kunit_wrapper_fn_name = format!("kunit_rust_wrapper_{test}");
103105
let kunit_wrapper = format!(
@@ -109,6 +111,27 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
109111
" ::kernel::kunit::kunit_case(::kernel::c_str!(\"{test}\"), {kunit_wrapper_fn_name}),"
110112
)
111113
.unwrap();
114+
writeln!(
115+
assert_macros,
116+
r#"
117+
/// Overrides the usual [`assert!`] macro with one that calls KUnit instead.
118+
#[allow(unused)]
119+
macro_rules! assert {{
120+
($cond:expr $(,)?) => {{{{
121+
kernel::kunit_assert!("{test}", "{path}", 0, $cond);
122+
}}}}
123+
}}
124+
125+
/// Overrides the usual [`assert_eq!`] macro with one that calls KUnit instead.
126+
#[allow(unused)]
127+
macro_rules! assert_eq {{
128+
($left:expr, $right:expr $(,)?) => {{{{
129+
kernel::kunit_assert_eq!("{test}", "{path}", 0, $left, $right);
130+
}}}}
131+
}}
132+
"#
133+
)
134+
.unwrap();
112135
}
113136

114137
writeln!(kunit_macros).unwrap();
@@ -147,10 +170,12 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
147170
}
148171
}
149172

150-
let mut new_body = TokenStream::from_iter(new_body);
151-
new_body.extend::<TokenStream>(kunit_macros.parse().unwrap());
173+
let mut final_body = TokenStream::new();
174+
final_body.extend::<TokenStream>(assert_macros.parse().unwrap());
175+
final_body.extend(new_body);
176+
final_body.extend::<TokenStream>(kunit_macros.parse().unwrap());
152177

153-
tokens.push(TokenTree::Group(Group::new(Delimiter::Brace, new_body)));
178+
tokens.push(TokenTree::Group(Group::new(Delimiter::Brace, final_body)));
154179

155180
tokens.into_iter().collect()
156181
}

rust/macros/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66
// and thus add a dependency on `include/config/RUSTC_VERSION_TEXT`, which is
77
// touched by Kconfig when the version string from the compiler changes.
88

9+
// Stable since Rust 1.88.0 under a different name, `proc_macro_span_file`,
10+
// which was added in Rust 1.88.0. This is why `cfg_attr` is used here, i.e.
11+
// to avoid depending on the full `proc_macro_span` on Rust >= 1.88.0.
12+
#![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
13+
914
#[macro_use]
1015
mod quote;
1116
mod concat_idents;

0 commit comments

Comments
 (0)