1 // SPDX-License-Identifier: GPL-2.0
3 //! Generates KUnit tests from saved `rustdoc`-generated tests.
5 //! KUnit passes a context (`struct kunit *`) to each test, which should be forwarded to the other
6 //! KUnit functions and macros.
8 //! However, we want to keep this as an implementation detail because:
10 //! - Test code should not care about the implementation.
12 //! - Documentation looks worse if it needs to carry extra details unrelated to the piece
15 //! - Test code should be able to define functions and call them, without having to carry
18 //! - Later on, we may want to be able to test non-kernel code (e.g. `core`, `alloc` or
19 //! third-party crates) which likely use the standard library `assert*!` macros.
21 //! For this reason, instead of the passed context, `kunit_get_current_test()` is used instead
22 //! (i.e. `current->kunit_test`).
24 //! Note that this means other threads/tasks potentially spawned by a given test, if failing, will
25 //! report the failure in the kernel log but will not fail the actual test. Saving the pointer in
26 //! e.g. a `static` per test does not fully solve the issue either, because currently KUnit does
27 //! not support assertions (only expectations) from other tasks. Thus leave that feature for
28 //! the future, which simplifies the code here too. We could also simply not allow `assert`s in
29 //! other tasks, but that seems overly constraining, and we do want to support them, eventually.
34 io::{BufWriter, Read, Write},
35 path::{Path, PathBuf},
38 /// Find the real path to the original file based on the `file` portion of the test name.
40 /// `rustdoc` generated `file`s look like `sync_locked_by_rs`. Underscores (except the last one)
41 /// may represent an actual underscore in a directory/file, or a path separator. Thus the actual
42 /// file might be `sync_locked_by.rs`, `sync/locked_by.rs`, `sync_locked/by.rs` or
43 /// `sync/locked/by.rs`. This function walks the file system to determine which is the real one.
45 /// This does require that ambiguities do not exist, but that seems fair, especially since this is
46 /// all supposed to be temporary until `rustdoc` gives us proper metadata to build this. If such
47 /// ambiguities are detected, they are diagnosed and the script panics.
48 fn find_real_path<'a>(srctree: &Path, valid_paths: &'a mut Vec<PathBuf>, file: &str) -> &'a str {
51 let potential_components: Vec<&str> = file.strip_suffix("_rs").unwrap().split('_').collect();
53 find_candidates(srctree, valid_paths, Path::new(""), &potential_components);
56 valid_paths: &mut Vec<PathBuf>,
58 potential_components: &[&str],
60 // The base case: check whether all the potential components left, joined by underscores,
62 let joined_potential_components = potential_components.join("_") + ".rs";
66 .join(&joined_potential_components)
69 // Avoid `srctree` here in order to keep paths relative to it in the KTAP output.
71 Path::new("rust/kernel")
73 .join(joined_potential_components),
77 // In addition, check whether each component prefix, joined by underscores, is a directory.
78 // If not, there is no need to check for combinations with that prefix.
79 for i in 1..potential_components.len() {
80 let (components_prefix, components_rest) = potential_components.split_at(i);
81 let prefix = prefix.join(components_prefix.join("_"));
82 if srctree.join("rust/kernel").join(&prefix).is_dir() {
83 find_candidates(srctree, valid_paths, &prefix, components_rest);
89 valid_paths.len() > 0,
90 "No path candidates found. This is likely a bug in the build system, or some files went \
91 away while compiling."
94 if valid_paths.len() > 1 {
95 eprintln!("Several path candidates found:");
96 for path in valid_paths {
97 eprintln!(" {path:?}");
100 "Several path candidates found, please resolve the ambiguity by renaming a file or \
105 valid_paths[0].to_str().unwrap()
109 let srctree = std::env::var("srctree").unwrap();
110 let srctree = Path::new(&srctree);
112 let mut paths = fs::read_dir("rust/test/doctests/kernel")
114 .map(|entry| entry.unwrap().path())
115 .collect::<Vec<_>>();
120 let mut rust_tests = String::new();
121 let mut c_test_declarations = String::new();
122 let mut c_test_cases = String::new();
123 let mut body = String::new();
124 let mut last_file = String::new();
126 let mut valid_paths: Vec<PathBuf> = Vec::new();
127 let mut real_path: &str = "";
129 // The `name` follows the `{file}_{line}_{number}` pattern (see description in
130 // `scripts/rustdoc_test_builder.rs`). Discard the `number`.
131 let name = path.file_name().unwrap().to_str().unwrap().to_string();
133 // Extract the `file` and the `line`, discarding the `number`.
134 let (file, line) = name.rsplit_once('_').unwrap().0.rsplit_once('_').unwrap();
136 // Generate an ID sequence ("test number") for each one in the file.
137 if file == last_file {
141 last_file = file.to_string();
143 // Figure out the real path, only once per file.
144 real_path = find_real_path(srctree, &mut valid_paths, file);
147 // Generate a KUnit name (i.e. test name and C symbol) for this test.
149 // We avoid the line number, like `rustdoc` does, to make things slightly more stable for
150 // bisection purposes. However, to aid developers in mapping back what test failed, we will
151 // print a diagnostics line in the KTAP report.
152 let kunit_name = format!("rust_doctest_kernel_{file}_{number}");
154 // Read the test's text contents to dump it below.
156 File::open(path).unwrap().read_to_string(&mut body).unwrap();
158 // Calculate how many lines before `main` function (including the `main` function line).
159 let body_offset = body
161 .take_while(|line| !line.contains("fn main() {"))
168 r#"/// Generated `{name}` KUnit test case from a Rust documentation test.
170 pub extern "C" fn {kunit_name}(__kunit_test: *mut kernel::bindings::kunit) {{
171 /// Overrides the usual [`assert!`] macro with one that calls KUnit instead.
173 macro_rules! assert {{
174 ($cond:expr $(,)?) => {{{{
175 kernel::kunit_assert!("{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $cond);
179 /// Overrides the usual [`assert_eq!`] macro with one that calls KUnit instead.
181 macro_rules! assert_eq {{
182 ($left:expr, $right:expr $(,)?) => {{{{
183 kernel::kunit_assert_eq!("{kunit_name}", "{real_path}", __DOCTEST_ANCHOR - {line}, $left, $right);
187 // Many tests need the prelude, so provide it by default.
189 use kernel::prelude::*;
191 // Unconditionally print the location of the original doctest (i.e. rather than the location in
192 // the generated file) so that developers can easily map the test back to the source code.
194 // This information is also printed when assertions fail, but this helps in the successful cases
195 // when the user is running KUnit manually, or when passing `--raw_output` to `kunit.py`.
197 // This follows the syntax for declaring test metadata in the proposed KTAP v2 spec, which may
198 // be used for the proposed KUnit test attributes API. Thus hopefully this will make migration
200 kernel::kunit::info(format_args!(" # {kunit_name}.location: {real_path}:{line}\n"));
202 /// The anchor where the test code body starts.
204 static __DOCTEST_ANCHOR: i32 = core::line!() as i32 + {body_offset} + 1;
215 write!(c_test_declarations, "void {kunit_name}(struct kunit *);\n").unwrap();
216 write!(c_test_cases, " KUNIT_CASE({kunit_name}),\n").unwrap();
219 let rust_tests = rust_tests.trim();
220 let c_test_declarations = c_test_declarations.trim();
221 let c_test_cases = c_test_cases.trim();
224 BufWriter::new(File::create("rust/doctests_kernel_generated.rs").unwrap()),
225 r#"//! `kernel` crate documentation tests.
227 const __LOG_PREFIX: &[u8] = b"rust_doctests_kernel\0";
235 BufWriter::new(File::create("rust/doctests_kernel_generated_kunit.c").unwrap()),
237 * `kernel` crate documentation tests.
240 #include <kunit/test.h>
242 {c_test_declarations}
244 static struct kunit_case test_cases[] = {{
249 static struct kunit_suite test_suite = {{
250 .name = "rust_doctests_kernel",
251 .test_cases = test_cases,
254 kunit_test_suite(test_suite);
256 MODULE_LICENSE("GPL");