← Documents Documentation/rust/testing.rst GitHub 원문 ↗

Linux 6.18.37 · Rust

커널 Rust 코드 시험

Rust doctest와 #[test]를 KUnit으로 실행하고 rusttest 및 Kselftest로 확장하는 방법을 설명합니다.

Source pathDocumentation/rust/testing.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

testing.rst:1-236

Rust doctest와 #[test]를 KUnit으로 실행하고 rusttest 및 Kselftest로 확장하는 방법을 설명합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 Testing
4 =======
5
6 This document contains useful information how to test the Rust code in the
7 kernel.
8
9 There are three sorts of tests:
10
11 - The KUnit tests.
12 - The ``#[test]`` tests.
13 - The Kselftests.
14
15 The KUnit tests
16 ---------------
17
18 These are the tests that come from the examples in the Rust documentation. They
19 get transformed into KUnit tests.
20
21 Usage
22 *****
23
24 These tests can be run via KUnit. For example via ``kunit_tool`` (``kunit.py``)
25 on the command line::
26
27 ./tools/testing/kunit/kunit.py run --make_options LLVM=1 --arch x86_64 --kconfig_add CONFIG_RUST=y
28
29 Alternatively, KUnit can run them as kernel built-in at boot. Refer to
30 Documentation/dev-tools/kunit/index.rst for the general KUnit documentation
31 and Documentation/dev-tools/kunit/architecture.rst for the details of kernel
32 built-in vs. command line testing.
33
34 To use these KUnit doctests, the following must be enabled::
35
36 CONFIG_KUNIT
37 Kernel hacking -> Kernel Testing and Coverage -> KUnit - Enable support for unit tests
38 CONFIG_RUST_KERNEL_DOCTESTS
39 Kernel hacking -> Rust hacking -> Doctests for the `kernel` crate
40
41 in the kernel config system.
42
43 KUnit tests are documentation tests
44 ***********************************
45
46 These documentation tests are typically examples of usage of any item (e.g.
47 function, struct, module...).
48
49 They are very convenient because they are just written alongside the
50 documentation. For instance:
51
52 .. code-block:: rust
53
54 /// Sums two numbers.
55 ///
56 /// ```
57 /// assert_eq!(mymod::f(10, 20), 30);
58 /// ```
59 pub fn f(a: i32, b: i32) -> i32 {
60 a + b
61 }
62
63 In userspace, the tests are collected and run via ``rustdoc``. Using the tool
64 as-is would be useful already, since it allows verifying that examples compile
65 (thus enforcing they are kept in sync with the code they document) and as well
66 as running those that do not depend on in-kernel APIs.
67
68 For the kernel, however, these tests get transformed into KUnit test suites.
69 This means that doctests get compiled as Rust kernel objects, allowing them to
70 run against a built kernel.
71
72 A benefit of this KUnit integration is that Rust doctests get to reuse existing
73 testing facilities. For instance, the kernel log would look like::
74
75 KTAP version 1
76 1..1
77 KTAP version 1
78 # Subtest: rust_doctests_kernel
79 1..59
80 # rust_doctest_kernel_build_assert_rs_0.location: rust/kernel/build_assert.rs:13
81 ok 1 rust_doctest_kernel_build_assert_rs_0
82 # rust_doctest_kernel_build_assert_rs_1.location: rust/kernel/build_assert.rs:56
83 ok 2 rust_doctest_kernel_build_assert_rs_1
84 # rust_doctest_kernel_init_rs_0.location: rust/kernel/init.rs:122
85 ok 3 rust_doctest_kernel_init_rs_0
86 ...
87 # rust_doctest_kernel_types_rs_2.location: rust/kernel/types.rs:150
88 ok 59 rust_doctest_kernel_types_rs_2
89 # rust_doctests_kernel: pass:59 fail:0 skip:0 total:59
90 # Totals: pass:59 fail:0 skip:0 total:59
91 ok 1 rust_doctests_kernel
92
93 Tests using the `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_
94 operator are also supported as usual, e.g.:
95
96 .. code-block:: rust
97
98 /// ```
99 /// # use kernel::{spawn_work_item, workqueue};
100 /// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?;
101 /// # Ok::<(), Error>(())
102 /// ```
103
104 The tests are also compiled with Clippy under ``CLIPPY=1``, just like normal
105 code, thus also benefitting from extra linting.
106
107 In order for developers to easily see which line of doctest code caused a
108 failure, a KTAP diagnostic line is printed to the log. This contains the
109 location (file and line) of the original test (i.e. instead of the location in
110 the generated Rust file)::
111
112 # rust_doctest_kernel_types_rs_2.location: rust/kernel/types.rs:150
113
114 Rust tests appear to assert using the usual ``assert!`` and ``assert_eq!``
115 macros from the Rust standard library (``core``). We provide a custom version
116 that forwards the call to KUnit instead. Importantly, these macros do not
117 require passing context, unlike those for KUnit testing (i.e.
118 ``struct kunit *``). This makes them easier to use, and readers of the
119 documentation do not need to care about which testing framework is used. In
120 addition, it may allow us to test third-party code more easily in the future.
121
122 A current limitation is that KUnit does not support assertions in other tasks.
123 Thus, we presently simply print an error to the kernel log if an assertion
124 actually failed. Additionally, doctests are not run for nonpublic functions.
125
126 Since these tests are examples, i.e. they are part of the documentation, they
127 should generally be written like "real code". Thus, for example, instead of
128 using ``unwrap()`` or ``expect()``, use the ``?`` operator. For more background,
129 please see:
130
131 https://rust.docs.kernel.org/kernel/error/type.Result.html#error-codes-in-c-and-rust
132
133 The ``#[test]`` tests
134 ---------------------
135
136 Additionally, there are the ``#[test]`` tests. Like for documentation tests,
137 these are also fairly similar to what you would expect from userspace, and they
138 are also mapped to KUnit.
139
140 These tests are introduced by the ``kunit_tests`` procedural macro, which takes
141 the name of the test suite as an argument.
142
143 For instance, assume we want to test the function ``f`` from the documentation
144 tests section. We could write, in the same file where we have our function:
145
146 .. code-block:: rust
147
148 #[kunit_tests(rust_kernel_mymod)]
149 mod tests {
150 use super::*;
151
152 #[test]
153 fn test_f() {
154 assert_eq!(f(10, 20), 30);
155 }
156 }
157
158 And if we run it, the kernel log would look like::
159
160 KTAP version 1
161 # Subtest: rust_kernel_mymod
162 # speed: normal
163 1..1
164 # test_f.speed: normal
165 ok 1 test_f
166 ok 1 rust_kernel_mymod
167
168 Like documentation tests, the ``assert!`` and ``assert_eq!`` macros are mapped
169 back to KUnit and do not panic. Similarly, the
170 `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_
171 operator is supported, i.e. the test functions may return either nothing (i.e.
172 the unit type ``()``) or ``Result`` (i.e. any ``Result<T, E>``). For instance:
173
174 .. code-block:: rust
175
176 #[kunit_tests(rust_kernel_mymod)]
177 mod tests {
178 use super::*;
179
180 #[test]
181 fn test_g() -> Result {
182 let x = g()?;
183 assert_eq!(x, 30);
184 Ok(())
185 }
186 }
187
188 If we run the test and the call to ``g`` fails, then the kernel log would show::
189
190 KTAP version 1
191 # Subtest: rust_kernel_mymod
192 # speed: normal
193 1..1
194 # test_g: ASSERTION FAILED at rust/kernel/lib.rs:335
195 Expected is_test_result_ok(test_g()) to be true, but is false
196 # test_g.speed: normal
197 not ok 1 test_g
198 not ok 1 rust_kernel_mymod
199
200 If a ``#[test]`` test could be useful as an example for the user, then please
201 use a documentation test instead. Even edge cases of an API, e.g. error or
202 boundary cases, can be interesting to show in examples.
203
204 The ``rusttest`` host tests
205 ---------------------------
206
207 These are userspace tests that can be built and run in the host (i.e. the one
208 that performs the kernel build) using the ``rusttest`` Make target::
209
210 make LLVM=1 rusttest
211
212 This requires the kernel ``.config``.
213
214 Currently, they are mostly used for testing the ``macros`` crate's examples.
215
216 The Kselftests
217 --------------
218
219 Kselftests are also available in the ``tools/testing/selftests/rust`` folder.
220
221 The kernel config options required for the tests are listed in the
222 ``tools/testing/selftests/rust/config`` file and can be included with the aid
223 of the ``merge_config.sh`` script::
224
225 ./scripts/kconfig/merge_config.sh .config tools/testing/selftests/rust/config
226
227 The kselftests are built within the kernel source tree and are intended to
228 be executed on a system that is running the same kernel.
229
230 Once a kernel matching the source tree has been installed and booted, the
231 tests can be compiled and executed using the following command::
232
233 make TARGETS="rust" kselftest
234
235 Refer to Documentation/dev-tools/kselftest.rst for the general Kselftest
236 documentation.
237

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Rust doctest를 KUnit으로 실행

1-132

커널 Rust 코드에는 KUnit test, `#[test]` test, Kselftest가 있다. 이 절의 KUnit test는 Rust 문서에 적은 예제를 변환해 만든 documentation test다.

명령행에서는 `./tools/testing/kunit/kunit.py run --make_options LLVM=1 --arch x86_64 --kconfig_add CONFIG_RUST=y`처럼 실행한다. 또는 kernel built-in으로 boot 때 실행할 수 있다. 일반 구조와 두 실행 방식은 KUnit index와 architecture 문서를 참고한다.

Rust doctest에는 `CONFIG_KUNIT`과 `CONFIG_RUST_KERNEL_DOCTESTS`가 필요하다. 문서 옆의 예제는 userspace에서는 `rustdoc`이 수집해 compile과 실행을 확인하지만, 커널에서는 Rust kernel object와 KUnit suite로 변환되어 실제 build kernel API를 상대로 실행된다.

KUnit 통합 덕분에 결과는 KTAP 형식으로 kernel log에 나오며 suite별 pass, fail, skip과 총계를 제공한다. 실패를 생성 Rust 파일이 아니라 원래 doctest의 파일과 줄에서 찾을 수 있도록 `.location` diagnostic도 출력한다.

`?` operator를 쓰는 예제도 평소처럼 지원되고, `CLIPPY=1`이면 일반 코드와 함께 Clippy로 컴파일된다. 표준 `core`의 `assert!`, `assert_eq!`처럼 보이는 macro는 KUnit으로 전달되는 custom version이며 `struct kunit *` context를 직접 넘길 필요가 없다.

현재 KUnit은 다른 task에서 assertion을 지원하지 않아 그런 실패는 kernel log에 error로 출력한다. 비공개 함수의 doctest도 실행하지 않는다. 이 test들은 문서의 실제 예제이므로 real code처럼 작성하고 `unwrap()`이나 `expect()` 대신 `?`로 실패를 전파한다.

Rust doctest 변환
rustdoc 예제 작성doctest 수집Rust kernel object로 compileKUnit suite 생성커널에서 실행KTAP와 원본 file:line 출력

문서 예제를 커널에서 실행되는 KUnit suite로 바꿉니다.

KUnit doctest 특성
기능동작
assert!/assert_eq!KUnit assertion으로 mapping
? operatorResult 실패 전파 지원
CLIPPY=1doctest에도 추가 lint
location diagnostic원본 Rust 파일과 줄 표시
다른 task assertion현재 log error로 제한
비공개 함수doctest 미실행

문서 품질과 커널 실행 시험을 같은 예제로 검증합니다.

.. SPDX-License-Identifier: GPL-2.0

Testing
=======

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

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. They
get transformed into KUnit tests.

Usage
*****

These tests can be run via KUnit. For example via ``kunit_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 to
Documentation/dev-tools/kunit/index.rst for the general KUnit documentation
and Documentation/dev-tools/kunit/architecture.rst for the details of kernel
built-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 tests
        CONFIG_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 the
documentation. For instance:

.. code-block:: rust

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

In userspace, the tests are collected and run via ``rustdoc``. Using the tool
as-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 well
as 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 to
run against a built kernel.

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

        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_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:59
        ok 1 rust_doctests_kernel

Tests using the `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_
operator are also supported as usual, e.g.:

.. code-block:: rust

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

The tests are also compiled with Clippy under ``CLIPPY=1``, just like normal
code, thus also benefitting from extra linting.

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

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

Rust tests appear to assert using the usual ``assert!`` and ``assert_eq!``
macros from the Rust standard library (``core``). We provide a custom version
that forwards the call to KUnit instead. Importantly, these macros do not
require passing context, unlike those for KUnit testing (i.e.
``struct kunit *``). This makes them easier to use, and readers of the
documentation do not need to care about which testing framework is used. In
addition, 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 assertion
actually failed. Additionally, doctests are not run for nonpublic functions.

Since these tests are examples, i.e. they are part of the documentation, they
should generally be written like "real code". Thus, for example, instead of
using ``unwrap()`` or ``expect()``, use the ``?`` operator. For more background,
please see:

        https://rust.docs.kernel.org/kernel/error/type.Result.html#error-codes-in-c-and-rust

#[test]와 kunit_tests macro

133-203

`#[test]` test도 userspace Rust와 비슷하게 작성하지만 KUnit으로 mapping된다. `kunit_tests` procedural macro에 test suite 이름을 넘기고, 같은 파일의 `mod tests` 안에 개별 `#[test]` 함수를 둔다.

실행 결과는 suite와 test 이름을 가진 KTAP로 기록된다. Documentation test와 마찬가지로 `assert!`, `assert_eq!`은 panic하지 않고 KUnit assertion으로 돌아간다.

Test 함수는 unit type `()`을 반환해도 되고 임의의 `Result<T, E>`를 반환해 `?` operator를 사용할 수도 있다. 호출한 `g()`가 실패하면 wrapper assertion이 실패한 위치와 기대 조건을 kernel log에 표시하고 test와 suite를 `not ok`로 끝낸다.

사용자에게 도움이 될 만한 test라면 `#[test]` 대신 documentation test로 작성한다. 오류나 경계 조건 같은 API edge case도 사용 예제로서 가치가 있을 수 있다.

#[test] KUnit 실행
#[kunit_tests(suite_name)]mod tests각 #[test] 함수 수집assert 또는 Result 실행KTAP test 결과suite 결과 집계

Procedural macro가 일반적인 Rust test 모듈을 KUnit suite에 연결합니다.

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

These tests are introduced by the ``kunit_tests`` procedural macro, which takes
the name of the test suite as an argument.

For instance, assume we want to test the function ``f`` from the documentation
tests section. We could write, in the same file where we have our function:

.. code-block:: rust

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

            #[test]
            fn test_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_f
        ok 1 rust_kernel_mymod

Like documentation tests, the ``assert!`` and ``assert_eq!`` macros are mapped
back to KUnit and do not panic. Similarly, the
`? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_
operator is supported, i.e. the test functions may return either nothing (i.e.
the unit type ``()``) or ``Result`` (i.e. any ``Result<T, E>``). For instance:

.. code-block:: rust

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

            #[test]
            fn test_g() -> Result {
                let x = g()?;
                assert_eq!(x, 30);
                Ok(())
            }
        }

If we run the test and the call to ``g`` 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_g
        not ok 1 rust_kernel_mymod

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

rusttest host 시험

204-215

`rusttest` host test는 커널을 빌드하는 host의 userspace에서 build하고 실행한다. `make LLVM=1 rusttest`를 사용하며 커널 `.config`가 필요하다. 현재는 주로 `macros` crate의 예제를 시험하는 데 쓰인다.

Host rusttest
커널 .config 준비make LLVM=1 rusttesthost userspace buildmacros crate 예제 실행결과 확인

커널 실행 없이 build host에서 macro 예제를 검증합니다.

The ``rusttest`` host tests
---------------------------

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

        make LLVM=1 rusttest

This requires the kernel ``.config``.

Currently, they are mostly used for testing the ``macros`` crate's examples.

실행 중인 커널의 Kselftest

216-236

Rust Kselftest는 `tools/testing/selftests/rust`에 있다. 필요한 kernel config option은 그 디렉터리의 `config` 파일에 있으며 `./scripts/kconfig/merge_config.sh .config tools/testing/selftests/rust/config`로 현재 설정에 합칠 수 있다.

Kselftest는 kernel source tree 안에서 빌드하고, 같은 source tree와 일치하는 kernel을 실행 중인 시스템에서 수행하도록 설계되었다. 해당 kernel을 설치하고 boot한 뒤 `make TARGETS="rust" kselftest`로 compile과 실행을 한다. 일반 사용법은 `Documentation/dev-tools/kselftest.rst`를 참고한다.

Rust Kselftest
selftests/rust/config 확인merge_config.sh로 .config 병합일치하는 kernel build와 설치그 kernel로 bootmake TARGETS=rust kselftest결과 확인

시험 설정과 실행 중인 커널의 source version을 맞춥니다.

The Kselftests
--------------

Kselftests are also available in the ``tools/testing/selftests/rust`` folder.

The kernel config options required for the tests are listed in the
``tools/testing/selftests/rust/config`` file and can be included with the aid
of the ``merge_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 to
be executed on a system that is running the same kernel.

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

        make TARGETS="rust" kselftest

Refer to Documentation/dev-tools/kselftest.rst for the general Kselftest
documentation.