rust: kunit: support #[should_panic] and same test name with different #[cfg(...)]
Subsystems (3)
cover rust: kunit: support #[should_panic] and same test name with different #[cfg(...)]
This patch series intends to implement two features for KUnit tests written in Rust. The work is based on a TODO comment made in the bitmap.rs module [1].
Changelog:
- RFC patch: [3]
1. Supporting #[should_panic] [2]:
KUnit tests in Rust follow the user-space syntax, but at the moment #[should_panic] is not supported. The first patch of this series adds support for the attribute (only in its basic form, #[should_panic = "message"] is not supported yet).
The way it is supported is by adding a new boolean property called rust_should_panic to kunit_attributes struct in kunit/test.h and check for the try_catch->try_result code and the named flag to detect if there was a panic in lib/kunit/test.c::kunit_run_case_catch_errors function.
The difference with the previous version [3] is that now, almost everything is handled in the C side, meaning that we don't have a separate #[panic_handler] when KUnit tests are active. In other words there's no need of a Rust side panic handler because the C side catches Rust's panics too, since the #[panic_hanlder] executes a bindings::BUG().
2. Allow same test name with different #[cfg(...)]:
When testing #[should_panic] in bitmap.rs (check the last patch of the series) I found that the test that was supposed to panic had the same name as another one, but they were run on different configurations. This caused the following compilation error:
ERROR:root:error[E0428]: the name kunit_rust_wrapper_owned_bitmap_out_of_bounds is defined multiple times
--> ../rust/kernel/bitmap.rs:503:1
|
503 | #[macros::kunit_tests(rust_kernel_bitmap)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `kunit_rust_wrapper_owned_bitmap_out_of_bounds` redefined here
| = note: kunit_rust_wrapper_owned_bitmap_out_of_bounds must be defined only once in the value namespace of this module = note: this error originates in the attribute macro macros::kunit_tests (in Nightly builds, run with -Z macro-backtrace for more info)
Now, only the tests with an active #[cfg(...)] will be executed by the runner. Tests with an inactive #[cfg(...)] will not appear in the report since they are not added to the TEST_CASES array.
[1] https://github.com/Rust-for-Linux/linux/blob/fd73f4a6659897191fa0d40695fe370925dd3780/rust/kernel/bitmap.rs#L592-L600
[2] https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#testing-panics
[3] https://lore.kernel.org/rust-for-linux/[email protected]/
---
Nicolás Antinori (3):
rust: kunit: add #[should_panic] support
rust: kunit: allow same test name with different #[cfg(...)]
rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case
include/kunit/test.h | 1 + lib/kunit/attributes.c | 18 ++++++++++++++++++ lib/kunit/test.c | 5 +++++ rust/kernel/bitmap.rs | 40 ++++++++++++++++++---------------------- rust/kernel/kunit.rs | 37 +++++++++++++++++++++++++++++++++++++ rust/macros/kunit.rs | 48 ++++++++++++++++++++++++++++++++++++++---------- 6 files changed, 117 insertions(+), 32 deletions(-)
---
base-commit: d266640c6c760c9bc215bf5a3ece122ca488b6f5
change-id: 20260930-rust_kunit_v4-7abaee11e6ac
Best regards,
Signature · 1 line
Nicolás Antinori <[email protected]>
PATCH 1/3 rust: kunit: add #[should_panic] support
KUnit tests in Rust are written using user-space like syntax. This patch adds support for the #[should_panic] attribute, enabling the user to test conditions that are expected to cause a panic and report the test as successful.
--- include/kunit/test.h | 1 + lib/kunit/attributes.c | 18 ++++++++++++++++++ lib/kunit/test.c | 5 +++++ rust/kernel/kunit.rs | 15 +++++++++++++++ rust/macros/kunit.rs | 28 +++++++++++++++++++++++----- 5 files changed, 62 insertions(+), 5 deletions(-)
include/kunit/test.h +1 -0
@@ -83,6 +83,7 @@ enum kunit_speed {/* Holds attributes for each test case and suite */ struct kunit_attributes {enum kunit_speed speed; +bool rust_should_panic; };/**
lib/kunit/attributes.c +18 -0
@@ -246,6 +246,16 @@ static void *attr_is_init_get(void *test_or_suite, bool is_test)return ((void *) suite->is_init); } +static void *attr_rust_should_panic_get (void *test_or_suite,bool is_test) +{ +struct kunit_case *test = is_test ? test_or_suite :NULL ; + +if (test) +return ((void *) test->attr.rust_should_panic); +else +return ((void *)NULL ); +} +/* List of all Test Attributes */ static struct kunit_attr kunit_attr_list[] = {
@@ -272,6 +282,14 @@ static struct kunit_attr kunit_attr_list[] = { .filter = attr_bool_filter, .attr_default = (void *)false, .print = PRINT_SUITE, + }, + { + .name = "rust_should_panic", + .get_attr = attr_rust_should_panic_get, + .to_string = attr_bool_to_string, + .filter = attr_bool_filter, + .attr_default = (void *)false, + .print = PRINT_NEVER, } };
lib/kunit/test.c +5 -0
@@ -590,6 +590,11 @@ static void kunit_run_case_catch_errors(struct kunit_suite *suite, context.test_case = test_case;kunit_try_catch_run (try_catch, &context); +if (try_catch->try_result == -EINTR && test_case->attr.rust_should_panic) { + test->status =KUNIT_SUCCESS ; + test_case->status =KUNIT_SUCCESS ; + } +/* Now run the cleanup */ kunit_try_catch_init(try_catch, test,
rust/kernel/kunit.rs +15 -0
@@ -207,6 +207,7 @@ pub const fn kunit_case( name: kernel::str::as_char_ptr_in_const_context(name), attr: kernel::bindings::kunit_attributes { speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, + rust_should_panic: false, }, generate_params: None, status: kernel::bindings::kunit_status_KUNIT_SUCCESS,
@@ -282,6 +283,7 @@ macro_rules! kunit_unsafe_test_suite { exit: None, attr: ::kernel::bindings::kunit_attributes { speed: ::kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, + rust_should_panic: false, }, status_comment: [0; 256usize], debugfs: ::core::ptr::null_mut(),
@@ -345,6 +347,19 @@ fn rust_test_kunit_in_kunit_test() {assert! (in_kunit_test ()); } +#[test] +#[should_panic] +fn rust_test_kunit_panic_in_kunit_test () { +panic! ("This test should panic and pass" ); + } + +#[test] +#[should_panic] +fn rust_test_kunit_panic_in_kunit_test_bug () { +// The panic is produced in a C call. This should succeed. +unsafe { bindings::BUG () }; + } +#[test] #[cfg(not(all()))] fn rust_test_kunit_always_disabled_test () {
rust/macros/kunit.rs +23 -5
@@ -106,6 +106,11 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Toke .cloned() .collect (); +let should_panic = f + .attrs + .iter () + .any (|attr| attr.path ().is_ident ("should_panic" )); +// Before the test, override usual `assert!` and `assert_eq!` macros with ones that call // KUnit instead. let test_str = test.to_string ();
@@ -135,25 +140,38 @@ macro_rules! assert_eq { &CString::new(test_str.as_str()).expect("identifier cannot contain NUL"), test.span(), ); +let assertion =if should_panic { +quote! ( +let _ = #test (); + (*_test).status = ::kernel::bindings::kunit_status_KUNIT_FAILURE; + ) + }else { +quote! ( +use ::kernel::kunit::is_test_result_ok; +assert! (is_test_result_ok (#test ())); + ) + }; processed_items.push (parse_quote! {unsafe extern "C" fn #kunit_wrapper_fn_name (_test: *mut ::kernel::bindings::kunit ) { (*_test).status = ::kernel::bindings::kunit_status_KUNIT_SKIPPED; +// Append any `cfg` attributes the user might have written on their tests so we // don't attempt to call them when they are `cfg`'d out. An extra `use` is used // here to reduce the length of the assert message. #(#cfg_attrs)* { (*_test).status = ::kernel::bindings::kunit_status_KUNIT_SUCCESS; -use ::kernel::kunit::is_test_result_ok; -assert! (is_test_result_ok (#test ())); + #assertion } } }); - test_cases.push (quote! ( - ::kernel::kunit::kunit_case (#test_cstr, #kunit_wrapper_fn_name) - )); + test_cases.push (quote! ({ +let mut case = ::kernel::kunit::kunit_case (#test_cstr, #kunit_wrapper_fn_name); + case.attr.rust_should_panic = #should_panic; + case + })); }let num_tests_plus_1 = test_cases.len () +1 ;
Signature · 1 line
2.47.3
PATCH 2/3 rust: kunit: allow same test name with different #[cfg(...)]
In reply to Nicolás AntinoriSometimes it is necessary to test the same code paths under different configurations. The #[cfg(...)] macro can be used to check if specific configurations are enabled and run tests accordingly.
Currently, defining multiple tests with the same name under different #[cfg(...)] attributes results in a compilation error. This patch removes that restriction, allowing identical test names across different configurations.
--- rust/kernel/kunit.rs | 22 ++++++++++++++++++++++ rust/macros/kunit.rs | 20 +++++++++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-)
rust/kernel/kunit.rs +22 -0
@@ -347,6 +347,28 @@ fn rust_test_kunit_in_kunit_test() {assert! (in_kunit_test ()); } +// Tests with cfg have the same name on purpose because we are implicitly testing that +// tests with the same name but different configs do not throw a compilation error +#[test] +#[cfg( CONFIG_RUST_KUNIT_SELFTEST = "y" )] +fn rust_test_kunit_run_only_active_cfg () { +assert! (in_kunit_test ()); + } + +#[test] +#[cfg( CONFIG_RUST_KUNIT_SELFTEST = "n" )] +fn rust_test_kunit_run_only_active_cfg () { +// This test should never run because of the `cfg`. +assert! (false ) + } + +#[test] +#[cfg( CONFIG_RUST_KUNIT_SELFTEST = "INVALID_VALUE" )] +fn rust_test_kunit_run_only_active_cfg () { +// This test should never run because of the `cfg`. +assert! (false ) + } +#[test] #[should_panic] fn rust_test_kunit_panic_in_kunit_test () {
rust/macros/kunit.rs +15 -5
@@ -45,6 +45,8 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Tokelet mut processed_items =Vec ::new ();let mut test_cases =Vec ::new (); +let mut test_cases_cfgs =Vec ::new (); +let mut test_case_number:u32 =1 ;// Generate the test KUnit test suite and a test case for each `#[test]`. //
@@ -135,7 +137,7 @@ macro_rules! assert_eq {// Add back the test item. processed_items.push (Item ::Fn (f)); -let kunit_wrapper_fn_name =format_ident! ("kunit_rust_wrapper_{test}" ); +let kunit_wrapper_fn_name =format_ident! ("kunit_rust_wrapper_{test}_{test_case_number}" );let test_cstr =LitCStr ::new ( &CString ::new (test_str.as_str ()).expect ("identifier cannot contain NUL" ), test.span(),
@@ -172,15 +174,23 @@ macro_rules! assert_eq { case.attr.rust_should_panic = #should_panic; case })); + test_cases_cfgs.push (cfg_attrs); + test_case_number +=1 ; } -let num_tests_plus_1 = test_cases.len () +1 ; +// This dummy array is used to calculate the exact number of tests cases that are active +// depending on their #[cfg(...)] attribute. + processed_items.push (parse_quote! ( +const TEST_CASES_COUNT : &[()] = &[#(#(#test_cases_cfgs)* (),)* ()]; + )); + processed_items.push (parse_quote! { -static mut TEST_CASES : [::kernel::bindings::kunit_case ; #num_tests_plus_1] = [ - #(#test_cases,)* - ::pin_init::zeroed (), +static mut TEST_CASES : [::kernel::bindings::kunit_case ;TEST_CASES_COUNT .len ()] = [ + #(#(#test_cases_cfgs)* { #test_cases },)* + ::pin_init::zeroed () ]; }); + processed_items.push (parse_quote! { ::kernel::kunit_unsafe_test_suite!(#test_suite,TEST_CASES ); });
Signature · 1 line
2.47.3
PATCH 3/3 rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case
In reply to Nicolás AntinoriRust KUnit tests now support #[should_panic] attribute. Uncomment the test so it can be run when CONFIG_RUST_BITMAP_HARDENED=y.
--- rust/kernel/bitmap.rs | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-)
rust/kernel/bitmap.rs +18 -22
@@ -571,33 +571,29 @@ fn bitmap_set_clear_find() -> Result<(), AllocError> {Ok (()) } +#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] #[test] fn owned_bitmap_out_of_bounds () ->Result <(),AllocError > { -// TODO: Kunit #[test]s do not support `cfg` yet, -// so we add it here in the body. -#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] - { -let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; - b.set_bit (2048 ); - b.set_bit_atomic (2048 ); - b.clear_bit (2048 ); - b.clear_bit_atomic (2048 ); -assert_eq! (None , b.next_bit (2048 )); -assert_eq! (None , b.next_zero_bit (2048 )); -assert_eq! (None , b.last_bit ()); - } +let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; + b.set_bit (2048 ); + b.set_bit_atomic (2048 ); + b.clear_bit (2048 ); + b.clear_bit_atomic (2048 ); +assert_eq! (None , b.next_bit (2048 )); +assert_eq! (None , b.next_zero_bit (2048 )); +assert_eq! (None , b.last_bit ());Ok (()) } -// TODO: uncomment once kunit supports [should_panic] and `cfg`. -// #[cfg(CONFIG_RUST_BITMAP_HARDENED)] -// #[test] -// #[should_panic] -// fn owned_bitmap_out_of_bounds() -> Result<(), AllocError> { -// let mut b = BitmapVec::new(128, GFP_KERNEL)?; -// -// b.set_bit(2048); -// } +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +#[test] +#[should_panic] +fn owned_bitmap_out_of_bounds () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; + + b.set_bit (2048 ); +Ok (()) + }#[test] fn bitmap_copy_and_extend () ->Result <(),AllocError > {
Signature · 1 line
2.47.3
Quoted 4 lines · On Wed, Sep 30, 2026 at 3:23 PM Nicolás Antinori via B4 Relay…
This patch series intends to implement two features for KUnit tests written in Rust. The work is based on a TODO comment made in the
bitmap.rsmodule [1].
I am glad it worked with b4! Hopefully no more Gmail issues :)
(Nit: in cases like this, I would suggest increasing tagging with RESEND or maybe increasing the version to avoid the same subject line in Lore and other clients.)
Cheers,
Miguel
Gary Guo
reviewerQuoted 9 lines · On Wed Sep 30, 2026 at 2:23 PM BST, Nicolás Antinori via B4 Relay wrote:
This patch series intends to implement two features for KUnit tests written in Rust. The work is based on a TODO comment made in the
bitmap.rsmodule [1].Changelog:
- RFC patch: [3]1. Supporting
#[should_panic][2]:
Quoted 7 lines
KUnit tests in Rust follow the user-space syntax, but at the moment
#[should_panic]is not supported. The first patch of this series adds support for the attribute (only in its basic form,#[should_panic = "message"]is not supported yet).The way it is supported is by adding a new boolean property called
rust_should_panictokunit_attributesstruct inkunit/test.hand
This is now more general than Rust panics? Perhaps this should just be "should_bug"?
Best,
Gary
Quoted 54 lines
check for the
try_catch->try_resultcode and the named flag to detect if there was a panic inlib/kunit/test.c::kunit_run_case_catch_errorsfunction.The difference with the previous version [3] is that now, almost everything is handled in the C side, meaning that we don't have a separate
#[panic_handler]when KUnit tests are active. In other words there's no need of a Rust side panic handler because the C side catches Rust's panics too, since the#[panic_hanlder]executes abindings::BUG().2. Allow same test name with different #[cfg(...)]:
When testing
#[should_panic]inbitmap.rs(check the last patch of the series) I found that the test that was supposed to panic had the same name as another one, but they were run on different configurations. This caused the following compilation error:ERROR:root:error[E0428]: the name
kunit_rust_wrapper_owned_bitmap_out_of_boundsis defined multiple times
-->../rust/kernel/bitmap.rs:503:1| 503 | #[macros::kunit_tests(rust_kernel_bitmap)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `kunit_rust_wrapper_owned_bitmap_out_of_bounds` redefined here |= note:
kunit_rust_wrapper_owned_bitmap_out_of_boundsmust be defined only once in the value namespace of this module = note: this error originates in the attribute macromacros::kunit_tests(in Nightly builds, run with -Z macro-backtrace for more info)Now, only the tests with an active
#[cfg(...)]will be executed by the runner. Tests with an inactive#[cfg(...)]will not appear in the report since they are not added to theTEST_CASESarray.[1] https://github.com/Rust-for-Linux/linux/blob/fd73f4a6659897191fa0d40695fe370925dd3780/rust/kernel/bitmap.rs#L592-L600
[2] https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#testing-panics
[3] https://lore.kernel.org/rust-for-linux/[email protected]/Signed-off-by Nicolás Antinori <[email protected]>---
Nicolás Antinori (3):
rust: kunit: add #[should_panic] support
rust: kunit: allow same test name with different #[cfg(...)]
rust: bitmap: kunit: uncommentowned_bitmap_out_of_boundspanic caseinclude/kunit/test.h | 1 + lib/kunit/attributes.c | 18 ++++++++++++++++++ lib/kunit/test.c | 5 +++++ rust/kernel/bitmap.rs | 40 ++++++++++++++++++---------------------- rust/kernel/kunit.rs | 37 +++++++++++++++++++++++++++++++++++++ rust/macros/kunit.rs | 48 ++++++++++++++++++++++++++++++++++++++---------- 6 files changed, 117 insertions(+), 32 deletions(-)---
base-commit:d266640c6c760c9bc215bf5a3ece122ca488b6f5
change-id: 20260930-rust_kunit_v4-7abaee11e6acBest regards,
Quoted 8 lines · Miguel Ojeda
Quoted 4 lines · On Wed, Sep 30, 2026 at 3:23 PM Nicolás Antinori via B4 Relay…
This patch series intends to implement two features for KUnit tests written in Rust. The work is based on a TODO comment made in the
bitmap.rsmodule [1].I am glad it worked with
b4! Hopefully no more Gmail issues :)
Yes! Thank you very much for the suggestion! I'll have it that as a fallback mechanism for now on
Quoted 4 lines
(Nit: in cases like this, I would suggest increasing tagging with RESEND or maybe increasing the version to avoid the same subject line in Lore and other clients.)
Sorry about that! I had the intention but forgot to do it
Quoted 3 lines
Cheers,
Miguel
Quoted 15 lines · Gary Guo
Quoted 14 lines · On Wed Sep 30, 2026 at 2:23 PM BST, Nicolás Antinori via B4 Relay wrote:
This patch series intends to implement two features for KUnit tests written in Rust. The work is based on a TODO comment made in the
bitmap.rsmodule [1].Changelog:
- RFC patch: [3]1. Supporting
#[should_panic][2]:KUnit tests in Rust follow the user-space syntax, but at the moment
#[should_panic]is not supported. The first patch of this series adds support for the attribute (only in its basic form,#[should_panic = "message"]is not supported yet).
Quoted 5 lines
Quoted 2 lines
The way it is supported is by adding a new boolean property called
rust_should_panictokunit_attributesstruct inkunit/test.handThis is now more general than Rust panics? Perhaps this should just be "
should_bug"?
I used the name suggested by David Gow in the RFC Patch [1]. I believe "should_panic" is better because it directly matches the attribute name and will stay consistent in case the panic handler changes the way it trigger kernel panics (although this is very unlikely I think).
That said, I'd be happy to change it to should_bug if that is preferred, please let me know what you think!
Best regards,
Nicolás
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Re: [PATCH 1/3] rust: kunit: add #[should_panic] support
In reply to Nicolás AntinoriHello,
There are two observations by Sashiko in this patch [1]:
Quoted 8 lines
[Severity: Low]
Does this interception occur too late to prevent spurious error logs?When a Rust test panics as expected, it triggers a kernel fault caught by KUnit with an exit code of
-EINTR. However,kunit_try_catch_run()unconditionally logs an error message for-EINTRbefore returning to this function
Quoted 10 lines
lib/kunit/try-catch.c:kunit_try_catch_run() {
...
else if (exit_code == -EINTR) {
if (test->last_seen.file)
kunit_err(test, "try faulted: last line seen %s:%d\n", ...);
else
kunit_err(test, "try faulted\n");
}
...
}Even though the tests marked as #[should_panic] are reported as successful by KUnit, when run with --raw_output=all those log errors appear. Is this a problem? Along with those the Oops message and stack trace message show up as well. The report summary is clean if no special logging options are used.
Quoted 9 lines
[Severity: Medium]
Will this condition correctly handle KUnit assertions inside a #[should_panic] test?The
kunit_testsmacro overrides assert! withkunit_assert!. If an assert! fails,kunit_assert! reports a KUnit assertion failure and aborts the thread via__kunit_abort, which results in-EFAULTrather than-EINTR.
Quoted 4 lines
Since
-EFAULTis cleared to 0 inkunit_try_catch_run(), this condition checking strictly for-EINTRwill fail to intercept the abort. Will this cause valid #[should_panic] tests containing an assert! failure to be incorrectly marked asKUNIT_FAILUREinstead of passing?
This is something I missed when working on the series and is accurate. The following test:
#[test]
#[should_panic]
fn rust_test_assert_false() {
assert!(false)
}
Is reported as failed:
[18:31:00] # rust_test_assert_false: ASSERTION FAILED at rust/kernel/kunit.rs:383 [18:31:00] Expected false to be true, but is false
[18:31:00] # rust_test_assert_false.speed: normal
[18:31:00] [FAILED] rust_test_assert_false
But the user-space behavior is to pass the test [2].
Does it make sense to leave this behavior as it is for the kernel? If I am not mistaken tests like those can easily be expressed without the #[should_panic] attribute and negating the condition inside assert!. assert! that are not in the test body behave as expected.
To solve those I'd need to check the rust_should_panic flag inside in kunit_try_catch_run function. That would require changing its signature (since the kunit_try_catch struct does not contain the test_case struct and the context argument is void*, so I can't safely cast it to what I need). Other alternative is to create a new function for cases where rust_should_panic is true.
My approach to this was to modify as little as possible in the C side. I think the current behavior is ok but I want to know your opinion.
Best regards,
Nicolás
[1] https://sashiko.dev/#/patchset/[email protected]?part=1
[2] https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=2b4b29a266271497ea9932068ecdb8ff