FILE
kunit.rs
File preview with syntax highlighting.
linux-6.19.14/rust/kernel/kunit.rs
1// SPDX-License-Identifier: GPL-2.0 2 3//! KUnit-based macros for Rust unit tests. 4//! 5//! C header: [`include/kunit/test.h`](srctree/include/kunit/test.h) 6//! 7//! Reference: <https://docs.kernel.org/dev-tools/kunit/index.html> 8 9use crate::fmt; 10use crate::prelude::*; 11 12#[cfg(CONFIG_PRINTK)] 13use crate::c_str; 14 15/// Prints a KUnit error-level message. 16/// 17/// Public but hidden since it should only be used from KUnit generated code. 18#[doc(hidden)] 19pub fn err(args: fmt::Arguments<'_>) { 20 // `args` is unused if `CONFIG_PRINTK` is not set - this avoids a build-time warning. 21 #[cfg(not(CONFIG_PRINTK))] 22 let _ = args; 23 24 // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we 25 // are passing. 26 #[cfg(CONFIG_PRINTK)] 27 unsafe { 28 bindings::_printk( 29 c_str!("\x013%pA").as_char_ptr(), 30 core::ptr::from_ref(&args).cast::<c_void>(), 31 ); 32 } 33} 34 35/// Prints a KUnit info-level message. 36/// 37/// Public but hidden since it should only be used from KUnit generated code. 38#[doc(hidden)] 39pub fn info(args: fmt::Arguments<'_>) { 40 // `args` is unused if `CONFIG_PRINTK` is not set - this avoids a build-time warning. 41 #[cfg(not(CONFIG_PRINTK))] 42 let _ = args; 43 44 // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we 45 // are passing. 46 #[cfg(CONFIG_PRINTK)] 47 unsafe { 48 bindings::_printk( 49 c_str!("\x016%pA").as_char_ptr(), 50 core::ptr::from_ref(&args).cast::<c_void>(), 51 ); 52 } 53} 54 55/// Asserts that a boolean expression is `true` at runtime. 56/// 57/// Public but hidden since it should only be used from generated tests. 58/// 59/// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit 60/// facilities. See [`assert!`] for more details. 61#[doc(hidden)] 62#[macro_export] 63macro_rules! kunit_assert { 64 ($name:literal, $file:literal, $diff:expr, $condition:expr $(,)?) => { 65 'out: { 66 // Do nothing if the condition is `true`. 67 if $condition { 68 break 'out; 69 } 70 71 static FILE: &'static $crate::str::CStr = $crate::c_str!($file); 72 static LINE: i32 = ::core::line!() as i32 - $diff; 73 static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition)); 74 75 // SAFETY: FFI call without safety requirements. 76 let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() }; 77 if kunit_test.is_null() { 78 // The assertion failed but this task is not running a KUnit test, so we cannot call 79 // KUnit, but at least print an error to the kernel log. This may happen if this 80 // macro is called from an spawned thread in a test (see 81 // `scripts/rustdoc_test_gen.rs`) or if some non-test code calls this macro by 82 // mistake (it is hidden to prevent that). 83 // 84 // This mimics KUnit's failed assertion format. 85 $crate::kunit::err($crate::prelude::fmt!( 86 " # {}: ASSERTION FAILED at {FILE}:{LINE}\n", 87 $name 88 )); 89 $crate::kunit::err($crate::prelude::fmt!( 90 " Expected {CONDITION} to be true, but is false\n" 91 )); 92 $crate::kunit::err($crate::prelude::fmt!( 93 " Failure not reported to KUnit since this is a non-KUnit task\n" 94 )); 95 break 'out; 96 } 97 98 #[repr(transparent)] 99 struct Location($crate::bindings::kunit_loc); 100 101 #[repr(transparent)] 102 struct UnaryAssert($crate::bindings::kunit_unary_assert); 103 104 // SAFETY: There is only a static instance and in that one the pointer field points to 105 // an immutable C string. 106 unsafe impl Sync for Location {} 107 108 // SAFETY: There is only a static instance and in that one the pointer field points to 109 // an immutable C string. 110 unsafe impl Sync for UnaryAssert {} 111 112 static LOCATION: Location = Location($crate::bindings::kunit_loc { 113 file: $crate::str::as_char_ptr_in_const_context(FILE), 114 line: LINE, 115 }); 116 static ASSERTION: UnaryAssert = UnaryAssert($crate::bindings::kunit_unary_assert { 117 assert: $crate::bindings::kunit_assert {}, 118 condition: $crate::str::as_char_ptr_in_const_context(CONDITION), 119 expected_true: true, 120 }); 121 122 // SAFETY: 123 // - FFI call. 124 // - The `kunit_test` pointer is valid because we got it from 125 // `kunit_get_current_test()` and it was not null. This means we are in a KUnit 126 // test, and that the pointer can be passed to KUnit functions and assertions. 127 // - The string pointers (`file` and `condition` above) point to null-terminated 128 // strings since they are `CStr`s. 129 // - The function pointer (`format`) points to the proper function. 130 // - The pointers passed will remain valid since they point to `static`s. 131 // - The format string is allowed to be null. 132 // - There are, however, problems with this: first of all, this will end up stopping 133 // the thread, without running destructors. While that is problematic in itself, 134 // it is considered UB to have what is effectively a forced foreign unwind 135 // with `extern "C"` ABI. One could observe the stack that is now gone from 136 // another thread. We should avoid pinning stack variables to prevent library UB, 137 // too. For the moment, given that test failures are reported immediately before the 138 // next test runs, that test failures should be fixed and that KUnit is explicitly 139 // documented as not suitable for production environments, we feel it is reasonable. 140 unsafe { 141 $crate::bindings::__kunit_do_failed_assertion( 142 kunit_test, 143 ::core::ptr::addr_of!(LOCATION.0), 144 $crate::bindings::kunit_assert_type_KUNIT_ASSERTION, 145 ::core::ptr::addr_of!(ASSERTION.0.assert), 146 Some($crate::bindings::kunit_unary_assert_format), 147 ::core::ptr::null(), 148 ); 149 } 150 151 // SAFETY: FFI call; the `test` pointer is valid because this hidden macro should only 152 // be called by the generated documentation tests which forward the test pointer given 153 // by KUnit. 154 unsafe { 155 $crate::bindings::__kunit_abort(kunit_test); 156 } 157 } 158 }; 159} 160 161/// Asserts that two expressions are equal to each other (using [`PartialEq`]). 162/// 163/// Public but hidden since it should only be used from generated tests. 164/// 165/// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit 166/// facilities. See [`assert!`] for more details. 167#[doc(hidden)] 168#[macro_export] 169macro_rules! kunit_assert_eq { 170 ($name:literal, $file:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{ 171 // For the moment, we just forward to the expression assert because, for binary asserts, 172 // KUnit supports only a few types (e.g. integers). 173 $crate::kunit_assert!($name, $file, $diff, $left == $right); 174 }}; 175} 176 177trait TestResult { 178 fn is_test_result_ok(&self) -> bool; 179} 180 181impl TestResult for () { 182 fn is_test_result_ok(&self) -> bool { 183 true 184 } 185} 186 187impl<T, E> TestResult for Result<T, E> { 188 fn is_test_result_ok(&self) -> bool { 189 self.is_ok() 190 } 191} 192 193/// Returns whether a test result is to be considered OK. 194/// 195/// This will be `assert!`ed from the generated tests. 196#[doc(hidden)] 197#[expect(private_bounds)] 198pub fn is_test_result_ok(t: impl TestResult) -> bool { 199 t.is_test_result_ok() 200} 201 202/// Represents an individual test case. 203/// 204/// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of valid test cases. 205/// Use [`kunit_case_null`] to generate such a delimiter. 206#[doc(hidden)] 207pub const fn kunit_case( 208 name: &'static kernel::str::CStr, 209 run_case: unsafe extern "C" fn(*mut kernel::bindings::kunit), 210) -> kernel::bindings::kunit_case { 211 kernel::bindings::kunit_case { 212 run_case: Some(run_case), 213 name: kernel::str::as_char_ptr_in_const_context(name), 214 attr: kernel::bindings::kunit_attributes { 215 speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, 216 }, 217 generate_params: None, 218 status: kernel::bindings::kunit_status_KUNIT_SUCCESS, 219 module_name: core::ptr::null_mut(), 220 log: core::ptr::null_mut(), 221 param_init: None, 222 param_exit: None, 223 } 224} 225 226/// Represents the NULL test case delimiter. 227/// 228/// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of test cases. This 229/// function returns such a delimiter. 230#[doc(hidden)] 231pub const fn kunit_case_null() -> kernel::bindings::kunit_case { 232 kernel::bindings::kunit_case { 233 run_case: None, 234 name: core::ptr::null_mut(), 235 generate_params: None, 236 attr: kernel::bindings::kunit_attributes { 237 speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, 238 }, 239 status: kernel::bindings::kunit_status_KUNIT_SUCCESS, 240 module_name: core::ptr::null_mut(), 241 log: core::ptr::null_mut(), 242 param_init: None, 243 param_exit: None, 244 } 245} 246 247/// Registers a KUnit test suite. 248/// 249/// # Safety 250/// 251/// `test_cases` must be a NULL terminated array of valid test cases, 252/// whose lifetime is at least that of the test suite (i.e., static). 253/// 254/// # Examples 255/// 256/// ```ignore 257/// extern "C" fn test_fn(_test: *mut kernel::bindings::kunit) { 258/// let actual = 1 + 1; 259/// let expected = 2; 260/// assert_eq!(actual, expected); 261/// } 262/// 263/// static mut KUNIT_TEST_CASES: [kernel::bindings::kunit_case; 2] = [ 264/// kernel::kunit::kunit_case(kernel::c_str!("name"), test_fn), 265/// kernel::kunit::kunit_case_null(), 266/// ]; 267/// kernel::kunit_unsafe_test_suite!(suite_name, KUNIT_TEST_CASES); 268/// ``` 269#[doc(hidden)] 270#[macro_export] 271macro_rules! kunit_unsafe_test_suite { 272 ($name:ident, $test_cases:ident) => { 273 const _: () = { 274 const KUNIT_TEST_SUITE_NAME: [::kernel::ffi::c_char; 256] = { 275 let name_u8 = ::core::stringify!($name).as_bytes(); 276 let mut ret = [0; 256]; 277 278 if name_u8.len() > 255 { 279 panic!(concat!( 280 "The test suite name `", 281 ::core::stringify!($name), 282 "` exceeds the maximum length of 255 bytes." 283 )); 284 } 285 286 let mut i = 0; 287 while i < name_u8.len() { 288 ret[i] = name_u8[i] as ::kernel::ffi::c_char; 289 i += 1; 290 } 291 292 ret 293 }; 294 295 static mut KUNIT_TEST_SUITE: ::kernel::bindings::kunit_suite = 296 ::kernel::bindings::kunit_suite { 297 name: KUNIT_TEST_SUITE_NAME, 298 #[allow(unused_unsafe)] 299 // SAFETY: `$test_cases` is passed in by the user, and 300 // (as documented) must be valid for the lifetime of 301 // the suite (i.e., static). 302 test_cases: unsafe { 303 ::core::ptr::addr_of_mut!($test_cases) 304 .cast::<::kernel::bindings::kunit_case>() 305 }, 306 suite_init: None, 307 suite_exit: None, 308 init: None, 309 exit: None, 310 attr: ::kernel::bindings::kunit_attributes { 311 speed: ::kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, 312 }, 313 status_comment: [0; 256usize], 314 debugfs: ::core::ptr::null_mut(), 315 log: ::core::ptr::null_mut(), 316 suite_init_err: 0, 317 is_init: false, 318 }; 319 320 #[used(compiler)] 321 #[allow(unused_unsafe)] 322 #[cfg_attr(not(target_os = "macos"), link_section = ".kunit_test_suites")] 323 static mut KUNIT_TEST_SUITE_ENTRY: *const ::kernel::bindings::kunit_suite = 324 // SAFETY: `KUNIT_TEST_SUITE` is static. 325 unsafe { ::core::ptr::addr_of_mut!(KUNIT_TEST_SUITE) }; 326 }; 327 }; 328} 329 330/// Returns whether we are currently running a KUnit test. 331/// 332/// In some cases, you need to call test-only code from outside the test case, for example, to 333/// create a function mock. This function allows to change behavior depending on whether we are 334/// currently running a KUnit test or not. 335/// 336/// # Examples 337/// 338/// This example shows how a function can be mocked to return a well-known value while testing: 339/// 340/// ``` 341/// # use kernel::kunit::in_kunit_test; 342/// fn fn_mock_example(n: i32) -> i32 { 343/// if in_kunit_test() { 344/// return 100; 345/// } 346/// 347/// n + 1 348/// } 349/// 350/// let mock_res = fn_mock_example(5); 351/// assert_eq!(mock_res, 100); 352/// ``` 353pub fn in_kunit_test() -> bool { 354 // SAFETY: `kunit_get_current_test()` is always safe to call (it has fallbacks for 355 // when KUnit is not enabled). 356 !unsafe { bindings::kunit_get_current_test() }.is_null() 357} 358 359#[kunit_tests(rust_kernel_kunit)] 360mod tests { 361 use super::*; 362 363 #[test] 364 fn rust_test_kunit_example_test() { 365 assert_eq!(1 + 1, 2); 366 } 367 368 #[test] 369 fn rust_test_kunit_in_kunit_test() { 370 assert!(in_kunit_test()); 371 } 372 373 #[test] 374 #[cfg(not(all()))] 375 fn rust_test_kunit_always_disabled_test() { 376 // This test should never run because of the `cfg`. 377 assert!(false); 378 } 379}
~/
Read-only file preview.