// SPDX-License-Identifier: GPL-2.012//! KUnit-based macros for Rust unit tests.3//!4//! C header: [`include/kunit/test.h`](srctree/include/kunit/test.h)5//!6//! Reference: <https://docs.kernel.org/dev-tools/kunit/index.html>78use crate::fmt;9use crate::prelude::*;1011#[cfg(CONFIG_PRINTK)]12use crate::c_str;1314/// Prints a KUnit error-level message.15///16/// Public but hidden since it should only be used from KUnit generated code.17#[doc(hidden)]18pub fn err(args: fmt::Arguments<'_>) {19// SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we20// are passing.21#[cfg(CONFIG_PRINTK)]22unsafe {23bindings::_printk(24c_str!("\x013%pA").as_char_ptr(),25core::ptr::from_ref(&args).cast::<c_void>(),26);27}28}2930/// Prints a KUnit info-level message.31///32/// Public but hidden since it should only be used from KUnit generated code.33#[doc(hidden)]34pub fn info(args: fmt::Arguments<'_>) {35// SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we36// are passing.37#[cfg(CONFIG_PRINTK)]38unsafe {39bindings::_printk(40c_str!("\x016%pA").as_char_ptr(),41core::ptr::from_ref(&args).cast::<c_void>(),42);43}44}4546/// Asserts that a boolean expression is `true` at runtime.47///48/// Public but hidden since it should only be used from generated tests.49///50/// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit51/// facilities. See [`assert!`] for more details.52#[doc(hidden)]53#[macro_export]54macro_rules! kunit_assert {55($name:literal, $file:literal, $diff:expr, $condition:expr $(,)?) => {56'out: {57// Do nothing if the condition is `true`.58if $condition {59break 'out;60}6162static FILE: &'static $crate::str::CStr = $crate::c_str!($file);63static LINE: i32 = ::core::line!() as i32 - $diff;64static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));6566// SAFETY: FFI call without safety requirements.67let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() };68if kunit_test.is_null() {69// The assertion failed but this task is not running a KUnit test, so we cannot call70// KUnit, but at least print an error to the kernel log. This may happen if this71// macro is called from an spawned thread in a test (see72// `scripts/rustdoc_test_gen.rs`) or if some non-test code calls this macro by73// mistake (it is hidden to prevent that).74//75// This mimics KUnit's failed assertion format.76$crate::kunit::err($crate::prelude::fmt!(77" # {}: ASSERTION FAILED at {FILE}:{LINE}\n",78$name79));80$crate::kunit::err($crate::prelude::fmt!(81" Expected {CONDITION} to be true, but is false\n"82));83$crate::kunit::err($crate::prelude::fmt!(84" Failure not reported to KUnit since this is a non-KUnit task\n"85));86break 'out;87}8889#[repr(transparent)]90struct Location($crate::bindings::kunit_loc);9192#[repr(transparent)]93struct UnaryAssert($crate::bindings::kunit_unary_assert);9495// SAFETY: There is only a static instance and in that one the pointer field points to96// an immutable C string.97unsafe impl Sync for Location {}9899// SAFETY: There is only a static instance and in that one the pointer field points to100// an immutable C string.101unsafe impl Sync for UnaryAssert {}102103static LOCATION: Location = Location($crate::bindings::kunit_loc {104file: $crate::str::as_char_ptr_in_const_context(FILE),105line: LINE,106});107static ASSERTION: UnaryAssert = UnaryAssert($crate::bindings::kunit_unary_assert {108assert: $crate::bindings::kunit_assert {},109condition: $crate::str::as_char_ptr_in_const_context(CONDITION),110expected_true: true,111});112113// SAFETY:114// - FFI call.115// - The `kunit_test` pointer is valid because we got it from116// `kunit_get_current_test()` and it was not null. This means we are in a KUnit117// test, and that the pointer can be passed to KUnit functions and assertions.118// - The string pointers (`file` and `condition` above) point to null-terminated119// strings since they are `CStr`s.120// - The function pointer (`format`) points to the proper function.121// - The pointers passed will remain valid since they point to `static`s.122// - The format string is allowed to be null.123// - There are, however, problems with this: first of all, this will end up stopping124// the thread, without running destructors. While that is problematic in itself,125// it is considered UB to have what is effectively a forced foreign unwind126// with `extern "C"` ABI. One could observe the stack that is now gone from127// another thread. We should avoid pinning stack variables to prevent library UB,128// too. For the moment, given that test failures are reported immediately before the129// next test runs, that test failures should be fixed and that KUnit is explicitly130// documented as not suitable for production environments, we feel it is reasonable.131unsafe {132$crate::bindings::__kunit_do_failed_assertion(133kunit_test,134::core::ptr::addr_of!(LOCATION.0),135$crate::bindings::kunit_assert_type_KUNIT_ASSERTION,136::core::ptr::addr_of!(ASSERTION.0.assert),137Some($crate::bindings::kunit_unary_assert_format),138::core::ptr::null(),139);140}141142// SAFETY: FFI call; the `test` pointer is valid because this hidden macro should only143// be called by the generated documentation tests which forward the test pointer given144// by KUnit.145unsafe {146$crate::bindings::__kunit_abort(kunit_test);147}148}149};150}151152/// Asserts that two expressions are equal to each other (using [`PartialEq`]).153///154/// Public but hidden since it should only be used from generated tests.155///156/// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit157/// facilities. See [`assert!`] for more details.158#[doc(hidden)]159#[macro_export]160macro_rules! kunit_assert_eq {161($name:literal, $file:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{162// For the moment, we just forward to the expression assert because, for binary asserts,163// KUnit supports only a few types (e.g. integers).164$crate::kunit_assert!($name, $file, $diff, $left == $right);165}};166}167168trait TestResult {169fn is_test_result_ok(&self) -> bool;170}171172impl TestResult for () {173fn is_test_result_ok(&self) -> bool {174true175}176}177178impl<T, E> TestResult for Result<T, E> {179fn is_test_result_ok(&self) -> bool {180self.is_ok()181}182}183184/// Returns whether a test result is to be considered OK.185///186/// This will be `assert!`ed from the generated tests.187#[doc(hidden)]188#[expect(private_bounds)]189pub fn is_test_result_ok(t: impl TestResult) -> bool {190t.is_test_result_ok()191}192193/// Represents an individual test case.194///195/// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of valid test cases.196/// Use [`kunit_case_null`] to generate such a delimiter.197#[doc(hidden)]198pub const fn kunit_case(199name: &'static kernel::str::CStr,200run_case: unsafe extern "C" fn(*mut kernel::bindings::kunit),201) -> kernel::bindings::kunit_case {202kernel::bindings::kunit_case {203run_case: Some(run_case),204name: kernel::str::as_char_ptr_in_const_context(name),205attr: kernel::bindings::kunit_attributes {206speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL,207},208generate_params: None,209status: kernel::bindings::kunit_status_KUNIT_SUCCESS,210module_name: core::ptr::null_mut(),211log: core::ptr::null_mut(),212param_init: None,213param_exit: None,214}215}216217/// Represents the NULL test case delimiter.218///219/// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of test cases. This220/// function returns such a delimiter.221#[doc(hidden)]222pub const fn kunit_case_null() -> kernel::bindings::kunit_case {223kernel::bindings::kunit_case {224run_case: None,225name: core::ptr::null_mut(),226generate_params: None,227attr: kernel::bindings::kunit_attributes {228speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL,229},230status: kernel::bindings::kunit_status_KUNIT_SUCCESS,231module_name: core::ptr::null_mut(),232log: core::ptr::null_mut(),233param_init: None,234param_exit: None,235}236}237238/// Registers a KUnit test suite.239///240/// # Safety241///242/// `test_cases` must be a NULL terminated array of valid test cases,243/// whose lifetime is at least that of the test suite (i.e., static).244///245/// # Examples246///247/// ```ignore248/// extern "C" fn test_fn(_test: *mut kernel::bindings::kunit) {249/// let actual = 1 + 1;250/// let expected = 2;251/// assert_eq!(actual, expected);252/// }253///254/// static mut KUNIT_TEST_CASES: [kernel::bindings::kunit_case; 2] = [255/// kernel::kunit::kunit_case(kernel::c_str!("name"), test_fn),256/// kernel::kunit::kunit_case_null(),257/// ];258/// kernel::kunit_unsafe_test_suite!(suite_name, KUNIT_TEST_CASES);259/// ```260#[doc(hidden)]261#[macro_export]262macro_rules! kunit_unsafe_test_suite {263($name:ident, $test_cases:ident) => {264const _: () = {265const KUNIT_TEST_SUITE_NAME: [::kernel::ffi::c_char; 256] = {266let name_u8 = ::core::stringify!($name).as_bytes();267let mut ret = [0; 256];268269if name_u8.len() > 255 {270panic!(concat!(271"The test suite name `",272::core::stringify!($name),273"` exceeds the maximum length of 255 bytes."274));275}276277let mut i = 0;278while i < name_u8.len() {279ret[i] = name_u8[i] as ::kernel::ffi::c_char;280i += 1;281}282283ret284};285286static mut KUNIT_TEST_SUITE: ::kernel::bindings::kunit_suite =287::kernel::bindings::kunit_suite {288name: KUNIT_TEST_SUITE_NAME,289#[allow(unused_unsafe)]290// SAFETY: `$test_cases` is passed in by the user, and291// (as documented) must be valid for the lifetime of292// the suite (i.e., static).293test_cases: unsafe {294::core::ptr::addr_of_mut!($test_cases)295.cast::<::kernel::bindings::kunit_case>()296},297suite_init: None,298suite_exit: None,299init: None,300exit: None,301attr: ::kernel::bindings::kunit_attributes {302speed: ::kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL,303},304status_comment: [0; 256usize],305debugfs: ::core::ptr::null_mut(),306log: ::core::ptr::null_mut(),307suite_init_err: 0,308is_init: false,309};310311#[used(compiler)]312#[allow(unused_unsafe)]313#[cfg_attr(not(target_os = "macos"), link_section = ".kunit_test_suites")]314static mut KUNIT_TEST_SUITE_ENTRY: *const ::kernel::bindings::kunit_suite =315// SAFETY: `KUNIT_TEST_SUITE` is static.316unsafe { ::core::ptr::addr_of_mut!(KUNIT_TEST_SUITE) };317};318};319}320321/// Returns whether we are currently running a KUnit test.322///323/// In some cases, you need to call test-only code from outside the test case, for example, to324/// create a function mock. This function allows to change behavior depending on whether we are325/// currently running a KUnit test or not.326///327/// # Examples328///329/// This example shows how a function can be mocked to return a well-known value while testing:330///331/// ```332/// # use kernel::kunit::in_kunit_test;333/// fn fn_mock_example(n: i32) -> i32 {334/// if in_kunit_test() {335/// return 100;336/// }337///338/// n + 1339/// }340///341/// let mock_res = fn_mock_example(5);342/// assert_eq!(mock_res, 100);343/// ```344pub fn in_kunit_test() -> bool {345// SAFETY: `kunit_get_current_test()` is always safe to call (it has fallbacks for346// when KUnit is not enabled).347!unsafe { bindings::kunit_get_current_test() }.is_null()348}349350#[kunit_tests(rust_kernel_kunit)]351mod tests {352use super::*;353354#[test]355fn rust_test_kunit_example_test() {356assert_eq!(1 + 1, 2);357}358359#[test]360fn rust_test_kunit_in_kunit_test() {361assert!(in_kunit_test());362}363364#[test]365#[cfg(not(all()))]366fn rust_test_kunit_always_disabled_test() {367// This test should never run because of the `cfg`.368assert!(false);369}370}371372373