Testing

This document contains useful information how to test the Rust code in thekernel.

There are three sorts of tests:

  • The KUnit tests.

  • The#[test] tests.

  • The Kselftests.

The KUnit tests

These are the tests that come from the examples in the Rust documentation. Theyget transformed into KUnit tests.

Usage

These tests can be run via KUnit. For example viakunit_tool (kunit.py)on the command line:

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

Alternatively, KUnit can run them as kernel built-in at boot. Refer toKUnit - Linux Kernel Unit Testing for the general KUnit documentationandKUnit Architecture for the details of kernelbuilt-in vs. command line testing.

To use these KUnit doctests, the following must be enabled:

CONFIG_KUNIT   Kernel hacking -> Kernel Testing and Coverage -> KUnit - Enable support for unit testsCONFIG_RUST_KERNEL_DOCTESTS   Kernel hacking -> Rust hacking -> Doctests for the `kernel` crate

in the kernel config system.

KUnit tests are documentation tests

These documentation tests are typically examples of usage of any item (e.g.function, struct, module...).

They are very convenient because they are just written alongside thedocumentation. For instance:

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

In userspace, the tests are collected and run viarustdoc. Using the toolas-is would be useful already, since it allows verifying that examples compile(thus enforcing they are kept in sync with the code they document) and as wellas running those that do not depend on in-kernel APIs.

For the kernel, however, these tests get transformed into KUnit test suites.This means that doctests get compiled as Rust kernel objects, allowing them torun against a built kernel.

A benefit of this KUnit integration is that Rust doctests get to reuse existingtesting facilities. For instance, the kernel log would look like:

KTAP version 11..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_doctest_kernel_init_rs_0.location: rust/kernel/init.rs:122    ok 3 rust_doctest_kernel_init_rs_0    ...    # rust_doctest_kernel_types_rs_2.location: rust/kernel/types.rs:150    ok 59 rust_doctest_kernel_types_rs_2# rust_doctests_kernel: pass:59 fail:0 skip:0 total:59# Totals: pass:59 fail:0 skip:0 total:59ok 1 rust_doctests_kernel

Tests using the?operator are also supported as usual, e.g.:

/// ```/// # use kernel::{spawn_work_item, workqueue};/// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?;/// # Ok::<(), Error>(())/// ```

The tests are also compiled with Clippy underCLIPPY=1, just like normalcode, thus also benefitting from extra linting.

In order for developers to easily see which line of doctest code caused afailure, a KTAP diagnostic line is printed to the log. This contains thelocation (file and line) of the original test (i.e. instead of the location inthe generated Rust file):

# rust_doctest_kernel_types_rs_2.location: rust/kernel/types.rs:150

Rust tests appear to assert using the usualassert! andassert_eq!macros from the Rust standard library (core). We provide a custom versionthat forwards the call to KUnit instead. Importantly, these macros do notrequire passing context, unlike those for KUnit testing (i.e.structkunit*). This makes them easier to use, and readers of thedocumentation do not need to care about which testing framework is used. Inaddition, it may allow us to test third-party code more easily in the future.

A current limitation is that KUnit does not support assertions in other tasks.Thus, we presently simply print an error to the kernel log if an assertionactually failed. Additionally, doctests are not run for nonpublic functions.

Since these tests are examples, i.e. they are part of the documentation, theyshould generally be written like “real code”. Thus, for example, instead ofusingunwrap() orexpect(), use the? operator. For more background,please see:

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 theyare also mapped to KUnit.

These tests are introduced by thekunit_tests procedural macro, which takesthe name of the test suite as an argument.

For instance, assume we want to test the functionf from the documentationtests section. We could write, in the same file where we have our function:

#[kunit_tests(rust_kernel_mymod)]modtests{usesuper::*;#[test]fntest_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_fok 1 rust_kernel_mymod

Like documentation tests, theassert! andassert_eq! macros are mappedback 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()) orResult (i.e. anyResult<T,E>). For instance:

#[kunit_tests(rust_kernel_mymod)]modtests{usesuper::*;#[test]fntest_g()->Result{letx=g()?;assert_eq!(x,30);Ok(())}}

If we run the test and the call tog 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_gnot ok 1 rust_kernel_mymod

If a#[test] test could be useful as an example for the user, then pleaseuse a documentation test instead. Even edge cases of an API, e.g. error orboundary cases, can be interesting to show in examples.

Therusttest host tests

These are userspace tests that can be built and run in the host (i.e. the onethat performs the kernel build) using therusttest Make target:

make LLVM=1 rusttest

This requires the kernel.config.

Currently, they are mostly used for testing themacros crate’s examples.

The Kselftests

Kselftests are also available in thetools/testing/selftests/rust folder.

The kernel config options required for the tests are listed in thetools/testing/selftests/rust/config file and can be included with the aidof themerge_config.sh script:

./scripts/kconfig/merge_config.sh .config tools/testing/selftests/rust/config

The kselftests are built within the kernel source tree and are intended tobe executed on a system that is running the same kernel.

Once a kernel matching the source tree has been installed and booted, thetests can be compiled and executed using the following command:

make TARGETS="rust" kselftest

Refer toLinux Kernel Selftests for the general Kselftestdocumentation.