Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: kunit: support checked `-> Result`s in KUnit `#[test]`s

Currently, return values of KUnit `#[test]` functions are ignored.

Thus introduce support for `-> Result` functions by checking their
returned values.

At the same time, require that test functions return `()` or `Result<T,
E>`, which should avoid mistakes, especially with non-`#[must_use]`
types. Other types can be supported in the future if needed.

With this, a failing test like:

#[test]
fn my_test() -> Result {
f()?;
Ok(())
}

will output:

[ 3.744214] KTAP version 1
[ 3.744287] # Subtest: my_test_suite
[ 3.744378] # speed: normal
[ 3.744399] 1..1
[ 3.745817] # my_test: ASSERTION FAILED at rust/kernel/lib.rs:321
[ 3.745817] Expected is_test_result_ok(my_test()) to be true, but is false
[ 3.747152] # my_test.speed: normal
[ 3.747199] not ok 1 my_test
[ 3.747345] not ok 4 my_test_suite

Reviewed-by: David Gow <davidgow@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250502215133.1923676-3-ojeda@kernel.org
[ Used `::kernel` for paths. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

+27 -1
+25
rust/kernel/kunit.rs
··· 164 164 }}; 165 165 } 166 166 167 + trait TestResult { 168 + fn is_test_result_ok(&self) -> bool; 169 + } 170 + 171 + impl TestResult for () { 172 + fn is_test_result_ok(&self) -> bool { 173 + true 174 + } 175 + } 176 + 177 + impl<T, E> TestResult for Result<T, E> { 178 + fn is_test_result_ok(&self) -> bool { 179 + self.is_ok() 180 + } 181 + } 182 + 183 + /// Returns whether a test result is to be considered OK. 184 + /// 185 + /// This will be `assert!`ed from the generated tests. 186 + #[doc(hidden)] 187 + #[expect(private_bounds)] 188 + pub fn is_test_result_ok(t: impl TestResult) -> bool { 189 + t.is_test_result_ok() 190 + } 191 + 167 192 /// Represents an individual test case. 168 193 /// 169 194 /// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of valid test cases.
+2 -1
rust/macros/kunit.rs
··· 102 102 let path = crate::helpers::file(); 103 103 for test in &tests { 104 104 let kunit_wrapper_fn_name = format!("kunit_rust_wrapper_{test}"); 105 + // An extra `use` is used here to reduce the length of the message. 105 106 let kunit_wrapper = format!( 106 - "unsafe extern \"C\" fn {kunit_wrapper_fn_name}(_test: *mut ::kernel::bindings::kunit) {{ {test}(); }}" 107 + "unsafe extern \"C\" fn {kunit_wrapper_fn_name}(_test: *mut ::kernel::bindings::kunit) {{ use ::kernel::kunit::is_test_result_ok; assert!(is_test_result_ok({test}())); }}", 107 108 ); 108 109 writeln!(kunit_macros, "{kunit_wrapper}").unwrap(); 109 110 writeln!(