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