rust: kunit: support #[should_panic] and same test name with different #[cfg(...)]
Subsystems (6)
v3 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:
v3:
Gone back to the #[panic_handler] implementation (original idea from RFC Patch), after discussing it in the v2 patch thread. This means that #[should_panic] will catch Rust panics only.
The changes are:
- #[should_panic] introduction patch (patch 1):
- Handling panics through a #[panic_handler] in
`rust/kernel/lib.rs`.
- Added a kunit_attributes pointer to the kunit struct to be able to read the test attributes from the panic handler in Rust.
- Modified kunit_init_test to fill the kunit_attributes pointer inside the kunit struct.
- Using extract_if for detecting should_panic attribute instead of just checking that it is there.
- Explicitly using kunit_assert! in macros/kunit.rs, because now the macro overwrite is done inside the function body.
- Fixed KUnit test initialization in lib/kunit/kunit-test.c, lib/kunit/platform-test.c, lib/kunit/string-stream-test.c and drivers/of/overlay_test.c (passed kunit_attributes)
- Rolled back kunit_assert! and kunit_assert_eq! modifications from v2.
- Rolled back adding rust_should_panic property to kunit_try_catch C struct
- Removed test case that called BUG() C binding directly within the test.
- Added #[should_panic] to documentation.
- bitmap.rs test (patch 3)
- Solved some nits pointed out by Miguel.
- General:
- Carried all Reviewed-by from v2 for patch 2 (this patch did not change)
- Carried Acked-by and Reviewed-by from v2 for patch 3 (changes are not functional)
Note: Now that we are using the #[panic_handler] I have a draft implementation of #[should_panic = "message"] support, but I think it'd be better to send it as a separate patch once this is merged to not add noise to the review of this (the affected patch is the first one).
Note: I was not sure whether to add the attributes assignment to kunit_init_test, as it is a public function and doing so required changing its signature to accept an attributes pointer argument. Is this the right place to do it?
Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]/
v2:
- Added more tests in rust/kernel/kunit.rs testing Sashiko findings and changes.
- Solved Sashiko: "[Low] kunit: spurious "try faulted" error logs for successful #[should_panic] tests": Solved by adding rust_should_panic in kunit_try_catch C struct to check if the test is expected to panic and act accordingly. Dismissed what I first talked about in [3].
- Solved Sashiko: "[Medium] kunit: assert! macro in #[should_panic] tests causes unexpected failure": Solved by making kunit_assert macro aware if the test should panic and act accordingly. Dismissed what I first talked about in [3]
- Solved Sashiko: "[Low] kunit: missing diagnostic log for #[should_panic] tests that fail to panic": Added an error message when a test that was expected to panic does not.
- Solved Sashiko: "[Low] kunit: dead_code error for test wrappers with inactive cfg": Solved by moving the #[cfg(..)] attributes on top of the wrapper functions
- Dismissed Sashiko: "[Medium] rust: bitmap: memory leak in owned_bitmap_out_of_bounds() test panic": Not sure if can be done anything. If I am not mistaken this is the same issue as stated here [4].
Sashiko report links: https://sashiko.dev/#/patchset/[email protected]?part=1
v1:
- Removed 'stringification' of test names (to avoid clash of names for different configurations now a number is appended).
- Added bool rust_should_panic attribute to kunit_attributes C
struct
- Removed #[panic_handler] in Rust side, checking for aborts in the C
side (kunit_run_case_catch_errors function). This allows to catch
panics triggered, for example in a Rust function that called a panicking
C function.
- Now the tests that have an inactive #[cfg(..)] do not appear in the
KUnit execution summary as ignored, they just do not run.
Link to v1: https://lore.kernel.org/all/[email protected]/
- RFC patch: https://lore.kernel.org/rust-for-linux/[email protected]/
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 in the #[panic_handler] whether the test was supposed to panic or not.
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/all/[email protected]/
[4] https://github.com/Rust-for-Linux/linux/blob/fd73f4a6659897191fa0d40695fe370925dd3780/rust/kernel/kunit.rs#L129-L136
---
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
Documentation/rust/testing.rst | 8 ++- drivers/of/overlay_test.c | 6 ++- include/kunit/test.h | 9 +++- lib/kunit/attributes.c | 18 +++++++ lib/kunit/kunit-test.c | 36 +++++++++++--- lib/kunit/platform-test.c | 6 ++- lib/kunit/string-stream-test.c | 9 +++- lib/kunit/test.c | 10 ++-- rust/kernel/bitmap.rs | 18 +++---- rust/kernel/kunit.rs | 54 ++++++++++++++++++++ rust/kernel/lib.rs | 43 +++++++++++++++- rust/macros/kunit.rs | 109 +++++++++++++++++++++++++++-------------- 12 files changed, 264 insertions(+), 62 deletions(-)
---
base-commit: ee83899302a0457a3ba47464a13e8682bd7ba27d
change-id: 20261029-rust_kunit_v6_send-d0353c1615f9
Best regards,
Signature · 1 line
Nicolás Antinori <[email protected]>
PATCH v3 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.
--- Documentation/rust/testing.rst | 8 ++++- drivers/of/overlay_test.c | 6 +++- include/kunit/test.h | 9 ++++- lib/kunit/attributes.c | 18 ++++++++++ lib/kunit/kunit-test.c | 36 ++++++++++++++++---- lib/kunit/platform-test.c | 6 +++- lib/kunit/string-stream-test.c | 9 ++++- lib/kunit/test.c | 10 ++++-- rust/kernel/kunit.rs | 32 ++++++++++++++++++ rust/kernel/lib.rs | 43 +++++++++++++++++++++-- rust/macros/kunit.rs | 77 +++++++++++++++++++++++++++++------------- 11 files changed, 215 insertions(+), 39 deletions(-)
Documentation/rust/testing.rst +7 -1
@@ -169,8 +169,14 @@ And if we run it, the kernel log would look like:: ok 1 test_f ok 1 rust_kernel_mymod +To test code paths that are expected to produce a Rust panic, the +``#[should_panic]`` attribute can be used. When this attribute is used, tests +that produce a panic (either with ``panic!`` or an ``assert!``) will pass. + Like documentation tests, the ``assert!`` and ``assert_eq!`` macros are mapped -back to KUnit and do not panic. Similarly, the +back to KUnit and do not panic. The exception is tests marked with +``#[should_panic]``, which use the standard Rust ``assert!``/``assert_eq!`` +macros so that failed assertions are handled by the panic logic. Similarly, the `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_ operator is supported, i.e. the test functions may return either nothing (i.e. the unit type ``()``) or ``Result`` (i.e. any ``Result<T, E>``). For instance:
drivers/of/overlay_test.c +5 -1
@@ -63,6 +63,10 @@ static void of_overlay_apply_kunit_cleanup(struct kunit *test)struct platform_device *pdev;struct device *dev;struct device_node *np; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + };of_root_kunit_skip (test);if (!IS_ENABLED (CONFIG_OF_OVERLAY ))
@@ -70,7 +74,7 @@ static void of_overlay_apply_kunit_cleanup(struct kunit *test)if (!IS_ENABLED (CONFIG_OF_EARLY_FLATTREE ))kunit_skip (test,"requires CONFIG_OF_EARLY_FLATTREE for root node" ); -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake.status,KUNIT_SUCCESS ); KUNIT_ASSERT_EQ(test, 0,
include/kunit/test.h +8 -1
@@ -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; };/**
@@ -355,6 +356,9 @@ struct kunit {char status_comment[KUNIT_STATUS_COMMENT_SIZE ];/* Saves the last seen test. Useful to help with faults. */ struct kunit_loc last_seen; + +/* The attributes associated with the test */ +struct kunit_attributes *attr; };static inline void kunit_set_failure (struct kunit *test)
@@ -369,7 +373,10 @@ const char *kunit_filter_glob(void);char *kunit_filter (void );char *kunit_filter_action (void ); -void kunit_init_test (struct kunit *test,const char *name,struct string_stream *log); +void kunit_init_test (struct kunit *test, +const char *name, +struct string_stream *log, +struct kunit_attributes *attr);int kunit_run_tests (struct kunit_suite *suite);
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/kunit-test.c +30 -6
@@ -186,7 +186,7 @@ static void kunit_resource_test_init_resources(struct kunit *test) {struct kunit_test_resource_context *ctx = test->priv; -kunit_init_test (&ctx->test,"testing_test_init_test" ,NULL ); +kunit_init_test (&ctx->test,"testing_test_init_test" ,NULL , ctx->test.attr);KUNIT_EXPECT_TRUE (test,list_empty (&ctx->test.resources)); }
@@ -539,12 +539,19 @@ static void kunit_resource_test_action_ordering(struct kunit *test)static int kunit_resource_test_init (struct kunit *test) {struct kunit_test_resource_context *ctx =kzalloc_obj (*ctx); +struct kunit_attributes *ctx_test_attr;KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx); test->priv = ctx; -kunit_init_test (&ctx->test,"test_test_context" ,NULL ); + ctx_test_attr =kzalloc_obj (*ctx_test_attr,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx_test_attr); + + ctx_test_attr->speed =KUNIT_SPEED_NORMAL ; + ctx_test_attr->rust_should_panic = false; + +kunit_init_test (&ctx->test,"test_test_context" ,NULL , ctx_test_attr);return 0 ; }
@@ -553,6 +560,7 @@ static void kunit_resource_test_exit(struct kunit *test) {struct kunit_test_resource_context *ctx = test->priv; +kfree (ctx->test.attr);kunit_cleanup (&ctx->test);kfree (ctx); }
@@ -666,8 +674,12 @@ static struct kunit_suite kunit_log_test_suite = {static void kunit_status_set_failure_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_EXPECT_EQ (test, fake.status, (enum kunit_status )KUNIT_SUCCESS );kunit_set_failure (&fake);
@@ -677,8 +689,12 @@ static void kunit_status_set_failure_test(struct kunit *test)static void kunit_status_mark_skipped_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);/* Before: Should be SUCCESS with no comment. */ KUNIT_EXPECT_EQ (test, fake.status,KUNIT_SUCCESS );
@@ -715,8 +731,12 @@ static void kunit_current_test(struct kunit *test)static void kunit_current_fail_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_EXPECT_EQ (test, fake.status,KUNIT_SUCCESS );/* Set current->kunit_test to fake test. */
@@ -881,8 +901,12 @@ static void kunit_stub_test(struct kunit *test)void *real_fn_addr;void *replacement_addr; } *stub_ctx; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake_test,"kunit_stub_fake_test" ,NULL ); +kunit_init_test (&fake_test,"kunit_stub_fake_test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake_test.status,KUNIT_SUCCESS );KUNIT_ASSERT_EQ (test,list_count_nodes (&fake_test.resources),0 );
lib/kunit/platform-test.c +5 -1
@@ -71,8 +71,12 @@ static void kunit_platform_device_add_cleans_up(struct kunit *test)const int id =-1 ;struct kunit fake;struct device *dev; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"kunit_platform_device_add_fake_test" ,NULL ); +kunit_init_test (&fake,"kunit_platform_device_add_fake_test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake.status,KUNIT_SUCCESS ); pdev =kunit_platform_device_alloc (&fake, name, id);
lib/kunit/string-stream-test.c +8 -1
@@ -122,11 +122,18 @@ static void string_stream_resource_free_test(struct kunit *test) {struct string_stream_test_priv *priv = test->priv;struct kunit *fake_test; +struct kunit_attributes *fake_attr; fake_test =kunit_kzalloc (test,sizeof (*fake_test),GFP_KERNEL );KUNIT_ASSERT_NOT_ERR_OR_NULL (test, fake_test); -kunit_init_test (fake_test,"string_stream_fake_test" ,NULL ); + fake_attr =kunit_kzalloc (test,sizeof (*fake_attr),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, fake_attr); + + fake_attr->speed =KUNIT_SPEED_NORMAL ; + fake_attr->rust_should_panic = false; + +kunit_init_test (fake_test,"string_stream_fake_test" ,NULL , fake_attr); fake_test->priv = priv;/*
lib/kunit/test.c +7 -3
@@ -351,7 +351,10 @@ static void kunit_init_params(struct kunit *test) test->params_array.elem_size =0 ; } -void kunit_init_test (struct kunit *test,const char *name,struct string_stream *log) +void kunit_init_test (struct kunit *test, +const char *name, +struct string_stream *log, +struct kunit_attributes *attributes) {spin_lock_init (&test->lock);INIT_LIST_HEAD (&test->resources);
@@ -359,6 +362,7 @@ void kunit_init_test(struct kunit *test, const char *name, struct string_stream test->log = log;if (test->log)string_stream_clear (log); + test->attr = attributes; test->status =KUNIT_SUCCESS ; test->status_comment[0 ] ='\0' ;kunit_init_params (test);
@@ -724,7 +728,7 @@ kunit_run_param_test(struct kunit_suite *suite, struct kunit_case *test_case, .param_index = ++test->param_index, .parent = test, }; -kunit_init_test (¶m_test, test_case->name,NULL ); +kunit_init_test (¶m_test, test_case->name,NULL , &test_case->attr); param_test.log = test_case->log;kunit_run_case_catch_errors (suite, test_case, ¶m_test);
@@ -764,7 +768,7 @@ kunit_run_one_test(struct kunit_suite *suite, struct kunit_case *test_case,struct kunit test = { .param_value =NULL , .param_index =0 };struct kunit_result_stats param_stats = {0 }; -kunit_init_test (&test, test_case->name, test_case->log); +kunit_init_test (&test, test_case->name, test_case->log, &test_case->attr);if (test_case->status ==KUNIT_SKIPPED ) {/* Test marked as skip */ test.status =KUNIT_SKIPPED ;
rust/kernel/kunit.rs +32 -0
@@ -209,6 +209,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,
@@ -284,6 +285,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(),
@@ -335,8 +337,20 @@ pub fn in_kunit_test() -> bool {#[cfg( CONFIG_RUST_KUNIT_SELFTEST )] #[kunit_tests(rust_kernel_kunit)] mod tests { +#![expect(clippy::assertions_on_constants, reason = "Testing failure behavior" )] +use super ::*; +struct TestStruct ; + +impl TestStruct { +// This assert does not get replaced with kunit_assert, since this is not a #[test] +// function. +pub (crate )fn escaped_assert () { +assert! (false ); + } + } +#[test] fn rust_test_kunit_example_test () {assert_eq! (1 +1 ,2 );
@@ -347,6 +361,24 @@ 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_assert_false_success_with_should_panic () { +assert! (false ) + } + +#[test] +#[should_panic] +fn rust_test_should_panic_with_escaped_assert () { +TestStruct ::escaped_assert (); + } +#[test] #[cfg(not(all()))] fn rust_test_kunit_always_disabled_test () {
rust/kernel/lib.rs +41 -2
54 lines not on this page · raw message
rust/macros/kunit.rs +54 -23
104 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [PATCH v3 1/3] rust: kunit: add #[should_panic] support
Quoted 9 lines · Nicolás Antinori
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.Signed-off-by Nicolás Antinori <[email protected]>--- Documentation/rust/testing.rst | 8 ++++- drivers/of/overlay_test.c | 6 +++-
Quoted 10 lines
include/kunit/test.h | 9 ++++- lib/kunit/attributes.c | 18 ++++++++++ lib/kunit/kunit-test.c | 36 ++++++++++++++++---- lib/kunit/platform-test.c | 6 +++- lib/kunit/string-stream-test.c | 9 ++++- lib/kunit/test.c | 10 ++++-- rust/kernel/kunit.rs | 32 ++++++++++++++++++ rust/kernel/lib.rs | 43 +++++++++++++++++++++-- rust/macros/kunit.rs | 77 +++++++++++++++++++++++++++++------------- 11 files changed, 215 insertions(+), 39 deletions(-)
Re: [PATCH v3 1/3] rust: kunit: add #[should_panic] support
In reply to Nicolás AntinoriLe 14/11/2026 à 02:20, 'Nicolás Antinori via B4 Relay' via KUnit Development a écrit :
Quoted 9 lines
From: Nicolás Antinori <[email protected]>
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.Signed-off-by Nicolás Antinori <[email protected]>---
Okay -- this looks good to go to me. Thanks very much for all of your effort!
I'm not 100% happy with how pushing the attributes into struct kunit has balooned into all of the different kunit_init_test() call, but I think all of the other options are either worse, or involve even more invasive refactoring. (That being said, I do think this might be the thing which finally makes me look into refactoring how we handle the struct kunit / struct kunit_case dichotomy better... :-))
It's also definitely working on all of the architectures I test now, so that's a relief.
Cheers,
-- David
Quoted 545 lines
Documentation/rust/testing.rst | 8 ++++- drivers/of/overlay_test.c | 6 +++- include/kunit/test.h | 9 ++++- lib/kunit/attributes.c | 18 ++++++++++ lib/kunit/kunit-test.c | 36 ++++++++++++++++---- lib/kunit/platform-test.c | 6 +++- lib/kunit/string-stream-test.c | 9 ++++- lib/kunit/test.c | 10 ++++-- rust/kernel/kunit.rs | 32 ++++++++++++++++++ rust/kernel/lib.rs | 43 +++++++++++++++++++++-- rust/macros/kunit.rs | 77 +++++++++++++++++++++++++++++------------- 11 files changed, 215 insertions(+), 39 deletions(-)Documentation/rust/testing.rst +7
-1@@ -169,8 +169,14 @@ And if we run it, the kernel log would look like:: ok 1 test_f ok 1 rust_kernel_mymod +To test code paths that are expected to produce a Rust panic, the +``#[should_panic]`` attribute can be used. When this attribute is used, tests +that produce a panic (either with ``panic!`` or an ``assert!``) will pass. + Like documentation tests, the ``assert!`` and ``assert_eq!`` macros are mapped -back to KUnit and do not panic. Similarly, the +back to KUnit and do not panic. The exception is tests marked with +``#[should_panic]``, which use the standard Rust ``assert!``/``assert_eq!`` +macros so that failed assertions are handled by the panic logic. Similarly, the `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_ operator is supported, i.e. the test functions may return either nothing (i.e. the unit type ``()``) or ``Result`` (i.e. any ``Result<T, E>``). For instance:drivers/of/overlay_test.c +5
-1@@ -63,6 +63,10 @@ static void of_overlay_apply_kunit_cleanup(struct kunit *test)struct platform_device *pdev;struct device *dev;struct device_node *np; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + };of_root_kunit_skip (test);if (!IS_ENABLED (CONFIG_OF_OVERLAY ))@@ -70,7 +74,7 @@ static void of_overlay_apply_kunit_cleanup(struct kunit *test)if (!IS_ENABLED (CONFIG_OF_EARLY_FLATTREE ))kunit_skip (test,"requires CONFIG_OF_EARLY_FLATTREE for root node" ); -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake.status,KUNIT_SUCCESS ); KUNIT_ASSERT_EQ(test, 0,include/kunit/test.h +8
-1@@ -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; };/** @@ -355,6 +356,9 @@ struct kunit {char status_comment[KUNIT_STATUS_COMMENT_SIZE ];/* Saves the last seen test. Useful to help with faults. */ struct kunit_loc last_seen; + +/* The attributes associated with the test */ +struct kunit_attributes *attr; };static inline void kunit_set_failure (struct kunit *test)@@ -369,7 +373,10 @@ const char *kunit_filter_glob(void);char *kunit_filter (void );char *kunit_filter_action (void ); -void kunit_init_test (struct kunit *test,const char *name,struct string_stream *log); +void kunit_init_test (struct kunit *test, +const char *name, +struct string_stream *log, +struct kunit_attributes *attr);int kunit_run_tests (struct kunit_suite *suite);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/kunit-test.c +30
-6@@ -186,7 +186,7 @@ static void kunit_resource_test_init_resources(struct kunit *test) {struct kunit_test_resource_context *ctx = test->priv; -kunit_init_test (&ctx->test,"testing_test_init_test" ,NULL ); +kunit_init_test (&ctx->test,"testing_test_init_test" ,NULL , ctx->test.attr);KUNIT_EXPECT_TRUE (test,list_empty (&ctx->test.resources)); }@@ -539,12 +539,19 @@ static void kunit_resource_test_action_ordering(struct kunit *test)static int kunit_resource_test_init (struct kunit *test) {struct kunit_test_resource_context *ctx =kzalloc_obj (*ctx); +struct kunit_attributes *ctx_test_attr;KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx); test->priv = ctx; -kunit_init_test (&ctx->test,"test_test_context" ,NULL ); + ctx_test_attr =kzalloc_obj (*ctx_test_attr,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx_test_attr); + + ctx_test_attr->speed =KUNIT_SPEED_NORMAL ; + ctx_test_attr->rust_should_panic = false; + +kunit_init_test (&ctx->test,"test_test_context" ,NULL , ctx_test_attr);return 0 ; }@@ -553,6 +560,7 @@ static void kunit_resource_test_exit(struct kunit *test) {struct kunit_test_resource_context *ctx = test->priv; +kfree (ctx->test.attr);kunit_cleanup (&ctx->test);kfree (ctx); }@@ -666,8 +674,12 @@ static struct kunit_suite kunit_log_test_suite = {static void kunit_status_set_failure_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_EXPECT_EQ (test, fake.status, (enum kunit_status )KUNIT_SUCCESS );kunit_set_failure (&fake);@@ -677,8 +689,12 @@ static void kunit_status_set_failure_test(struct kunit *test)static void kunit_status_mark_skipped_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);/* Before: Should be SUCCESS with no comment. */ KUNIT_EXPECT_EQ (test, fake.status,KUNIT_SUCCESS );@@ -715,8 +731,12 @@ static void kunit_current_test(struct kunit *test)static void kunit_current_fail_test (struct kunit *test) {struct kunit fake; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"fake test" ,NULL ); +kunit_init_test (&fake,"fake test" ,NULL , &attr);KUNIT_EXPECT_EQ (test, fake.status,KUNIT_SUCCESS );/* Set current->kunit_test to fake test. */ @@ -881,8 +901,12 @@ static void kunit_stub_test(struct kunit *test)void *real_fn_addr;void *replacement_addr; } *stub_ctx; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake_test,"kunit_stub_fake_test" ,NULL ); +kunit_init_test (&fake_test,"kunit_stub_fake_test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake_test.status,KUNIT_SUCCESS );KUNIT_ASSERT_EQ (test,list_count_nodes (&fake_test.resources),0 );lib/kunit/platform-test.c +5
-1@@ -71,8 +71,12 @@ static void kunit_platform_device_add_cleans_up(struct kunit *test)const int id =-1 ;struct kunit fake;struct device *dev; +struct kunit_attributes attr = { + .speed =KUNIT_SPEED_NORMAL , + .rust_should_panic = false, + }; -kunit_init_test (&fake,"kunit_platform_device_add_fake_test" ,NULL ); +kunit_init_test (&fake,"kunit_platform_device_add_fake_test" ,NULL , &attr);KUNIT_ASSERT_EQ (test, fake.status,KUNIT_SUCCESS ); pdev =kunit_platform_device_alloc (&fake, name, id);lib/kunit/string-stream-test.c +8
-1@@ -122,11 +122,18 @@ static void string_stream_resource_free_test(struct kunit *test) {struct string_stream_test_priv *priv = test->priv;struct kunit *fake_test; +struct kunit_attributes *fake_attr; fake_test =kunit_kzalloc (test,sizeof (*fake_test),GFP_KERNEL );KUNIT_ASSERT_NOT_ERR_OR_NULL (test, fake_test); -kunit_init_test (fake_test,"string_stream_fake_test" ,NULL ); + fake_attr =kunit_kzalloc (test,sizeof (*fake_attr),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, fake_attr); + + fake_attr->speed =KUNIT_SPEED_NORMAL ; + fake_attr->rust_should_panic = false; + +kunit_init_test (fake_test,"string_stream_fake_test" ,NULL , fake_attr); fake_test->priv = priv;/* lib/kunit/test.c +7
-3@@ -351,7 +351,10 @@ static void kunit_init_params(struct kunit *test) test->params_array.elem_size =0 ; } -void kunit_init_test (struct kunit *test,const char *name,struct string_stream *log) +void kunit_init_test (struct kunit *test, +const char *name, +struct string_stream *log, +struct kunit_attributes *attributes) {spin_lock_init (&test->lock);INIT_LIST_HEAD (&test->resources);@@ -359,6 +362,7 @@ void kunit_init_test(struct kunit *test, const char *name, struct string_stream test->log = log;if (test->log)string_stream_clear (log); + test->attr = attributes; test->status =KUNIT_SUCCESS ; test->status_comment[0 ] ='\0' ;kunit_init_params (test);@@ -724,7 +728,7 @@ kunit_run_param_test(struct kunit_suite *suite, struct kunit_case *test_case, .param_index = ++test->param_index, .parent = test, }; -kunit_init_test (¶m_test, test_case->name,NULL ); +kunit_init_test (¶m_test, test_case->name,NULL , &test_case->attr); param_test.log = test_case->log;kunit_run_case_catch_errors (suite, test_case, ¶m_test);@@ -764,7 +768,7 @@ kunit_run_one_test(struct kunit_suite *suite, struct kunit_case *test_case,struct kunit test = { .param_value =NULL , .param_index =0 };struct kunit_result_stats param_stats = {0 }; -kunit_init_test (&test, test_case->name, test_case->log); +kunit_init_test (&test, test_case->name, test_case->log, &test_case->attr);if (test_case->status ==KUNIT_SKIPPED ) {/* Test marked as skip */ test.status =KUNIT_SKIPPED ;rust/kernel/kunit.rs +32
-0@@ -209,6 +209,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,@@ -284,6 +285,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(),@@ -335,8 +337,20 @@ pub fn in_kunit_test() -> bool {#[cfg( CONFIG_RUST_KUNIT_SELFTEST )] #[kunit_tests(rust_kernel_kunit)] mod tests { +#![expect(clippy::assertions_on_constants, reason = "Testing failure behavior" )] +use super ::*; +struct TestStruct ; + +impl TestStruct { +// This assert does not get replaced with kunit_assert, since this is not a #[test] +// function. +pub (crate )fn escaped_assert () { +assert! (false ); + } + } +#[test] fn rust_test_kunit_example_test () {assert_eq! (1 +1 ,2 );@@ -347,6 +361,24 @@ 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_assert_false_success_with_should_panic () { +assert! (false ) + } + +#[test] +#[should_panic] +fn rust_test_should_panic_with_escaped_assert () { +TestStruct ::escaped_assert (); + } +#[test] #[cfg(not(all()))] fn rust_test_kunit_always_disabled_test () {rust/kernel/lib.rs +41
-2@@ -179,13 +179,52 @@ impl ModuleMetadata for LocalModule { }#[cfg(not(testlib))] -#[panic_handler] -fn panic (info: &core::panic::PanicInfo <'_>) -> ! { +#[inline] +fn bug_on_panic (info: &core::panic::PanicInfo <'_>) -> ! {pr_emerg! ("{}\n" , info);// SAFETY: FFI call. unsafe { bindings::BUG () }; } +#[cfg(all(not(testlib), not( CONFIG_KUNIT = "y" )))] +#[panic_handler] +fn panic (info: &core::panic::PanicInfo <'_>) -> ! { +bug_on_panic (info); +} + +#[cfg(all(not(testlib), CONFIG_KUNIT = "y" ))] +#[panic_handler] +fn panic (info: &core::panic::PanicInfo <'_>) -> ! { +// SAFETY: This function is safe to call even if CONFIG_KUNIT=n. If a null pointer is returned, +// the panic is handled same as if CONFIG_KUNIT=n. +let kunit_test =unsafe { ::bindings::kunit_get_current_test () }; +if kunit_test.is_null () { +bug_on_panic (info); + }else { +// SAFETY: We are in the else branch of kunit_test.is_null() condition, meaning that +// `::bindings::kunit_get_current_test()` returned a kunit struct successfully. +let test_attributes =unsafe { (*kunit_test).attr }; +if test_attributes.is_null () { +use crate ::str::CStrExt as _; +// SAFETY: Test name should be set by KUnit framework at this stage. +let test_str =unsafe { str::CStr ::from_char_ptr ((*kunit_test).name.cast ()) }; +pr_emerg! ("Test case {} has no attributes\n" , test_str); +bug_on_panic (info); + } +// SAFETY: We already tested that test_attributes.is_null() is false, meaning that it is +// safe to retrieve its attributes. +else if unsafe { (*test_attributes).rust_should_panic } { +// SAFETY: We are in the else branch of kunit_test.is_null() condition, meaning that +// `::bindings::kunit_get_current_test()` returned a kunit struct successfully. +unsafe { + bindings::__kunit_abort (kunit_test); + }; + }else { +bug_on_panic (info); + } + } +} +/// Produces a pointer to an object from a pointer to one of its fields. /// /// If you encounter a type mismatch due to the [`Opaque`] type, then use [`Opaque::cast_into`] or rust/macros/kunit.rs +54
-23@@ -106,25 +106,40 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Toke .cloned() .collect (); -// Before the test, override usual `assert!` and `assert_eq!` macros with ones that call -// KUnit instead. +let should_panic = f + .attrs + .extract_if (.., |attr| attr.path ().is_ident ("should_panic" )) + .count () + >0 ; + +// Inside the test, override usual `assert!` and `assert_eq!` macros with ones that call +// KUnit instead unless the test should panic. For tests expected to panic, assertions are +// not overwritten so they can be handled by the Rust's panic handler. let test_str = test.to_string (); - processed_items.push (parse_quote! { -#[allow(unused)] -macro_rules! assert { - ($cond:expr $(,)?) => {{ - kernel::kunit_assert!(#test_str, $cond); - }} - } - }); - processed_items.push (parse_quote! { -#[allow(unused)] -macro_rules! assert_eq { - ($left:expr, $right:expr $(,)?) => {{ - kernel::kunit_assert_eq!(#test_str, $left, $right); - }} - } - }); +if !should_panic { + f.block.stmts.insert ( +0 , +parse_quote! { +#[allow(unused)] +macro_rules! assert { + ($cond:expr $(,)?) => {{ + kernel::kunit_assert!(#test_str, $cond); + }} + } + }, + ); + f.block.stmts.insert ( +0 , +parse_quote! { +#[allow(unused)] +macro_rules! assert_eq { + ($left:expr, $right:expr $(,)?) => {{ + kernel::kunit_assert_eq!(#test_str, $left, $right); + }} + } + }, + ); + }// Add back the test item. processed_items.push (Item ::Fn (f));@@ -134,25 +149,41 @@ 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 (); + ::kernel::kunit::err (::kernel::prelude::fmt!( +" Expected {} to panic\n" , #test_str + )); + (*_test).status = ::kernel::bindings::kunit_status_KUNIT_FAILURE; + ) + }else { +quote! ( +use ::kernel::kunit::is_test_result_ok; + kernel::kunit_assert!(#test_str,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 ;
PATCH v3 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 | 36 ++++++++++++++++++++---------------- 2 files changed, 42 insertions(+), 16 deletions(-)
rust/kernel/kunit.rs +22 -0
@@ -361,6 +361,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 +20 -16
@@ -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]`. //
@@ -144,7 +146,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(),
@@ -164,18 +166,12 @@ macro_rules! assert_eq { ) }; processed_items.push (parse_quote! { +// Prepend any `cfg` attributes before the function declaration to activate it only in +// cases the configs are on + #(#cfg_attrs)*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; - #assertion - } + (*_test).status = ::kernel::bindings::kunit_status_KUNIT_SUCCESS; + #assertion } });
@@ -184,15 +180,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 v3 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.
Also, move the #[test] attribute above other attributes to match existing tests.
--- rust/kernel/bitmap.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
rust/kernel/bitmap.rs +9 -9
@@ -777,15 +777,15 @@ fn owned_bitmap_out_of_bounds() -> Result<(), AllocError> {Ok (()) } -// TODO: uncomment once kunit supports `#[should_panic]`. -// #[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); -// } +#[test] +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +#[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