* [PATCH v3 0/3] rust: kunit: support #[should_panic] and same test name with different #[cfg(...)]
@ 2026-11-13 18:20 Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 1/3] rust: kunit: add #[should_panic] support Nicolás Antinori via B4 Relay
` (2 more replies)
0 siblings, 3 replies; 4+ messages in thread
From: Nicolás Antinori via B4 Relay @ 2026-11-13 18:20 UTC (permalink / raw)
To: Alice Ryhl, Benno Lossin, Boqun Feng, Brendan Higgins,
Daniel Almeida, Danilo Krummrich, David Gow, Gary Guo,
Miguel Ojeda, Onur Özkan
Cc: Shuah Khan, Alexandre Courbot, Andreas Hindborg,
Björn Roy Baron, Burak Emir, Rae Moar, Tamir Duberstein,
Trevor Gross, Yury Norov, kunit-dev, linux-kernel,
linux-kselftest, rust-for-linux, linux-doc,
Nicolás Antinori
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/20261029-rust_kunit_v6_send-v2-0-5ce551efc48e@gmail.com/
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/20260930-rust_kunit_v4-v1-0-e3b0d45311dd@gmail.com?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/20260930-rust_kunit_v4-v1-0-e3b0d45311dd@gmail.com/
- RFC patch: https://lore.kernel.org/rust-for-linux/cover.1789500084.git.nico.antinori.7@gmail.com/
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/DM41PHVITKOG.3I6P2X8048BEP@gmail.com/
[4] https://github.com/Rust-for-Linux/linux/blob/fd73f4a6659897191fa0d40695fe370925dd3780/rust/kernel/kunit.rs#L129-L136
Signed-off-by: Nicolás Antinori <nico.antinori.7@gmail.com>
---
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,
--
Nicolás Antinori <nico.antinori.7@gmail.com>
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH v3 1/3] rust: kunit: add #[should_panic] support
2026-11-13 18:20 [PATCH v3 0/3] rust: kunit: support #[should_panic] and same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
@ 2026-11-13 18:20 ` Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 2/3] rust: kunit: allow same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 3/3] rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case Nicolás Antinori via B4 Relay
2 siblings, 0 replies; 4+ messages in thread
From: Nicolás Antinori via B4 Relay @ 2026-11-13 18:20 UTC (permalink / raw)
To: Alice Ryhl, Benno Lossin, Boqun Feng, Brendan Higgins,
Daniel Almeida, Danilo Krummrich, David Gow, Gary Guo,
Miguel Ojeda, Onur Özkan
Cc: Shuah Khan, Alexandre Courbot, Andreas Hindborg,
Björn Roy Baron, Burak Emir, Rae Moar, Tamir Duberstein,
Trevor Gross, Yury Norov, kunit-dev, linux-kernel,
linux-kselftest, rust-for-linux, linux-doc,
Nicolás Antinori
From: Nicolás Antinori <nico.antinori.7@gmail.com>
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 <nico.antinori.7@gmail.com>
---
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(-)
diff --git a/Documentation/rust/testing.rst b/Documentation/rust/testing.rst
index 73046523a9a27393648cb4aeaeb055b745357c6d..6a82ac5885cecfd2e12839c64fdbf50428502344 100644
--- a/Documentation/rust/testing.rst
+++ b/Documentation/rust/testing.rst
@@ -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:
diff --git a/drivers/of/overlay_test.c b/drivers/of/overlay_test.c
index c787524c5a887cdf87e5acc98982733e02feb847..55df32ea1e5b947e23968afd17b0ed1ca9ed5088 100644
--- a/drivers/of/overlay_test.c
+++ b/drivers/of/overlay_test.c
@@ -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,
diff --git a/include/kunit/test.h b/include/kunit/test.h
index 31d549578f8ec113bef9b5d72bc9355c07fce3c0..43c48a1b3684f5ca7ed237a7606a22d7d0c9fb31 100644
--- a/include/kunit/test.h
+++ b/include/kunit/test.h
@@ -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);
diff --git a/lib/kunit/attributes.c b/lib/kunit/attributes.c
index 6d7a53af94a9acf3cf336409462059b972efeb22..8a9dc526b3cb2d363d42087f8666a03e9bc2bc4b 100644
--- a/lib/kunit/attributes.c
+++ b/lib/kunit/attributes.c
@@ -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,
}
};
diff --git a/lib/kunit/kunit-test.c b/lib/kunit/kunit-test.c
index 126e30879dad652d5b236aeb13d4406a4ddbab00..e2219e1e37501406ae7991895483fb28872f4339 100644
--- a/lib/kunit/kunit-test.c
+++ b/lib/kunit/kunit-test.c
@@ -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);
diff --git a/lib/kunit/platform-test.c b/lib/kunit/platform-test.c
index e3debb8fbcef36f22418310ae6a0c14be0859ce3..4e60079a8a0bc1a0de6954dab2c8ca09985e9dd9 100644
--- a/lib/kunit/platform-test.c
+++ b/lib/kunit/platform-test.c
@@ -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);
diff --git a/lib/kunit/string-stream-test.c b/lib/kunit/string-stream-test.c
index 7734e33156f9456eebfdca5b82972c010fb4e7df..3f43fb3dc144dfa3f7890ff9c47b08d7e9045e1e 100644
--- a/lib/kunit/string-stream-test.c
+++ b/lib/kunit/string-stream-test.c
@@ -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;
/*
diff --git a/lib/kunit/test.c b/lib/kunit/test.c
index 09e3dabfac0c945b2608feb88c1b1d46fb807edc..0ef869385c435f2394db629301f62916b840064b 100644
--- a/lib/kunit/test.c
+++ b/lib/kunit/test.c
@@ -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;
diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs
index 25ff272d29b2b3f192a3968481c1d5417df4335b..be02b9e4ae70f4913a5074c512d4adf78e34335c 100644
--- a/rust/kernel/kunit.rs
+++ b/rust/kernel/kunit.rs
@@ -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() {
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 1ab41129d557a97c09b4fb1bfc6aadb4250156a7..ba9e1a07aab8cf1f91d44c09e3a8e2291781d32a 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -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
diff --git a/rust/macros/kunit.rs b/rust/macros/kunit.rs
index e9152b9d51f9450b7e549e2e1629b5fc5f485a28..ac7495deab17d6579e3f213b7018516c9ca68425 100644
--- a/rust/macros/kunit.rs
+++ b/rust/macros/kunit.rs
@@ -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;
--
2.47.3
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH v3 2/3] rust: kunit: allow same test name with different #[cfg(...)]
2026-11-13 18:20 [PATCH v3 0/3] rust: kunit: support #[should_panic] and same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 1/3] rust: kunit: add #[should_panic] support Nicolás Antinori via B4 Relay
@ 2026-11-13 18:20 ` Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 3/3] rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case Nicolás Antinori via B4 Relay
2 siblings, 0 replies; 4+ messages in thread
From: Nicolás Antinori via B4 Relay @ 2026-11-13 18:20 UTC (permalink / raw)
To: Alice Ryhl, Benno Lossin, Boqun Feng, Brendan Higgins,
Daniel Almeida, Danilo Krummrich, David Gow, Gary Guo,
Miguel Ojeda, Onur Özkan
Cc: Shuah Khan, Alexandre Courbot, Andreas Hindborg,
Björn Roy Baron, Burak Emir, Rae Moar, Tamir Duberstein,
Trevor Gross, Yury Norov, kunit-dev, linux-kernel,
linux-kselftest, rust-for-linux, linux-doc,
Nicolás Antinori
From: Nicolás Antinori <nico.antinori.7@gmail.com>
Sometimes 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.
Reviewed-by: David Gow <david@davidgow.net>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Nicolás Antinori <nico.antinori.7@gmail.com>
---
rust/kernel/kunit.rs | 22 ++++++++++++++++++++++
rust/macros/kunit.rs | 36 ++++++++++++++++++++----------------
2 files changed, 42 insertions(+), 16 deletions(-)
diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs
index be02b9e4ae70f4913a5074c512d4adf78e34335c..76be6156f452cc174019e6565b54320967521874 100644
--- a/rust/kernel/kunit.rs
+++ b/rust/kernel/kunit.rs
@@ -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() {
diff --git a/rust/macros/kunit.rs b/rust/macros/kunit.rs
index ac7495deab17d6579e3f213b7018516c9ca68425..476315c3f9e1b9d987b4f4121b36745d83ad87bb 100644
--- a/rust/macros/kunit.rs
+++ b/rust/macros/kunit.rs
@@ -45,6 +45,8 @@ pub(crate) fn kunit_tests(test_suite: Ident, mut module: ItemMod) -> Result<Toke
let 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);
});
--
2.47.3
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH v3 3/3] rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case
2026-11-13 18:20 [PATCH v3 0/3] rust: kunit: support #[should_panic] and same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 1/3] rust: kunit: add #[should_panic] support Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 2/3] rust: kunit: allow same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
@ 2026-11-13 18:20 ` Nicolás Antinori via B4 Relay
2 siblings, 0 replies; 4+ messages in thread
From: Nicolás Antinori via B4 Relay @ 2026-11-13 18:20 UTC (permalink / raw)
To: Alice Ryhl, Benno Lossin, Boqun Feng, Brendan Higgins,
Daniel Almeida, Danilo Krummrich, David Gow, Gary Guo,
Miguel Ojeda, Onur Özkan
Cc: Shuah Khan, Alexandre Courbot, Andreas Hindborg,
Björn Roy Baron, Burak Emir, Rae Moar, Tamir Duberstein,
Trevor Gross, Yury Norov, kunit-dev, linux-kernel,
linux-kselftest, rust-for-linux, linux-doc,
Nicolás Antinori
From: Nicolás Antinori <nico.antinori.7@gmail.com>
Rust 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.
Acked-by: David Gow <david@davidgow.net>
Reviewed-by: Burak Emir <burak.emir@gmail.com>
Signed-off-by: Nicolás Antinori <nico.antinori.7@gmail.com>
---
rust/kernel/bitmap.rs | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/rust/kernel/bitmap.rs b/rust/kernel/bitmap.rs
index 610d565535ccfba6af8f2ca4ac4028fa027a9644..942c0cbc994b80d71bc4b3de67e5730c914e4a7f 100644
--- a/rust/kernel/bitmap.rs
+++ b/rust/kernel/bitmap.rs
@@ -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> {
--
2.47.3
^ permalink raw reply [flat|nested] 4+ messages in thread
end of thread, other threads:[~2026-11-13 18:21 UTC | newest]
Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-13 18:20 [PATCH v3 0/3] rust: kunit: support #[should_panic] and same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 1/3] rust: kunit: add #[should_panic] support Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 2/3] rust: kunit: allow same test name with different #[cfg(...)] Nicolás Antinori via B4 Relay
2026-11-13 18:20 ` [PATCH v3 3/3] rust: bitmap: kunit: uncomment owned_bitmap_out_of_bounds panic case Nicolás Antinori via B4 Relay
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®