From patchwork Fri Feb 14 07:40:46 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: David Gow X-Patchwork-Id: 865220 Received: from mail-pj1-f74.google.com (mail-pj1-f74.google.com [209.85.216.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C35DC21578A for ; Fri, 14 Feb 2025 07:41:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739518871; cv=none; b=CoEt/bJZjHVJbW0e0Ng7OL0DXJ5kXYXKiRoSGw9yEoByUH4juVMnlPX4PopeAmWsSThjrNAS/8Del1+mKO0g5fRLM0kSZ3SERiVA4aFwQjKNYhVcH4h8ZrPmlkSTT/vHaewFyFiqiUSMm/toFxiSUxTduo0tZAI5sfnJDecDqEo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739518871; c=relaxed/simple; bh=rRmk5P33y1uYQIpsiuj0sC+e0UqdZNh/NXp5rJbgg74=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=LPVJIDFd/FAuRuaavGGLVEtmy+06ALTAlywP9Ozh28sK0VVg62czeaGMANc5deJElSi0cllqkFtlmgYspfT8ZgeV2lMH1Q7UPRJKGVR0LZFQbFLQplq6qESHq7pqL6KTlfBQFEb6zG/RgIg8TELOIsFYduNC9fnKF9b0xZYhnz8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--davidgow.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=abseRfhQ; arc=none smtp.client-ip=209.85.216.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--davidgow.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="abseRfhQ" Received: by mail-pj1-f74.google.com with SMTP id 98e67ed59e1d1-2fc1cb0c2cbso4166960a91.1 for ; Thu, 13 Feb 2025 23:41:09 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739518869; x=1740123669; darn=vger.kernel.org; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:from:to:cc:subject:date:message-id :reply-to; bh=5TOm5BmvS8v8oQ9kZyES3kYeXrmQfoQNZ+ar7vcR0ek=; b=abseRfhQ7ImKdo7Lv99Oz+y2vY4NBsL9HXSuxktA8/F/+V/XYuZWw6a2E4/d7lItwf rNWISkRPu+Y5gD0sPzEecbhonzJZQbaybFAGbXgMQFEvsgaPu145ctEb19Qpgzo8LgU1 8LEMBMA2lvUhzzVi/W14yEaky9AvrvCEm1tUzwlKmdqTmj6u54oLi0mP0ovlqDwrk3at nVkd+Ce6flcXjdd+CForPyi3MbDpr7bc8Tkq1C8QFZccJeinB6xGro6mq7fRZYZWc5G8 1D4yLKT+7PFmiH39TVY9fcQIjCe6S5FH4ghHY+w3zzYr+aHIT9aey/aEMizdHk/zcY+D jBpQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739518869; x=1740123669; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:x-gm-message-state:from:to:cc:subject :date:message-id:reply-to; bh=5TOm5BmvS8v8oQ9kZyES3kYeXrmQfoQNZ+ar7vcR0ek=; b=ERfqF2Ka6vG1y7HCcvETa5q3UtNkh50IKi2hVp0a0aBqCItweon51Bf0k+AznHAm+W k/20xGectbB/VS9h0vVDd9NVP9CGAm+Omr5o/nYZrQqrGsEtqgqIYawFPilMBMBctzY4 k82PNX2ZhPVdKYfJVmy2QQIqkNuK+vQwxHarshM7ILdd9CxixFcdBN4mVs4QGqDubXsO /FD5mpodOGUy9dMeuCHDNXd0QM/I6T+X2d1zz8aiv+VMjxFcXyMy6F5t0kdGQ8JacwMX q17iQFSOf7Ca8ShIQR6+aXcz+YEq+k5aw9aZsRm7VX02ijMQaTME1ptUHFUSCLsrI9rt PQDw== X-Forwarded-Encrypted: i=1; AJvYcCWejd5SivzzkduAkGXoL4m8Ut7J0MZ7fdEYMrIbXkEkRqjnB9QyqDXtA/sBvj2hcDqWqfj/ErWNiFrTbYz+B+c=@vger.kernel.org X-Gm-Message-State: AOJu0YwIXatG3CxT4auIr353XTaz1WIgSeu0ZBVKpmXZbfeSGXkADPek JAEO467oN5KMZlsUBAgyuNzhFl33DJkCul8tY4GBJoTXrt4qk93YiGIcTSSaYykM7BznnA/ZowX oyb88n11Bsw== X-Google-Smtp-Source: AGHT+IH+KLE/mGGXMe/zfdTQKXLEZHWmPPgC5UEZjWlu/O3oSpFLRBAABCT5sd3ZpT/1V6DbDeIu2Hq5R+wT6w== X-Received: from pfblc21.prod.google.com ([2002:a05:6a00:4f55:b0:730:9378:98c1]) (user=davidgow job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6a00:2d9f:b0:730:a40f:e6dc with SMTP id d2e1a72fcca58-7323c1f6797mr9559670b3a.23.1739518868934; Thu, 13 Feb 2025 23:41:08 -0800 (PST) Date: Fri, 14 Feb 2025 15:40:46 +0800 In-Reply-To: <20250214074051.1619256-1-davidgow@google.com> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250214074051.1619256-1-davidgow@google.com> X-Mailer: git-send-email 2.48.1.601.g30ceb7b040-goog Message-ID: <20250214074051.1619256-2-davidgow@google.com> Subject: [PATCH v6 1/3] rust: kunit: add KUnit case and suite macros From: David Gow To: Miguel Ojeda , " =?utf-8?b?Sm9zw6kgRXhww7NzaXRv?= " , Rae Moar , Boqun Feng , Alex Gaynor , Gary Guo , Benno Lossin , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Alice Ryhl , Matt Gilbride , Brendan Higgins Cc: kunit-dev@googlegroups.com, linux-kselftest@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, David Gow From: José Expósito Add a couple of Rust const functions and macros to allow to develop KUnit tests without relying on generated C code: - The `kunit_unsafe_test_suite!` Rust macro is similar to the `kunit_test_suite` C macro. It requires a NULL-terminated array of test cases (see below). - The `kunit_case` Rust function is similar to the `KUNIT_CASE` C macro. It generates as case from the name and function. - The `kunit_case_null` Rust function generates a NULL test case, which is to be used as delimiter in `kunit_test_suite!`. While these functions and macros can be used on their own, a future patch will introduce another macro to create KUnit tests using a user-space like syntax. Signed-off-by: José Expósito Co-developed-by: Matt Gilbride Signed-off-by: Matt Gilbride Co-developed-by: Miguel Ojeda Signed-off-by: Miguel Ojeda Co-developed-by: David Gow Signed-off-by: David Gow --- Changes since v5: https://lore.kernel.org/all/20241213081035.2069066-2-davidgow@google.com/ - Rebased against 6.14-rc1 - Several documentation touch-ups, including noting that the example test function need not be unsafe. (Thanks, Miguel) - Remove the need for static_mut_refs, by using core::addr_of_mut!() combined with a cast. (Thanks, Miguel) - While this should also avoid the need for const_mut_refs, it seems to have been enabled for other users anyway. - Use ::kernel::ffi::c_char for C strings, rather than i8 directly. (Thanks, Miguel) Changes since v4: https://lore.kernel.org/linux-kselftest/20241101064505.3820737-2-davidgow@google.com/ - Rebased against 6.13-rc1 - Allowed an unused_unsafe warning after the behaviour of addr_of_mut!() changed in Rust 1.82. (Thanks Boqun, Miguel) - Fix a couple of minor rustfmt issues which were triggering checkpatch warnings. Changes since v3: https://lore.kernel.org/linux-kselftest/20241030045719.3085147-4-davidgow@google.com/ - The kunit_unsafe_test_suite!() macro now panic!s if the suite name is too long, triggering a compile error. (Thanks, Alice!) Changes since v2: https://lore.kernel.org/linux-kselftest/20241029092422.2884505-2-davidgow@google.com/ - The kunit_unsafe_test_suite!() macro will truncate the name of the suite if it is too long. (Thanks Alice!) - We no longer needlessly use UnsafeCell<> in kunit_unsafe_test_suite!(). (Thanks Alice!) Changes since v1: https://lore.kernel.org/lkml/20230720-rustbind-v1-1-c80db349e3b5@google.com/ - Rebase on top of rust-next - As a result, KUnit attributes are new set. These are hardcoded to the defaults of "normal" speed and no module name. - Split the kunit_case!() macro into two const functions, kunit_case() and kunit_case_null() (for the NULL terminator). --- rust/kernel/kunit.rs | 121 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 824da0e9738a..d34a92075174 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -161,3 +161,124 @@ macro_rules! kunit_assert_eq { $crate::kunit_assert!($name, $file, $diff, $left == $right); }}; } + +/// Represents an individual test case. +/// +/// The `kunit_unsafe_test_suite!` macro expects a NULL-terminated list of valid test cases. +/// Use `kunit_case_null` to generate such a delimiter. +#[doc(hidden)] +pub const fn kunit_case( + name: &'static kernel::str::CStr, + run_case: unsafe extern "C" fn(*mut kernel::bindings::kunit), +) -> kernel::bindings::kunit_case { + kernel::bindings::kunit_case { + run_case: Some(run_case), + name: name.as_char_ptr(), + attr: kernel::bindings::kunit_attributes { + speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, + }, + generate_params: None, + status: kernel::bindings::kunit_status_KUNIT_SUCCESS, + module_name: core::ptr::null_mut(), + log: core::ptr::null_mut(), + } +} + +/// Represents the NULL test case delimiter. +/// +/// The `kunit_unsafe_test_suite!` macro expects a NULL-terminated list of test cases. This +/// function returns such a delimiter. +#[doc(hidden)] +pub const fn kunit_case_null() -> kernel::bindings::kunit_case { + kernel::bindings::kunit_case { + run_case: None, + name: core::ptr::null_mut(), + generate_params: None, + attr: kernel::bindings::kunit_attributes { + speed: kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, + }, + status: kernel::bindings::kunit_status_KUNIT_SUCCESS, + module_name: core::ptr::null_mut(), + log: core::ptr::null_mut(), + } +} + +/// Registers a KUnit test suite. +/// +/// # Safety +/// +/// `test_cases` must be a NULL terminated array of valid test cases. +/// +/// # Examples +/// +/// ```ignore +/// extern "C" fn test_fn(_test: *mut kernel::bindings::kunit) { +/// let actual = 1 + 1; +/// let expected = 2; +/// assert_eq!(actual, expected); +/// } +/// +/// static mut KUNIT_TEST_CASES: [kernel::bindings::kunit_case; 2] = [ +/// kernel::kunit::kunit_case(kernel::c_str!("name"), test_fn), +/// kernel::kunit::kunit_case_null(), +/// ]; +/// kernel::kunit_unsafe_test_suite!(suite_name, KUNIT_TEST_CASES); +/// ``` +#[doc(hidden)] +#[macro_export] +macro_rules! kunit_unsafe_test_suite { + ($name:ident, $test_cases:ident) => { + const _: () = { + const KUNIT_TEST_SUITE_NAME: [::kernel::ffi::c_char; 256] = { + let name_u8 = ::core::stringify!($name).as_bytes(); + let mut ret = [0; 256]; + + if name_u8.len() > 255 { + panic!(concat!( + "The test suite name `", + ::core::stringify!($name), + "` exceeds the maximum length of 255 bytes." + )); + } + + let mut i = 0; + while i < name_u8.len() { + ret[i] = name_u8[i] as ::kernel::ffi::c_char; + i += 1; + } + + ret + }; + + #[allow(unused_unsafe)] + static mut KUNIT_TEST_SUITE: ::kernel::bindings::kunit_suite = + ::kernel::bindings::kunit_suite { + name: KUNIT_TEST_SUITE_NAME, + // SAFETY: User is expected to pass a correct `test_cases`, given the safety + // precondition; hence this macro named `unsafe`. + test_cases: unsafe { + ::core::ptr::addr_of_mut!($test_cases) + .cast::<::kernel::bindings::kunit_case>() + }, + suite_init: None, + suite_exit: None, + init: None, + exit: None, + attr: ::kernel::bindings::kunit_attributes { + speed: ::kernel::bindings::kunit_speed_KUNIT_SPEED_NORMAL, + }, + status_comment: [0; 256usize], + debugfs: ::core::ptr::null_mut(), + log: ::core::ptr::null_mut(), + suite_init_err: 0, + is_init: false, + }; + + #[used] + #[link_section = ".kunit_test_suites"] + static mut KUNIT_TEST_SUITE_ENTRY: *const ::kernel::bindings::kunit_suite = + // SAFETY: `KUNIT_TEST_SUITE` is static. + unsafe { ::core::ptr::addr_of_mut!(KUNIT_TEST_SUITE) }; + }; + }; +} From patchwork Fri Feb 14 07:40:48 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: David Gow X-Patchwork-Id: 865219 Received: from mail-pj1-f74.google.com (mail-pj1-f74.google.com [209.85.216.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 604F42163B9 for ; Fri, 14 Feb 2025 07:41:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739518881; cv=none; b=RGusANHIlRjESoGG8vWUoc1wQ/8U+1bXK9TjIQKskcUtjbzoS50N9+fiVVoCZUQuJOIKFC4c7Pz989UE1xj1SSBsNnrZx5gacjR/Ft33jdloqaMR/LucWOvsVqNrJkT0DCE/fRPjVES75fB4hfICB8dDvFliPh7FC96WkH3Fi2c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739518881; c=relaxed/simple; bh=wu1wYChkKBa84U+/lJlhYvBmiPd0MNbKVAR64OfX5YY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=RBfuCQj/NfBoo/M8nwZo4gv7rp0AuXQ/6G1NQ/KJoc5cY4XMcDapJKp1QwSvJUqB2EWIXbIa2KO0s55a2WvYfzD8QZRznHCQoA48kl3ovO4zjwUXYwmNYPsDn231NuxLO3qbYx86dxaOCEtL6EwfVPk3vBM5lIqpHB2txn84QsQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--davidgow.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=DNipiRVN; arc=none smtp.client-ip=209.85.216.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--davidgow.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="DNipiRVN" Received: by mail-pj1-f74.google.com with SMTP id 98e67ed59e1d1-2f9da17946fso6172300a91.3 for ; Thu, 13 Feb 2025 23:41:19 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739518878; x=1740123678; darn=vger.kernel.org; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:from:to:cc:subject:date:message-id :reply-to; bh=Qphj6TWjxMj/gif/4tS2O4Kyyc5IbUJk5s6oYOqOgqw=; b=DNipiRVNYB5pwNKT4xxWREnjPu8+cRIck/NsOReDCVUB/dd9nFsF7CYobqTL09s/ox ufdCPZ7f7liktb9ILmFVKMAYFHKBUYZi6RB8lJmLMfmRjMmYZ8Z6aVOhdjtMiNSX9hQ+ 3+cTsv8kfkRXnskVEaflpOVHC7cKfhTMmFNZrBrult+S5ZMJ670L1wG0BjBEcGfie2O4 Rz2vnD6a9KQKKRyxQ+RdlGqQSRWjxyI5NPvzQorv8d8Z877Ga8WqxJN5PMaDJwrfhyMr 6rbRXVInHHZi7HmXO2qed4dx93bNvBcI0S+0LEmcoBa+Tm6PVc2ijJ2ww/zrImMjkabj 8A8A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739518878; x=1740123678; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:x-gm-message-state:from:to:cc:subject :date:message-id:reply-to; bh=Qphj6TWjxMj/gif/4tS2O4Kyyc5IbUJk5s6oYOqOgqw=; b=cTuzb534HNPM+3yqUf00Qtwrj4xWaxkBDz7FaDn4YlGYVD4a5C+EmL183L3WDoKXzn cpb4OyQ7B406J+u73rtip6l1/nhaj8erydam9yL8/sRgQYwgmZlgIrTDdKducR5kJCtr qp0mhVB5Z76BhZKFeUyvrlztPThGb5UEraIYergsdZaTEVQN2IwOvpjFmmalEHfpKfwQ xahZIBL/VY7fc7dsNsaWRPDKl1RoDMbAXdlhwfDzMKCxYB4cNTaY0KVmYKStaVa+7TXW GUVjqhocen11nh6qwsgoD41EZRTy/U3hBy6DVGe3RyZgy3DVxhDyRrCKtWOgQCjvlSKo QTuw== X-Forwarded-Encrypted: i=1; AJvYcCXm9Ha6fsnpweVmjCsfUIlXYt2HkeTs7IsYGNx1FCkrJQf7hQAY7i9o9dx6sIcgT5i5gAHTT13yGQtJQkDrRr8=@vger.kernel.org X-Gm-Message-State: AOJu0YzZlu/UHnk3pEzJ4HEwEaG5FnOA511k7/YH12GCqmUGZ8PzdLkq j17g0PYTLsZkS1qHxvmXkg3RcB/8NW96YuoxTXwiOSYLWZZfSfXICkVeCztX4nV45YHe7rlYMkN e+9lJ9WpVwA== X-Google-Smtp-Source: AGHT+IFgeVopjebWDLNzibTUdu5X7StXLo69muuWXN8z+HL8PoMGaE8j2OZtBwMk7ckUhoqyVUCJrBYQdPwGMw== X-Received: from pfne24.prod.google.com ([2002:aa7:8258:0:b0:730:8518:b97]) (user=davidgow job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6a00:98b:b0:732:1bad:e245 with SMTP id d2e1a72fcca58-7322c37ea39mr14491448b3a.7.1739518878328; Thu, 13 Feb 2025 23:41:18 -0800 (PST) Date: Fri, 14 Feb 2025 15:40:48 +0800 In-Reply-To: <20250214074051.1619256-1-davidgow@google.com> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250214074051.1619256-1-davidgow@google.com> X-Mailer: git-send-email 2.48.1.601.g30ceb7b040-goog Message-ID: <20250214074051.1619256-4-davidgow@google.com> Subject: [PATCH v6 3/3] rust: kunit: allow to know if we are in a test From: David Gow To: Miguel Ojeda , " =?utf-8?b?Sm9zw6kgRXhww7NzaXRv?= " , Rae Moar , Boqun Feng , Alex Gaynor , Gary Guo , Benno Lossin , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Alice Ryhl , Matt Gilbride , Brendan Higgins Cc: kunit-dev@googlegroups.com, linux-kselftest@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, David Gow From: José Expósito In some cases, we need to call test-only code from outside the test case, for example, to mock a function or a module. In order to check whether we are in a test or not, we need to test if `CONFIG_KUNIT` is set. Unfortunately, we cannot rely only on this condition because: - a test could be running in another thread, - some distros compile KUnit in production kernels, so checking at runtime that `current->kunit_test != NULL` is required. Forturately, KUnit provides an optimised check in `kunit_get_current_test()`, which checks CONFIG_KUNIT, a global static key, and then the current thread's running KUnit test. Add a safe wrapper function around this to know whether or not we are in a KUnit test and examples showing how to mock a function and a module. Signed-off-by: José Expósito Co-developed-by: David Gow Signed-off-by: David Gow Co-developed-by: Miguel Ojeda Signed-off-by: Miguel Ojeda --- Changes since v5: https://lore.kernel.org/all/20241213081035.2069066-4-davidgow@google.com/ - Greatly improved documentation, which is both clearer and better matches the rustdoc norm. (Thanks, Miguel) - The examples and safety comments are also both more idiomatic an cleaner. (Thanks, Miguel) - More things sit appropriately behind CONFIG_KUNIT (Thanks, Miguel) Changes since v4: https://lore.kernel.org/linux-kselftest/20241101064505.3820737-4-davidgow@google.com/ - Rebased against 6.13-rc1 - Fix some missing safety comments, and remove some unneeded 'unsafe' blocks. (Thanks Boqun) Changes since v3: https://lore.kernel.org/linux-kselftest/20241030045719.3085147-8-davidgow@google.com/ - The example test has been updated to no longer use assert_eq!() with a constant bool argument (fixes a clippy warning). No changes since v2: https://lore.kernel.org/linux-kselftest/20241029092422.2884505-4-davidgow@google.com/ Changes since v1: https://lore.kernel.org/lkml/20230720-rustbind-v1-3-c80db349e3b5@google.com/ - Rebased on top of rust-next. - Use the `kunit_get_current_test()` C function, which wasn't previously available, instead of rolling our own. - (Thanks also to Boqun for suggesting a nicer way of implementing this, which I tried, but the `kunit_get_current_test()` version obsoleted.) --- rust/kernel/kunit.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 9e27b74a605b..3aad7a281b6d 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -286,11 +286,77 @@ macro_rules! kunit_unsafe_test_suite { }; } +/// Returns whether we are currently running a KUnit test. +/// +/// In some cases, you need to call test-only code from outside the test case, for example, to +/// create a function mock. This function allows to change behavior depending on whether we are +/// currently running a KUnit test or not. +/// +/// # Examples +/// +/// This example shows how a function can be mocked to return a well-known value while testing: +/// +/// ``` +/// # use kernel::kunit::in_kunit_test; +/// fn fn_mock_example(n: i32) -> i32 { +/// if in_kunit_test() { +/// return 100; +/// } +/// +/// n + 1 +/// } +/// +/// let mock_res = fn_mock_example(5); +/// assert_eq!(mock_res, 100); +/// ``` +/// +/// Sometimes, you don't control the code that needs to be mocked. This example shows how the +/// `bindings` module can be mocked: +/// +/// ``` +/// // Import our mock naming it as the real module. +/// #[cfg(CONFIG_KUNIT)] +/// use bindings_mock_example as bindings; +/// #[cfg(not(CONFIG_KUNIT))] +/// use kernel::bindings; +/// +/// // This module mocks `bindings`. +/// #[cfg(CONFIG_KUNIT)] +/// mod bindings_mock_example { +/// /// Mock `ktime_get_boot_fast_ns` to return a well-known value when running a KUnit test. +/// pub(crate) fn ktime_get_boot_fast_ns() -> u64 { +/// 1234 +/// } +/// } +/// +/// // This is the function we want to test. Since `bindings` has been mocked, we can use its +/// // functions seamlessly. +/// fn get_boot_ns() -> u64 { +/// // SAFETY: `ktime_get_boot_fast_ns()` is always safe to call. +/// unsafe { bindings::ktime_get_boot_fast_ns() } +/// } +/// +/// let time = get_boot_ns(); +/// assert_eq!(time, 1234); +/// ``` +pub fn in_kunit_test() -> bool { + // SAFETY: `kunit_get_current_test()` is always safe to call (it has fallbacks for + // when KUnit is not enabled). + unsafe { !bindings::kunit_get_current_test().is_null() } +} + #[kunit_tests(rust_kernel_kunit)] mod tests { + use super::*; + #[test] fn rust_test_kunit_example_test() { #![expect(clippy::eq_op)] assert_eq!(1 + 1, 2); } + + #[test] + fn rust_test_kunit_in_kunit_test() { + assert!(in_kunit_test()); + } }