Skip to content
systemcoding.dev
Kernels

Test Rust Kernel Code With KUnit and Rust Doctests

Run the Rust doctests of the kernel crate and write your own kunit_tests suite on Linux 6.18, with kunit.py, KTAP output and the limits of each test kind.

7 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Rust, Linux and CMake logos.

Rust has a testing culture that user-space programmers take for granted: a #[test] function, assert_eq!, and cargo test. The kernel has no cargo and no std, but it has KUnit, and the Rust support maps the familiar test syntax onto it. This post covers the kinds of Rust tests that exist in Linux 6.18 and how to run each. It runs the doctests of the kernel crate, writes a test suite for a module with #[kunit_tests], and reads the KTAP output. For the C side of the same framework, see unit testing kernel code with KUnit.

Everything here comes from the kernel's Rust testing document, the kunit_tests macro in rust/macros/, and the KUnit documentation.

The kinds of Rust test

The testing document lists three. The KUnit tests that come from the examples in the Rust documentation, called doctests, which the build turns into KUnit test suites. The #[test] tests, introduced by the kunit_tests procedural macro, which are also mapped to KUnit. And the kselftests under tools/testing/selftests/rust, which run from user space against a booted kernel. There is a fourth, the rusttest host tests, which are user-space tests built and run on the build machine with make LLVM=1 rusttest, and the document says they are mostly used for testing the macros crate's examples.

Use doctests to document and verify how an API is used. Use #[test] functions for edge cases and error paths that would clutter documentation. Use kselftests when the test needs a user-space program. The testing document makes the same split: if a #[test] test would be useful as an example for the reader, write a doctest instead, and even edge cases of an API, such as error or boundary cases, can be interesting examples.

Turn on the framework

The tests need KUnit and, for doctests, a kernel config option from the Rust hacking menu:

Text
CONFIG_KUNIT=y
CONFIG_RUST=y
CONFIG_RUST_KERNEL_DOCTESTS=y

CONFIG_RUST_KERNEL_DOCTESTS builds the documentation tests of the kernel crate as KUnit tests, and it depends on KUNIT=y. The KUnit documentation also says that CONFIG_KUNIT should not be enabled in a production environment, because enabling it disables KASLR and tests may alter kernel state.

Run the existing doctests

The documented way is kunit.py, which builds a kernel with the tests, runs it under QEMU for a non-UML architecture, and prints the results. For Rust, pass the make options and the Kconfig it needs:

Shell
./tools/testing/kunit/kunit.py run \
	--make_options LLVM=1 \
	--arch x86_64 \
	--kconfig_add CONFIG_RUST=y

The kernel log from that run is TAP-style, with a line per doctest and a location line that points back at the original source. This is the shape the testing document shows:

Text
KTAP version 1
1..1
    KTAP version 1
    # Subtest: rust_doctests_kernel
    1..59
    # rust_doctest_kernel_build_assert_rs_0.location: rust/kernel/build_assert.rs:13
    ok 1 rust_doctest_kernel_build_assert_rs_0
    # rust_doctest_kernel_build_assert_rs_1.location: rust/kernel/build_assert.rs:56
    ok 2 rust_doctest_kernel_build_assert_rs_1
    # rust_doctests_kernel: pass:59 fail:0 skip:0 total:59
ok 1 rust_doctests_kernel

The count of doctests grows with the kernel version, so 59 is the figure from the document and yours will differ. The location line is the useful part: when a doctest fails, it names the file and line of the example in the original source, instead of a line in a generated file. The tests are also compiled with Clippy when you build with CLIPPY=1, so they get linted like the rest of the code.

Write a doctest

A doctest is an example in a documentation comment. The build extracts it, compiles it as a Rust kernel object and runs it as a KUnit case. The testing document gives this form:

rust
/// Sums two numbers.
///
/// ```
/// assert_eq!(mymod::f(10, 20), 30);
/// ```
pub fn f(a: i32, b: i32) -> i32 {
    a + b
}

The assert! and assert_eq! macros in these examples look like the standard ones but are mapped to KUnit and do not panic. A failure is recorded in the test result and the rest of the test continues. Because the examples are documentation, the document says they should be written like real code: use the ? operator instead of unwrap() or expect(), and end a doctest that uses ? with a line hidden from the rendered page:

rust
/// ```
/// # use kernel::prelude::*;
/// let mut numbers = KVec::new();
/// numbers.push(72, GFP_KERNEL)?;
/// assert_eq!(numbers.len(), 1);
/// # Ok::<(), Error>(())
/// ```

Lines starting with # are compiled but not shown in the generated HTML, which keeps imports and the closing Ok out of the reader's way. Two limits from the document apply. Doctests are only run for public functions, since nonpublic items cannot be reached from the generated test. And these doctests belong to the kernel crate, which is what CONFIG_RUST_KERNEL_DOCTESTS builds, so an example written in the doc comment of your own module is documentation only and does not run as a test. For your own code, use #[kunit_tests].

Write a #[test] suite for a module

The kunit_tests macro turns a Rust mod of #[test] functions into a KUnit suite, with the suite name as its argument. The macro's own documentation says it should be used on modules and that if CONFIG_KUNIT is n, the target module is ignored, so the tests cost nothing in a normal build. Put a function and its tests in samples/rust/rust_checked.rs:

samples/rust/rust_checked.rsrust
// SPDX-License-Identifier: GPL-2.0

//! A function with tests.

use kernel::prelude::*;

module! {
    type: Checked,
    name: "rust_checked",
    authors: ["Example Author"],
    description: "Function with KUnit tests",
    license: "GPL",
}

struct Checked;

impl kernel::Module for Checked {
    fn init(_module: &'static ThisModule) -> Result<Self> {
        pr_info!("total of 1,2,3 is {:?}\n", checked_total(&[1, 2, 3]));
        Ok(Checked)
    }
}

/// Sums the values, or returns `None` if the sum would overflow.
fn checked_total(values: &[u32]) -> Option<u32> {
    let mut total: u32 = 0;
    for v in values {
        total = total.checked_add(*v)?;
    }
    Some(total)
}

#[kunit_tests(rust_checked)]
mod tests {
    use super::*;

    #[test]
    fn sums() {
        assert_eq!(checked_total(&[1, 2, 3]), Some(6));
    }

    #[test]
    fn overflow_is_none() {
        assert_eq!(checked_total(&[u32::MAX, 1]), None);
    }

    #[test]
    fn alloc_works() -> Result {
        let mut v = KVec::new();
        v.push(7u32, GFP_KERNEL)?;
        assert_eq!(checked_total(&v), Some(7));
        Ok(())
    }
}

The function uses checked_add so the overflow case returns None instead of panicking, which the CONFIG_RUST_OVERFLOW_CHECKS default would otherwise do. The test functions may return nothing or a Result, as the document says, and the ? operator works inside them: alloc_works can fail with an allocation error and the test is then reported as failed. The assert_eq! macros map to KUnit, the same way as in doctests.

Register it as in any sample, with a Kconfig tristate entry named SAMPLE_RUST_CHECKED and the Makefile line obj-$(CONFIG_SAMPLE_RUST_CHECKED) += rust_checked.o. Then run it:

Shell
./tools/testing/kunit/kunit.py run \
	--make_options LLVM=1 \
	--arch x86_64 \
	--kconfig_add CONFIG_RUST=y \
	--kconfig_add CONFIG_SAMPLES_RUST=y \
	--kconfig_add CONFIG_SAMPLE_RUST_CHECKED=y \
	'rust_checked'

The filter argument selects the suite by name. The log has the format the testing document shows for #[test] suites:

Text
    KTAP version 1
    # Subtest: rust_checked
    # speed: normal
    1..3
    # sums.speed: normal
    ok 1 sums
    # overflow_is_none.speed: normal
    ok 2 overflow_is_none
    # alloc_works.speed: normal
    ok 3 alloc_works
ok 1 rust_checked

A failing assertion prints the file and line of the macro call. In the document's example of a test whose function returns an error, the log shows ASSERTION FAILED at rust/kernel/lib.rs:335 followed by Expected is_test_result_ok(test_g()) to be true, but is false, and the case is not ok.

Limits to know

The testing document lists one limitation directly: KUnit does not support assertions in other tasks, so a failed assertion in, for example, a spawned work item is currently only printed as an error to the kernel log rather than failing the test. Keep assertions in the test's own task. The tests also run inside the kernel, with all the usual rules: no sleeping where sleeping is not allowed, and no assumptions about hardware.

Where this does not fit

KUnit tests call Rust functions directly, so they cover pure logic and abstractions that do not need real hardware. A driver against a device needs a fake device or a test in a VM with a device model. Behavior seen through a system call belongs in a kselftest, run from tools/testing/selftests/rust with make TARGETS="rust" kselftest, which the document describes. For code that depends on timing or concurrency across CPUs, a single-threaded unit test shows only one interleaving.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.