From patchwork Fri May 2 21:51:26 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 886766 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D924D2153DA; Fri, 2 May 2025 21:51:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222713; cv=none; b=osVcbt7VM1fDkm28Y5lx7YgMHUwuRFFSjK0np09KwtQoWgBBjHH9s20CR1j8dKhDaWQyZMAUDNafkZm6RdddSYxa+bPseabnTyZHe9a29S3HM8gP+X1bvZjkmRunrm0v+FHHRJT+0TuPRg54V5Rj3yzDgGjG8vNNVNmpAr62g6s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222713; c=relaxed/simple; bh=1ROB2ECqCRMXxG3uU2grTJzFUCgEFG5F5Pl5x/9OCXQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=XNHjudJkNTi0nn6oA5cf3hn6HLyJ+xNO6mRdabEXSXnJ18kzFMjMvktcQUu3c7LgGsYG4tlrEnh7PzWCYoy9VhVfQbZ343By85PevNAgsF3WS2peWN7VA3VCTXnpvaU8X0ObRo5LTsqYouC6S4b9harrMZluCkgg/b1ZrnUvB9c= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=GzkTLYHI; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="GzkTLYHI" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 98B17C4CEED; Fri, 2 May 2025 21:51:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222712; bh=1ROB2ECqCRMXxG3uU2grTJzFUCgEFG5F5Pl5x/9OCXQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GzkTLYHIlDTRDuzSCnMkf9TZ4FjHbGasKauKRDGMDCDs8lidZ4exNJnYZCZKocCBT WrP/TRRpCHeB4WY1roIYZw4/LrDM3k9iW8qn65hNKq2Ui7hTk1sRsRQaLnCchUo3KD EYLWJRzJEbc6Gu38ELyMiZzBVsHJEUBe5GDaFVWJZVsGJEWX4+f9EhNDNhMNwzgSVS JZAHeRHipJXZ+iol9DUO+6Q3tNTvWTP2LbuwyOPtvJyIuHcP6bxG/FCLWZ0++hbc2S M/sXaadcXQL8RBUMKne/agJVYy9EzyrxjvB4ThFGAmRAikScgGbReTvcP7IUtNPFkG U8lcAPsIjcv3A== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 1/7] rust: kunit: support KUnit-mapped `assert!` macros in `#[test]`s Date: Fri, 2 May 2025 23:51:26 +0200 Message-ID: <20250502215133.1923676-2-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 The KUnit `#[test]` support that landed recently is very basic and does not map the `assert*!` macros into KUnit like the doctests do, so they panic at the moment. Thus implement the custom mapping in a similar way to doctests, reusing the infrastructure there. In Rust 1.88.0, the `file()` method in `Span` may be stable [1]. However, it was changed recently (from `SourceFile`), so we need to do something different in previous versions. Thus create a helper for it and use it to get the path. With this, a failing test suite like: #[kunit_tests(my_test_suite)] mod tests { use super::*; #[test] fn my_first_test() { assert_eq!(42, 43); } #[test] fn my_second_test() { assert!(42 >= 43); } } will properly map back to KUnit, printing something like: [ 1.924325] KTAP version 1 [ 1.924421] # Subtest: my_test_suite [ 1.924506] # speed: normal [ 1.924525] 1..2 [ 1.926385] # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251 [ 1.926385] Expected 42 == 43 to be true, but is false [ 1.928026] # my_first_test.speed: normal [ 1.928075] not ok 1 my_first_test [ 1.928723] # my_second_test: ASSERTION FAILED at rust/kernel/lib.rs:256 [ 1.928723] Expected 42 >= 43 to be true, but is false [ 1.929834] # my_second_test.speed: normal [ 1.929868] not ok 2 my_second_test [ 1.930032] # my_test_suite: pass:0 fail:2 skip:0 total:2 [ 1.930153] # Totals: pass:0 fail:2 skip:0 total Link: https://github.com/rust-lang/rust/pull/140514 [1] Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- init/Kconfig | 3 +++ rust/Makefile | 3 ++- rust/kernel/kunit.rs | 1 - rust/macros/helpers.rs | 16 ++++++++++++++++ rust/macros/kunit.rs | 28 +++++++++++++++++++++++++++- rust/macros/lib.rs | 4 ++++ 6 files changed, 52 insertions(+), 3 deletions(-) diff --git a/init/Kconfig b/init/Kconfig index 63f5974b9fa6..5f442c64c47b 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -140,6 +140,9 @@ config LD_CAN_USE_KEEP_IN_OVERLAY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >= 108400 +config RUSTC_HAS_SPAN_FILE + def_bool RUSTC_VERSION >= 108800 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE)) diff --git a/rust/Makefile b/rust/Makefile index 3aca903a7d08..075b38a24997 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -402,7 +402,8 @@ quiet_cmd_rustc_procmacro = $(RUSTC_OR_CLIPPY_QUIET) P $@ -Clink-args='$(call escsq,$(KBUILD_PROCMACROLDFLAGS))' \ --emit=dep-info=$(depfile) --emit=link=$@ --extern proc_macro \ --crate-type proc-macro \ - --crate-name $(patsubst lib%.$(libmacros_extension),%,$(notdir $@)) $< + --crate-name $(patsubst lib%.$(libmacros_extension),%,$(notdir $@)) \ + @$(objtree)/include/generated/rustc_cfg $< # Procedural macros can only be used with the `rustc` that compiled it. $(obj)/$(libmacros_name): $(src)/macros/lib.rs FORCE diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 1604fb6a5b1b..2659895d4c5d 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -323,7 +323,6 @@ mod tests { #[test] fn rust_test_kunit_example_test() { - #![expect(clippy::eq_op)] assert_eq!(1 + 1, 2); } diff --git a/rust/macros/helpers.rs b/rust/macros/helpers.rs index a3ee27e29a6f..57c3b0f0c194 100644 --- a/rust/macros/helpers.rs +++ b/rust/macros/helpers.rs @@ -86,3 +86,19 @@ pub(crate) fn function_name(input: TokenStream) -> Option { } None } + +pub(crate) fn file() -> String { + #[cfg(not(CONFIG_RUSTC_HAS_SPAN_FILE))] + { + proc_macro::Span::call_site() + .source_file() + .path() + .to_string_lossy() + .into_owned() + } + + #[cfg(CONFIG_RUSTC_HAS_SPAN_FILE)] + { + proc_macro::Span::call_site().file() + } +} diff --git a/rust/macros/kunit.rs b/rust/macros/kunit.rs index 4f553ecf40c0..eb4f2afdbe43 100644 --- a/rust/macros/kunit.rs +++ b/rust/macros/kunit.rs @@ -101,6 +101,8 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream { // ``` let mut kunit_macros = "".to_owned(); let mut test_cases = "".to_owned(); + let mut assert_macros = "".to_owned(); + let path = crate::helpers::file(); for test in &tests { let kunit_wrapper_fn_name = format!("kunit_rust_wrapper_{}", test); let kunit_wrapper = format!( @@ -114,6 +116,27 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream { test, kunit_wrapper_fn_name ) .unwrap(); + writeln!( + assert_macros, + r#" +/// Overrides the usual [`assert!`] macro with one that calls KUnit instead. +#[allow(unused)] +macro_rules! assert {{ + ($cond:expr $(,)?) => {{{{ + kernel::kunit_assert!("{test}", "{path}", 0, $cond); + }}}} +}} + +/// Overrides the usual [`assert_eq!`] macro with one that calls KUnit instead. +#[allow(unused)] +macro_rules! assert_eq {{ + ($left:expr, $right:expr $(,)?) => {{{{ + kernel::kunit_assert_eq!("{test}", "{path}", 0, $left, $right); + }}}} +}} + "# + ) + .unwrap(); } writeln!(kunit_macros).unwrap(); @@ -152,7 +175,10 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream { } } - let mut new_body = TokenStream::from_iter(new_body); + let body = new_body; + let mut new_body = TokenStream::new(); + new_body.extend::(assert_macros.parse().unwrap()); + new_body.extend(body); new_body.extend::(kunit_macros.parse().unwrap()); tokens.push(TokenTree::Group(Group::new(Delimiter::Brace, new_body))); diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 9acaa68c974e..8bd7906276be 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -6,6 +6,10 @@ // and thus add a dependency on `include/config/RUSTC_VERSION_TEXT`, which is // touched by Kconfig when the version string from the compiler changes. +// TODO: check that when Rust 1.88.0 is released, this would be enough: +// #![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))] +#![feature(proc_macro_span)] + #[macro_use] mod quote; mod concat_idents; From patchwork Fri May 2 21:51:27 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 887316 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D4C15210198; Fri, 2 May 2025 21:51:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222718; cv=none; b=Mj0fv7Ql6PlVOXnOvvHcbad2TsAZ2dAjMr+XFdzUZk23esTBkuMUIi+5o/hT3Wl16RShkYEbgiUrrhiRGJdH8XHCdc/cMkg7Yk/hkdobzMOIQf4vABIO44WQYo1nn7k03O2oyJYvK6COKuVL6iS53KjeB+GBDIVwez9vP4caGxU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222718; c=relaxed/simple; bh=vvQNN9akNzYWDVQbfCy9pnQxfwa6gSBIzDY7UkgvpC8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=EuZoKAEaAgDxEk00M+sZODwMj/Hvaj2GEfiDE4dAkXzO/ShWfGBT/vUpF9fJATv454iOPZeknxv2c6nU/+h+7UIEKJDwTvK0FVsq16Y2rdFOMR9D1U6DDzLP+XIIKym1Mzy8LvZ/IME/dYclKocp1A13aNzoTO17oHpk3C9xgb8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=c1GsZP1X; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="c1GsZP1X" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3B504C4CEE4; Fri, 2 May 2025 21:51:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222717; bh=vvQNN9akNzYWDVQbfCy9pnQxfwa6gSBIzDY7UkgvpC8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=c1GsZP1XDahePAMHJmlzCYgiV/CEt9OkY7hQCb51O3Cktn0WXN4oYqAzYERFILW1/ Z5bQjtiwRxEAIhg/KsLtbMK2E3fmtDsrOrQW6bNARl7ouksHPUklV+qBx0wv+SOJYI uDq4pMTICw5bfGkWYs8UfYQo6m8DUSnVqfUyNNwuAtDQ7YhKK8fhPrYGkMEhM2NL47 SIgZEMrkM9VjGbocsgrO06C72vJEWbsFUZHvOPBUYNjJ9Kg9fv7yU7pYtrs7nr22qN LzNRDiANge7gegfSuhGHhxZeX5Qau2+sce1rXrnyY1NSq5vx+ywkQ25HRqCmtWB2FJ zR0OQRn0yRIpQ== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 2/7] rust: kunit: support checked `-> Result`s in KUnit `#[test]`s Date: Fri, 2 May 2025 23:51:27 +0200 Message-ID: <20250502215133.1923676-3-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 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`, 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 Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- rust/kernel/kunit.rs | 25 +++++++++++++++++++++++++ rust/macros/kunit.rs | 3 ++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 2659895d4c5d..f43e3ed460c2 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -164,6 +164,31 @@ macro_rules! kunit_assert_eq { }}; } +trait TestResult { + fn is_test_result_ok(&self) -> bool; +} + +impl TestResult for () { + fn is_test_result_ok(&self) -> bool { + true + } +} + +impl TestResult for Result { + fn is_test_result_ok(&self) -> bool { + self.is_ok() + } +} + +/// Returns whether a test result is to be considered OK. +/// +/// This will be `assert!`ed from the generated tests. +#[doc(hidden)] +#[expect(private_bounds)] +pub fn is_test_result_ok(t: impl TestResult) -> bool { + t.is_test_result_ok() +} + /// Represents an individual test case. /// /// The [`kunit_unsafe_test_suite!`] macro expects a NULL-terminated list of valid test cases. diff --git a/rust/macros/kunit.rs b/rust/macros/kunit.rs index eb4f2afdbe43..9681775d160a 100644 --- a/rust/macros/kunit.rs +++ b/rust/macros/kunit.rs @@ -105,8 +105,9 @@ pub(crate) fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream { let path = crate::helpers::file(); for test in &tests { let kunit_wrapper_fn_name = format!("kunit_rust_wrapper_{}", test); + // An extra `use` is used here to reduce the length of the message. let kunit_wrapper = format!( - "unsafe extern \"C\" fn {}(_test: *mut kernel::bindings::kunit) {{ {}(); }}", + "unsafe extern \"C\" fn {}(_test: *mut kernel::bindings::kunit) {{ use kernel::kunit::is_test_result_ok; assert!(is_test_result_ok({}())); }}", kunit_wrapper_fn_name, test ); writeln!(kunit_macros, "{kunit_wrapper}").unwrap(); From patchwork Fri May 2 21:51:28 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 886765 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8C7A8221F21; Fri, 2 May 2025 21:52:02 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222722; cv=none; b=ZurvBqxx+aBVP6qVKS9Xfe4d8zRz2o1jGqWavULApm32g9CmhlIlXn0+FKu9As5RZ8swTnW7dk9YcSBl85DnCtx9/ZeC4MPrCoiP8DNXXQVhXbDjaKAgzQhzid9P0Gv0fhjTmLSrzjSt/woIo5nlalYS359GoraDogYncvQA508= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222722; c=relaxed/simple; bh=Ywzns9kdzvgchDQq8gUskAhoVH1XxfCbNL7gC5kzNDM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=T4g6JTjkca8dcivixdrb6yJzPfUGRSfTV7Eebvjn7ocvBKOuxo4hvQzFcQt5F12QA5eFIlZNuUYjLL87115tcrcdAManoe3hbcHGJJ/Q/tBc2ewvzua7LOy/grWX1UP6F1EDESskVUCsi8SymungQhAQTvWVSAusXPjdRPk6J38= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=cYJxa0fO; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="cYJxa0fO" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D19A2C4CEEB; Fri, 2 May 2025 21:51:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222722; bh=Ywzns9kdzvgchDQq8gUskAhoVH1XxfCbNL7gC5kzNDM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cYJxa0fOKQNQqSN0tZ1fD5HfOhHC4111Fosluxj856LqCVvm1i0bw/BiMz2LGr1Cq dtCFMp+b+4N272rKP6CvTAWLgArXYlUCpxw74GwvqQMyAvh2ofbie1Dn2Bp1Zdd28c Lqzt0u3WyEPFJmv3Wig1dGARB0gwhirUFUimzNMcx3P9ugogPciIevNdC4WYrfA9fc EaVwygKjs3rpK1s4gvezw8Z9qic4K307JQTj2C2V2EBgGYx0odRCeFvOcWklajdt61 OUQfDlAj2OIjTrqRCHYKb/NJOOvtYc+DTFZA3LTDWdnOymVpcpZi9B+0/NJL6ME++R WnFvWCd66PhXA== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 3/7] rust: add `kunit_tests` to the prelude Date: Fri, 2 May 2025 23:51:28 +0200 Message-ID: <20250502215133.1923676-4-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 It is convenient to have certain things in the `kernel` prelude, and means kernel developers will find it even easier to start writing tests. And, anyway, nobody should need to use this identifier for anything else. Thus add it to the prelude. Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- rust/kernel/kunit.rs | 3 +-- rust/kernel/prelude.rs | 2 +- rust/macros/lib.rs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index f43e3ed460c2..053a7da147d5 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -6,6 +6,7 @@ //! //! Reference: +use crate::prelude::*; use core::{ffi::c_void, fmt}; /// Prints a KUnit error-level message. @@ -40,8 +41,6 @@ pub fn info(args: fmt::Arguments<'_>) { } } -use macros::kunit_tests; - /// Asserts that a boolean expression is `true` at runtime. /// /// Public but hidden since it should only be used from generated tests. diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index baa774a351ce..e5d61a83952f 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -17,7 +17,7 @@ pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec}; #[doc(no_inline)] -pub use macros::{export, module, vtable}; +pub use macros::{export, kunit_tests, module, vtable}; pub use pin_init::{init, pin_data, pin_init, pinned_drop, InPlaceWrite, Init, PinInit, Zeroable}; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 8bd7906276be..8b8d46e759d4 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -406,7 +406,7 @@ pub fn paste(input: TokenStream) -> TokenStream { /// # Examples /// /// ```ignore -/// # use macros::kunit_tests; +/// # use kernel::prelude::*; /// #[kunit_tests(kunit_test_suit_name)] /// mod tests { /// #[test] From patchwork Fri May 2 21:51:29 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 887315 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 21B70219E93; Fri, 2 May 2025 21:52:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222727; cv=none; b=HYHiD2ETPiTQTmPreIf2HyhmPWya/h213/8L7HXHbYRpQNfOyI44E6mt05/HRT++gv/dzJS3oF5lPLsdNSkTwsGJ6crr98kGcKQPXdDBxO2VHwe0JV4pjxOy3ZxOHu9h2BwZtJTxGThlNp2CTt78+VEHS4FjAvmiAkIyWuYiT9E= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222727; c=relaxed/simple; bh=YG1y6vcd/mwrVWGLSsGMxcKcSqp12PyuG/HK1WrSQL4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=BiuN2Gi53y1DW/LlMScHGUfs8QWzK1uHTdF6jj7A/mzknji8Ioau8sT6LThSOkCiNLiaStwYONCMFL5uU9v2YAP0142YAjGGDbP5/nc99UC3ugDKbi0h22TY3A1k5wYxbM/2/Gqf6z5b8f/wwk3Q8CEoSCseuoYAQySfXTVaUc4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=cSw+oRn5; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="cSw+oRn5" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 798E6C4CEE4; Fri, 2 May 2025 21:52:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222726; bh=YG1y6vcd/mwrVWGLSsGMxcKcSqp12PyuG/HK1WrSQL4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cSw+oRn5Ywhz2iT8S9ASiK4VzgoAVpw+bnbGyLDaR7N2jRdI8iuMxfaQqOx3P1zj+ YCEiRO5LUv90Ccd4VyPknQEW8YC897iSA35Amv0Xgv2bqDzKx7rjg5u1GuBPXo2tW8 7GXRpncRHRme7HGbSGhw8aMQMwAn6j35FBqSuXdLLNo2xhrPdkr/Uv0SKHjNCeleU/ nN98wg6/+3PZuZ0UBAeBZfAhhzWurcfiGH24kuDMXFwjac2cBssVa+V+cthr4UHWeG 3fpxKm+RuQkhG4KbH8za53psCxPgK73vHqyxS3Urx6Uj8JNkvKMg5Is+iDB8pbwNeH M5HeJXaHgPNTQ== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 4/7] rust: str: convert `rusttest` tests into KUnit Date: Fri, 2 May 2025 23:51:29 +0200 Message-ID: <20250502215133.1923676-5-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 In general, we should aim to test as much as possible within the actual kernel, and not in the build host. Thus convert these `rusttest` tests into KUnit tests. Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- rust/kernel/str.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 878111cb77bc..cf2caa2db168 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -6,7 +6,7 @@ use core::fmt::{self, Write}; use core::ops::{self, Deref, DerefMut, Index}; -use crate::error::{code::*, Error}; +use crate::prelude::*; /// Byte string without UTF-8 validity guarantee. #[repr(transparent)] @@ -572,8 +572,7 @@ macro_rules! c_str { }}; } -#[cfg(test)] -#[expect(clippy::items_after_test_module)] +#[kunit_tests(rust_kernel_str)] mod tests { use super::*; @@ -622,11 +621,10 @@ fn test_cstr_to_str() { } #[test] - #[should_panic] - fn test_cstr_to_str_panic() { + fn test_cstr_to_str_invalid_utf8() { let bad_bytes = b"\xc3\x28\0"; let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap(); - checked_cstr.to_str().unwrap(); + assert!(checked_cstr.to_str().is_err()); } #[test] From patchwork Fri May 2 21:51:30 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 886764 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B52AC20E33F; Fri, 2 May 2025 21:52:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222731; cv=none; b=OxvXhVeF3H7XFmg3kjoNzxl8t+vsazNbsUq6HipsD8Vzig5klgyDyjz9BN2LILiGjv1UU8kc6SiYdLPopXx3/2aDsy3RRYs7OQAb6isAjDCg6Lqb9VPNrRI+ZksuJJbagHUszKUze2bMjK0liyYhrJ3vmWJwEahfKgU/7KClxf8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222731; c=relaxed/simple; bh=b2XaTBmaYpfpczAKBytuofI8i3ymM1pZ7PB4JPzi6y8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=BgvhHIqMQLYG0sYdB2YLfY5tMFoTQ+Adch4n9O5F9ufq2MSUqlxJqnf5IH/umSzKed7eZHJhpnoPwIJDLR8Mv9mds9zPW3MQhv7AWDXW6+E3sQ9YKpb5swhNORdxoC0IRGanarpb+ApplQrR3vFy3NK29kakCxb5PoG2kGLLx7E= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=a3H9e7yl; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="a3H9e7yl" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1FA26C4CEEB; Fri, 2 May 2025 21:52:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222731; bh=b2XaTBmaYpfpczAKBytuofI8i3ymM1pZ7PB4JPzi6y8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=a3H9e7yljJdkJlrpu610A2i0b6Cmo6kr5pX+4jo7PMHvK55VgTWMqOKZZ8zPF8ndN HcTWv+sffu3Nj2wUllw0aXWkzElys/btzNQvIvHKEx0wp2bxbEsIKzN5s3IgogqMLc CvQ2oGFYVx+fLRAlxD8PM4FpAoM5DxcZaUkl44IsAZr8pD3nhA8o3BhBEmifcJ3Dqp YqY/PvCCGrC32Wd09ItABmAaCvkp7gZDmS97b4eHUHGDsg5xxEfWKg0K7HDcSJMQqt eRZE4eWn83XQj/0MB38svPKr5XzvB2bhi8hztRbECO/EqJk/0yQ6rSZaVeYwCtpsO6 wNQEKBOLYQN/g== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 5/7] rust: str: take advantage of the `-> Result` support in KUnit `#[test]`'s Date: Fri, 2 May 2025 23:51:30 +0200 Message-ID: <20250502215133.1923676-6-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Since now we have support for returning `-> Result`s, we can convert some of these tests to use the feature, and serve as a first user for it too. Thus convert them. This, in turn, simplifies them a fair bit. We keep the actual assertions we want to make as explicit ones with `assert*!`s. Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- rust/kernel/str.rs | 68 ++++++++++++++++++++-------------------------- 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index cf2caa2db168..8dcfb11013f2 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -576,25 +576,9 @@ macro_rules! c_str { mod tests { use super::*; - struct String(CString); - - impl String { - fn from_fmt(args: fmt::Arguments<'_>) -> Self { - String(CString::try_from_fmt(args).unwrap()) - } - } - - impl Deref for String { - type Target = str; - - fn deref(&self) -> &str { - self.0.to_str().unwrap() - } - } - macro_rules! format { ($($f:tt)*) => ({ - &*String::from_fmt(kernel::fmt!($($f)*)) + CString::try_from_fmt(kernel::fmt!($($f)*))?.to_str()? }) } @@ -613,66 +597,72 @@ macro_rules! format { \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"; #[test] - fn test_cstr_to_str() { + fn test_cstr_to_str() -> Result { let good_bytes = b"\xf0\x9f\xa6\x80\0"; - let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); - let checked_str = checked_cstr.to_str().unwrap(); + let checked_cstr = CStr::from_bytes_with_nul(good_bytes)?; + let checked_str = checked_cstr.to_str()?; assert_eq!(checked_str, "🦀"); + Ok(()) } #[test] - fn test_cstr_to_str_invalid_utf8() { + fn test_cstr_to_str_invalid_utf8() -> Result { let bad_bytes = b"\xc3\x28\0"; - let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap(); + let checked_cstr = CStr::from_bytes_with_nul(bad_bytes)?; assert!(checked_cstr.to_str().is_err()); + Ok(()) } #[test] - fn test_cstr_as_str_unchecked() { + fn test_cstr_as_str_unchecked() -> Result { let good_bytes = b"\xf0\x9f\x90\xA7\0"; - let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); + let checked_cstr = CStr::from_bytes_with_nul(good_bytes)?; // SAFETY: The contents come from a string literal which contains valid UTF-8. let unchecked_str = unsafe { checked_cstr.as_str_unchecked() }; assert_eq!(unchecked_str, "🐧"); + Ok(()) } #[test] - fn test_cstr_display() { - let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); + fn test_cstr_display() -> Result { + let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0")?; assert_eq!(format!("{}", hello_world), "hello, world!"); - let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); + let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0")?; assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a"); - let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); + let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0")?; assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); - let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); + let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0")?; assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + Ok(()) } #[test] - fn test_cstr_display_all_bytes() { + fn test_cstr_display_all_bytes() -> Result { let mut bytes: [u8; 256] = [0; 256]; // fill `bytes` with [1..=255] + [0] for i in u8::MIN..=u8::MAX { bytes[i as usize] = i.wrapping_add(1); } - let cstr = CStr::from_bytes_with_nul(&bytes).unwrap(); + let cstr = CStr::from_bytes_with_nul(&bytes)?; assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS); + Ok(()) } #[test] - fn test_cstr_debug() { - let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); + fn test_cstr_debug() -> Result { + let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0")?; assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); - let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); + let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0")?; assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\""); - let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); + let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0")?; assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); - let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); + let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0")?; assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + Ok(()) } #[test] - fn test_bstr_display() { + fn test_bstr_display() -> Result { let hello_world = BStr::from_bytes(b"hello, world!"); assert_eq!(format!("{}", hello_world), "hello, world!"); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); @@ -683,10 +673,11 @@ fn test_bstr_display() { assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + Ok(()) } #[test] - fn test_bstr_debug() { + fn test_bstr_debug() -> Result { let hello_world = BStr::from_bytes(b"hello, world!"); assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); @@ -697,6 +688,7 @@ fn test_bstr_debug() { assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + Ok(()) } } From patchwork Fri May 2 21:51:31 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 887314 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 58AC7215783; Fri, 2 May 2025 21:52:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222736; cv=none; b=mx6m+aLsimO8iYiufoddLBT8jAwYIPdQOoe+llNOOtmbDdKGUd+s3ON+9yHIK5H+x1K1ejQWAcSTA5u6ZQcoLGxIKxbwIc3XZ87uIv5GqAOiF/Wyot8Nq0KnfH4wWUkNCPkRa4eXVgp4JlJ70Q9SEJTBOXiFiXgEvPVP06baFcA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222736; c=relaxed/simple; bh=6u8yOrDSOAkZwu2NCJXzUPUic0tTjwsBIeXknGukVb4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=a7XD3US8KSFmIUKoXD4+iGxi/mStduAJbLSIuBZd57k6KHxgtLoxdhzOJqcVAmXOMfGD4M9J0oLw3fFDsDAqtlvLjEIHoX7gG6WtV6Gz8uGCd0rehVWQFaUWRwe1MyXUcYZps1QrDyh8C1+hmFkVoKrOFjGsd9T4lWYrLMnVkmo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=TynLFFOm; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="TynLFFOm" Received: by smtp.kernel.org (Postfix) with ESMTPSA id B6C04C4CEE4; Fri, 2 May 2025 21:52:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222735; bh=6u8yOrDSOAkZwu2NCJXzUPUic0tTjwsBIeXknGukVb4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=TynLFFOmnbtENdtWpGLKw/ZQ2MA6OBNVW2iK6YzY0r7ao2Fnmg5cOzNeci0Frxk7t LGJ01IrhEfDz4hXfkIMqSnSME1ATsAHkpq3I2rpWdeWdO4Y9Zbf8JZZR49rrrLCs14 2aoBZNp/ibRmME2zCWzWurMy2ch11bXFgjdm0Pd3pUXMGwUS/EOEEgKijVDh4qUNQm VjQAfkV5KUJzr+ht/OtPReSAP5Py+o6GQWjHLvBKbAIHif6BmBV4Pg/i2AYS8TZq+A I5oScAOscmi63kOLDDRDhR5CgjBiXWB1jz+Qp17ohZvV/PufKf+DZDD/BZ7xc+8+AD WcgpvN2DXDUPg== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 6/7] Documentation: rust: rename `#[test]`s to "`rusttest` host tests" Date: Fri, 2 May 2025 23:51:31 +0200 Message-ID: <20250502215133.1923676-7-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Now that `rusttest`s are not really used much, clarify the section of the documentation that describes them. In addition, free the section name for the KUnit-based `#[test]`s that will be added afterwards. To do so, rename the section into `rusttest` host tests. Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- Documentation/rust/testing.rst | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Documentation/rust/testing.rst b/Documentation/rust/testing.rst index f692494f7b74..6337b83815ab 100644 --- a/Documentation/rust/testing.rst +++ b/Documentation/rust/testing.rst @@ -130,16 +130,17 @@ please see: https://rust.docs.kernel.org/kernel/error/type.Result.html#error-codes-in-c-and-rust -The ``#[test]`` tests ---------------------- +The ``rusttest`` host tests +--------------------------- -Additionally, there are the ``#[test]`` tests. These can be run using the -``rusttest`` Make target:: +These are userspace tests that can be built and run in the host (i.e. the one +that performs the kernel build) using the ``rusttest`` Make target:: make LLVM=1 rusttest -This requires the kernel ``.config``. It runs the ``#[test]`` tests on the host -(currently) and thus is fairly limited in what these tests can test. +This requires the kernel ``.config``. + +Currently, they are mostly used for testing the ``macros`` crate's examples. The Kselftests -------------- From patchwork Fri May 2 21:51:32 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 886763 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EAE51212FBF; Fri, 2 May 2025 21:52:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222742; cv=none; b=nJrlyMx9N8q5CGpM2aGl7hlX6tQSW87R394OW4l/Hyo44YNQwBuPSdqM/g0H/NjgNfVaqsM/2X4zXNSRQzXVHmj6Tw094lFC2f9Wx/z38Pa9a9kSKEIgGVMy9bqWxSUmPrJobKY8sVm8d/NXMDIDuew79pGS5K67qhS/luMYezc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746222742; c=relaxed/simple; bh=0d+B6C4f5BhKibcwQvvX7AE1XP/6ykd4eiWYjI558WQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aq4q+dDij1x1ilL8qVPpGxwPLLfQu3WXMaUuY4RDM2iK1ZR+arNWlGbCXYMZgjxUnm86eBYn0WuVrJHJ68wGgSQq0N57ZpN0JakKha0BqE7QvWL1kKlZ6wwxss1mAaQxxrEdEMFrB7SxM3xJSmt2CJJGNDj1Yj9z8JxNTht1lnA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Ueoh3jGQ; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Ueoh3jGQ" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4DCFEC4CEEB; Fri, 2 May 2025 21:52:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746222740; bh=0d+B6C4f5BhKibcwQvvX7AE1XP/6ykd4eiWYjI558WQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Ueoh3jGQfdluiir5m9D+KAT0kCQ1LZDyRlD89g7UZTWIvS6/pC7RbnsMNMEqu/S1R +I5+SO2EsYPlgBsnUKBSoPQHaCyFX0hBRFOGnQkRShOv/7jss6xnMjtpk5qUCzLO4m 0oia8FpH9TBUl9PPc8u1dVTSbDp8gAzZqZzwSayWu+h0S5o9jBcdhsSnWW8XYk5cG6 uDqytDKWPFiOcfEmxfM+ulVSx7L8za/KI2yH/+Dry7JvxSO/E8HoYNWfbfb4jVn1o5 HRUdWQo0Ad9kmCYPAG6g5zsC+1U4PTvwJ2it9VGdmdQnm5unWY9p8n+3HRLrfQOCC9 a72/tkdwZc84Q== From: Miguel Ojeda To: Brendan Higgins , David Gow , Miguel Ojeda , Alex Gaynor Cc: Rae Moar , linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH 7/7] Documentation: rust: testing: add docs on the new KUnit `#[test]` tests Date: Fri, 2 May 2025 23:51:32 +0200 Message-ID: <20250502215133.1923676-8-ojeda@kernel.org> In-Reply-To: <20250502215133.1923676-1-ojeda@kernel.org> References: <20250502215133.1923676-1-ojeda@kernel.org> Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 There was no documentation yet on the KUnit-based `#[test]`s. Thus add it now. It includes an explanation about the `assert*!` macros being mapped to KUnit and the support for `-> Result` introduced in these series. Signed-off-by: Miguel Ojeda Reviewed-by: David Gow --- Documentation/rust/testing.rst | 71 ++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/Documentation/rust/testing.rst b/Documentation/rust/testing.rst index 6337b83815ab..f43cb77bcc69 100644 --- a/Documentation/rust/testing.rst +++ b/Documentation/rust/testing.rst @@ -130,6 +130,77 @@ please see: https://rust.docs.kernel.org/kernel/error/type.Result.html#error-codes-in-c-and-rust +The ``#[test]`` tests +--------------------- + +Additionally, there are the ``#[test]`` tests. Like for documentation tests, +these are also fairly similar to what you would expect from userspace, and they +are also mapped to KUnit. + +These tests are introduced by the ``kunit_tests`` procedural macro, which takes +the name of the test suite as an argument. + +For instance, assume we want to test the function ``f`` from the documentation +tests section. We could write, in the same file where we have our function: + +.. code-block:: rust + + #[kunit_tests(rust_kernel_mymod)] + mod tests { + use super::*; + + #[test] + fn test_f() { + assert_eq!(f(10, 20), 30); + } + } + +And if we run it, the kernel log would look like:: + + KTAP version 1 + # Subtest: rust_kernel_mymod + # speed: normal + 1..1 + # test_f.speed: normal + ok 1 test_f + ok 1 rust_kernel_mymod + +Like documentation tests, the ``assert!`` and ``assert_eq!`` macros are mapped +back to KUnit and do not panic. Similarly, the +`? `_ +operator is supported, i.e. the test functions may return either nothing (i.e. +the unit type ``()``) or ``Result`` (i.e. any ``Result``). For instance: + +.. code-block:: rust + + #[kunit_tests(rust_kernel_mymod)] + mod tests { + use super::*; + + #[test] + fn test_g() -> Result { + let x = g()?; + assert_eq!(x, 30); + Ok(()) + } + } + +If we run the test and the call to ``g`` fails, then the kernel log would show:: + + KTAP version 1 + # Subtest: rust_kernel_mymod + # speed: normal + 1..1 + # test_g: ASSERTION FAILED at rust/kernel/lib.rs:335 + Expected is_test_result_ok(test_g()) to be true, but is false + # test_g.speed: normal + not ok 1 test_g + not ok 1 rust_kernel_mymod + +If a ``#[test]`` test could be useful as an example for the user, then please +use a documentation test instead. Even edge cases of an API, e.g. error or +boundary cases, can be interesting to show in examples. + The ``rusttest`` host tests ---------------------------