kunit.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! 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>
  7. use core::{ffi::c_void, fmt};
  8. /// Prints a KUnit error-level message.
  9. ///
  10. /// Public but hidden since it should only be used from KUnit generated code.
  11. #[doc(hidden)]
  12. pub fn err(args: fmt::Arguments<'_>) {
  13. // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we
  14. // are passing.
  15. #[cfg(CONFIG_PRINTK)]
  16. unsafe {
  17. bindings::_printk(
  18. c"\x013%pA".as_ptr() as _,
  19. &args as *const _ as *const c_void,
  20. );
  21. }
  22. }
  23. /// Prints a KUnit info-level message.
  24. ///
  25. /// Public but hidden since it should only be used from KUnit generated code.
  26. #[doc(hidden)]
  27. pub fn info(args: fmt::Arguments<'_>) {
  28. // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we
  29. // are passing.
  30. #[cfg(CONFIG_PRINTK)]
  31. unsafe {
  32. bindings::_printk(
  33. c"\x016%pA".as_ptr() as _,
  34. &args as *const _ as *const c_void,
  35. );
  36. }
  37. }
  38. /// Asserts that a boolean expression is `true` at runtime.
  39. ///
  40. /// Public but hidden since it should only be used from generated tests.
  41. ///
  42. /// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit
  43. /// facilities. See [`assert!`] for more details.
  44. #[doc(hidden)]
  45. #[macro_export]
  46. macro_rules! kunit_assert {
  47. ($name:literal, $file:literal, $diff:expr, $condition:expr $(,)?) => {
  48. 'out: {
  49. // Do nothing if the condition is `true`.
  50. if $condition {
  51. break 'out;
  52. }
  53. static FILE: &'static $crate::str::CStr = $crate::c_str!($file);
  54. static LINE: i32 = core::line!() as i32 - $diff;
  55. static CONDITION: &'static $crate::str::CStr = $crate::c_str!(stringify!($condition));
  56. // SAFETY: FFI call without safety requirements.
  57. let kunit_test = unsafe { $crate::bindings::kunit_get_current_test() };
  58. if kunit_test.is_null() {
  59. // The assertion failed but this task is not running a KUnit test, so we cannot call
  60. // KUnit, but at least print an error to the kernel log. This may happen if this
  61. // macro is called from an spawned thread in a test (see
  62. // `scripts/rustdoc_test_gen.rs`) or if some non-test code calls this macro by
  63. // mistake (it is hidden to prevent that).
  64. //
  65. // This mimics KUnit's failed assertion format.
  66. $crate::kunit::err(format_args!(
  67. " # {}: ASSERTION FAILED at {FILE}:{LINE}\n",
  68. $name
  69. ));
  70. $crate::kunit::err(format_args!(
  71. " Expected {CONDITION} to be true, but is false\n"
  72. ));
  73. $crate::kunit::err(format_args!(
  74. " Failure not reported to KUnit since this is a non-KUnit task\n"
  75. ));
  76. break 'out;
  77. }
  78. #[repr(transparent)]
  79. struct Location($crate::bindings::kunit_loc);
  80. #[repr(transparent)]
  81. struct UnaryAssert($crate::bindings::kunit_unary_assert);
  82. // SAFETY: There is only a static instance and in that one the pointer field points to
  83. // an immutable C string.
  84. unsafe impl Sync for Location {}
  85. // SAFETY: There is only a static instance and in that one the pointer field points to
  86. // an immutable C string.
  87. unsafe impl Sync for UnaryAssert {}
  88. static LOCATION: Location = Location($crate::bindings::kunit_loc {
  89. file: FILE.as_char_ptr(),
  90. line: LINE,
  91. });
  92. static ASSERTION: UnaryAssert = UnaryAssert($crate::bindings::kunit_unary_assert {
  93. assert: $crate::bindings::kunit_assert {},
  94. condition: CONDITION.as_char_ptr(),
  95. expected_true: true,
  96. });
  97. // SAFETY:
  98. // - FFI call.
  99. // - The `kunit_test` pointer is valid because we got it from
  100. // `kunit_get_current_test()` and it was not null. This means we are in a KUnit
  101. // test, and that the pointer can be passed to KUnit functions and assertions.
  102. // - The string pointers (`file` and `condition` above) point to null-terminated
  103. // strings since they are `CStr`s.
  104. // - The function pointer (`format`) points to the proper function.
  105. // - The pointers passed will remain valid since they point to `static`s.
  106. // - The format string is allowed to be null.
  107. // - There are, however, problems with this: first of all, this will end up stopping
  108. // the thread, without running destructors. While that is problematic in itself,
  109. // it is considered UB to have what is effectively a forced foreign unwind
  110. // with `extern "C"` ABI. One could observe the stack that is now gone from
  111. // another thread. We should avoid pinning stack variables to prevent library UB,
  112. // too. For the moment, given that test failures are reported immediately before the
  113. // next test runs, that test failures should be fixed and that KUnit is explicitly
  114. // documented as not suitable for production environments, we feel it is reasonable.
  115. unsafe {
  116. $crate::bindings::__kunit_do_failed_assertion(
  117. kunit_test,
  118. core::ptr::addr_of!(LOCATION.0),
  119. $crate::bindings::kunit_assert_type_KUNIT_ASSERTION,
  120. core::ptr::addr_of!(ASSERTION.0.assert),
  121. Some($crate::bindings::kunit_unary_assert_format),
  122. core::ptr::null(),
  123. );
  124. }
  125. // SAFETY: FFI call; the `test` pointer is valid because this hidden macro should only
  126. // be called by the generated documentation tests which forward the test pointer given
  127. // by KUnit.
  128. unsafe {
  129. $crate::bindings::__kunit_abort(kunit_test);
  130. }
  131. }
  132. };
  133. }
  134. /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
  135. ///
  136. /// Public but hidden since it should only be used from generated tests.
  137. ///
  138. /// Unlike the one in `core`, this one does not panic; instead, it is mapped to the KUnit
  139. /// facilities. See [`assert!`] for more details.
  140. #[doc(hidden)]
  141. #[macro_export]
  142. macro_rules! kunit_assert_eq {
  143. ($name:literal, $file:literal, $diff:expr, $left:expr, $right:expr $(,)?) => {{
  144. // For the moment, we just forward to the expression assert because, for binary asserts,
  145. // KUnit supports only a few types (e.g. integers).
  146. $crate::kunit_assert!($name, $file, $diff, $left == $right);
  147. }};
  148. }