← Documents Documentation/dev-tools/kselftest.rst GitHub 원문 ↗

Linux 6.18.37 · Dev Tools

Linux Kernel Selftests

Kselftest의 빌드·선택 실행·설치·패키징 방법과 TAP 규칙, lib.mk 변수, kernel test module 및 userspace harness 작성법을 설명합니다.

Source pathDocumentation/dev-tools/kselftest.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약과 해설

kselftest.rst:1-447

Kselftest는 부팅한 커널의 개별 코드 경로를 userspace에서 검사하는 표준 test suite입니다. Mainline 테스트를 stable kernel에도 실행할 수 있도록 호환성과 정상적인 skip 처리를 유지하며, TARGETS와 SKIP_TARGETS로 범위를 제어하고 TAP 결과를 CI에서 소비할 수 있습니다.

새 테스트는 lib.mk의 분류 변수를 사용하고 모든 architecture에서 build되어야 하며, 기능이 구성되지 않았을 때 최상위 run_tests를 실패시키지 않아야 합니다. Kernel 내부 검사가 필요하면 TAINT_TEST를 적용한 test module을 shell runner로 연결하고, userspace 검사는 kselftest_harness.h의 fixture와 assertion API를 사용합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ======================
2 Linux Kernel Selftests
3 ======================
4
5 The kernel contains a set of "self tests" under the tools/testing/selftests/
6 directory. These are intended to be small tests to exercise individual code
7 paths in the kernel. Tests are intended to be run after building, installing
8 and booting a kernel.
9
10 Kselftest from mainline can be run on older stable kernels. Running tests
11 from mainline offers the best coverage. Several test rings run mainline
12 kselftest suite on stable releases. The reason is that when a new test
13 gets added to test existing code to regression test a bug, we should be
14 able to run that test on an older kernel. Hence, it is important to keep
15 code that can still test an older kernel and make sure it skips the test
16 gracefully on newer releases.
17
18 You can find additional information on Kselftest framework, how to
19 write new tests using the framework on Kselftest wiki:
20
21 https://kselftest.wiki.kernel.org/
22
23 On some systems, hot-plug tests could hang forever waiting for cpu and
24 memory to be ready to be offlined. A special hot-plug target is created
25 to run the full range of hot-plug tests. In default mode, hot-plug tests run
26 in safe mode with a limited scope. In limited mode, cpu-hotplug test is
27 run on a single cpu as opposed to all hotplug capable cpus, and memory
28 hotplug test is run on 2% of hotplug capable memory instead of 10%.
29
30 kselftest runs as a userspace process. Tests that can be written/run in
31 userspace may wish to use the `Test Harness`_. Tests that need to be
32 run in kernel space may wish to use a `Test Module`_.
33
34 Documentation on the tests
35 ==========================
36
37 For documentation on the kselftests themselves, see:
38
39 .. toctree::
40
41 testing-devices
42
43 Running the selftests (hotplug tests are run in limited mode)
44 =============================================================
45
46 To build the tests::
47
48 $ make headers
49 $ make -C tools/testing/selftests
50
51 To run the tests::
52
53 $ make -C tools/testing/selftests run_tests
54
55 To build and run the tests with a single command, use::
56
57 $ make kselftest
58
59 Note that some tests will require root privileges.
60
61 Kselftest supports saving output files in a separate directory and then
62 running tests. To locate output files in a separate directory two syntaxes
63 are supported. In both cases the working directory must be the root of the
64 kernel src. This is applicable to "Running a subset of selftests" section
65 below.
66
67 To build, save output files in a separate directory with O= ::
68
69 $ make O=/tmp/kselftest kselftest
70
71 To build, save output files in a separate directory with KBUILD_OUTPUT ::
72
73 $ export KBUILD_OUTPUT=/tmp/kselftest; make kselftest
74
75 The O= assignment takes precedence over the KBUILD_OUTPUT environment
76 variable.
77
78 The above commands by default run the tests and print full pass/fail report.
79 Kselftest supports "summary" option to make it easier to understand the test
80 results. Please find the detailed individual test results for each test in
81 /tmp/testname file(s) when summary option is specified. This is applicable
82 to "Running a subset of selftests" section below.
83
84 To run kselftest with summary option enabled ::
85
86 $ make summary=1 kselftest
87
88 Running a subset of selftests
89 =============================
90
91 You can use the "TARGETS" variable on the make command line to specify
92 single test to run, or a list of tests to run.
93
94 To run only tests targeted for a single subsystem::
95
96 $ make -C tools/testing/selftests TARGETS=ptrace run_tests
97
98 You can specify multiple tests to build and run::
99
100 $ make TARGETS="size timers" kselftest
101
102 To build, save output files in a separate directory with O= ::
103
104 $ make O=/tmp/kselftest TARGETS="size timers" kselftest
105
106 To build, save output files in a separate directory with KBUILD_OUTPUT ::
107
108 $ export KBUILD_OUTPUT=/tmp/kselftest; make TARGETS="size timers" kselftest
109
110 Additionally you can use the "SKIP_TARGETS" variable on the make command
111 line to specify one or more targets to exclude from the TARGETS list.
112
113 To run all tests but a single subsystem::
114
115 $ make -C tools/testing/selftests SKIP_TARGETS=ptrace run_tests
116
117 You can specify multiple tests to skip::
118
119 $ make SKIP_TARGETS="size timers" kselftest
120
121 You can also specify a restricted list of tests to run together with a
122 dedicated skiplist::
123
124 $ make TARGETS="breakpoints size timers" SKIP_TARGETS=size kselftest
125
126 See the top-level tools/testing/selftests/Makefile for the list of all
127 possible targets.
128
129 Running the full range hotplug selftests
130 ========================================
131
132 To build the hotplug tests::
133
134 $ make -C tools/testing/selftests hotplug
135
136 To run the hotplug tests::
137
138 $ make -C tools/testing/selftests run_hotplug
139
140 Note that some tests will require root privileges.
141
142
143 Install selftests
144 =================
145
146 You can use the "install" target of "make" (which calls the `kselftest_install.sh`
147 tool) to install selftests in the default location (`tools/testing/selftests/kselftest_install`),
148 or in a user specified location via the `INSTALL_PATH` "make" variable.
149
150 To install selftests in default location::
151
152 $ make -C tools/testing/selftests install
153
154 To install selftests in a user specified location::
155
156 $ make -C tools/testing/selftests install INSTALL_PATH=/some/other/path
157
158 Running installed selftests
159 ===========================
160
161 Found in the install directory, as well as in the Kselftest tarball,
162 is a script named `run_kselftest.sh` to run the tests.
163
164 You can simply do the following to run the installed Kselftests. Please
165 note some tests will require root privileges::
166
167 $ cd kselftest_install
168 $ ./run_kselftest.sh
169
170 To see the list of available tests, the `-l` option can be used::
171
172 $ ./run_kselftest.sh -l
173
174 The `-c` option can be used to run all the tests from a test collection, or
175 the `-t` option for specific single tests. Either can be used multiple times::
176
177 $ ./run_kselftest.sh -c size -c seccomp -t timers:posix_timers -t timer:nanosleep
178
179 For other features see the script usage output, seen with the `-h` option.
180
181 Timeout for selftests
182 =====================
183
184 Selftests are designed to be quick and so a default timeout is used of 45
185 seconds for each test. Tests can override the default timeout by adding
186 a settings file in their directory and set a timeout variable there to the
187 configured a desired upper timeout for the test. Only a few tests override
188 the timeout with a value higher than 45 seconds, selftests strives to keep
189 it that way. Timeouts in selftests are not considered fatal because the
190 system under which a test runs may change and this can also modify the
191 expected time it takes to run a test. If you have control over the systems
192 which will run the tests you can configure a test runner on those systems to
193 use a greater or lower timeout on the command line as with the `-o` or
194 the `--override-timeout` argument. For example to use 165 seconds instead
195 one would use::
196
197 $ ./run_kselftest.sh --override-timeout 165
198
199 You can look at the TAP output to see if you ran into the timeout. Test
200 runners which know a test must run under a specific time can then optionally
201 treat these timeouts then as fatal.
202
203 Packaging selftests
204 ===================
205
206 In some cases packaging is desired, such as when tests need to run on a
207 different system. To package selftests, run::
208
209 $ make -C tools/testing/selftests gen_tar
210
211 This generates a tarball in the `INSTALL_PATH/kselftest-packages` directory. By
212 default, `.gz` format is used. The tar compression format can be overridden by
213 specifying a `FORMAT` make variable. Any value recognized by `tar's auto-compress`_
214 option is supported, such as::
215
216 $ make -C tools/testing/selftests gen_tar FORMAT=.xz
217
218 `make gen_tar` invokes `make install` so you can use it to package a subset of
219 tests by using variables specified in `Running a subset of selftests`_
220 section::
221
222 $ make -C tools/testing/selftests gen_tar TARGETS="size" FORMAT=.xz
223
224 .. _tar's auto-compress: https://www.gnu.org/software/tar/manual/html_node/gzip.html#auto_002dcompress
225
226 Contributing new tests
227 ======================
228
229 In general, the rules for selftests are
230
231 * Do as much as you can if you're not root;
232
233 * Don't take too long;
234
235 * Don't break the build on any architecture, and
236
237 * Don't cause the top-level "make run_tests" to fail if your feature is
238 unconfigured.
239
240 * The output of tests must conform to the TAP standard to ensure high
241 testing quality and to capture failures/errors with specific details.
242 The kselftest.h and kselftest_harness.h headers provide wrappers for
243 outputting test results. These wrappers should be used for pass,
244 fail, exit, and skip messages. CI systems can easily parse TAP output
245 messages to detect test results.
246
247 Contributing new tests (details)
248 ================================
249
250 * In your Makefile, use facilities from lib.mk by including it instead of
251 reinventing the wheel. Specify flags and binaries generation flags on
252 need basis before including lib.mk. ::
253
254 CFLAGS = $(KHDR_INCLUDES)
255 TEST_GEN_PROGS := close_range_test
256 include ../lib.mk
257
258 * Use TEST_GEN_XXX if such binaries or files are generated during
259 compiling.
260
261 TEST_PROGS, TEST_GEN_PROGS mean it is the executable tested by
262 default.
263
264 TEST_GEN_MODS_DIR should be used by tests that require modules to be built
265 before the test starts. The variable will contain the name of the directory
266 containing the modules.
267
268 TEST_CUSTOM_PROGS should be used by tests that require custom build
269 rules and prevent common build rule use.
270
271 TEST_PROGS are for test shell scripts. Please ensure shell script has
272 its exec bit set. Otherwise, lib.mk run_tests will generate a warning.
273
274 TEST_CUSTOM_PROGS and TEST_PROGS will be run by common run_tests.
275
276 TEST_PROGS_EXTENDED, TEST_GEN_PROGS_EXTENDED mean it is the
277 executable which is not tested by default.
278
279 TEST_FILES, TEST_GEN_FILES mean it is the file which is used by
280 test.
281
282 TEST_INCLUDES is similar to TEST_FILES, it lists files which should be
283 included when exporting or installing the tests, with the following
284 differences:
285
286 * symlinks to files in other directories are preserved
287 * the part of paths below tools/testing/selftests/ is preserved when
288 copying the files to the output directory
289
290 TEST_INCLUDES is meant to list dependencies located in other directories of
291 the selftests hierarchy.
292
293 * First use the headers inside the kernel source and/or git repo, and then the
294 system headers. Headers for the kernel release as opposed to headers
295 installed by the distro on the system should be the primary focus to be able
296 to find regressions. Use KHDR_INCLUDES in Makefile to include headers from
297 the kernel source.
298
299 * If a test needs specific kernel config options enabled, add a config file in
300 the test directory to enable them.
301
302 e.g: tools/testing/selftests/android/config
303
304 * Create a .gitignore file inside test directory and add all generated objects
305 in it.
306
307 * Add new test name in TARGETS in selftests/Makefile::
308
309 TARGETS += android
310
311 * All changes should pass::
312
313 kselftest-{all,install,clean,gen_tar}
314 kselftest-{all,install,clean,gen_tar} O=abo_path
315 kselftest-{all,install,clean,gen_tar} O=rel_path
316 make -C tools/testing/selftests {all,install,clean,gen_tar}
317 make -C tools/testing/selftests {all,install,clean,gen_tar} O=abs_path
318 make -C tools/testing/selftests {all,install,clean,gen_tar} O=rel_path
319
320 Test Module
321 ===========
322
323 Kselftest tests the kernel from userspace. Sometimes things need
324 testing from within the kernel, one method of doing this is to create a
325 test module. We can tie the module into the kselftest framework by
326 using a shell script test runner. ``kselftest/module.sh`` is designed
327 to facilitate this process. There is also a header file provided to
328 assist writing kernel modules that are for use with kselftest:
329
330 - ``tools/testing/selftests/kselftest_module.h``
331 - ``tools/testing/selftests/kselftest/module.sh``
332
333 Note that test modules should taint the kernel with TAINT_TEST. This will
334 happen automatically for modules which are in the ``tools/testing/``
335 directory, or for modules which use the ``kselftest_module.h`` header above.
336 Otherwise, you'll need to add ``MODULE_INFO(test, "Y")`` to your module
337 source. selftests which do not load modules typically should not taint the
338 kernel, but in cases where a non-test module is loaded, TEST_TAINT can be
339 applied from userspace by writing to ``/proc/sys/kernel/tainted``.
340
341 How to use
342 ----------
343
344 Here we show the typical steps to create a test module and tie it into
345 kselftest. We use kselftests for lib/ as an example.
346
347 1. Create the test module
348
349 2. Create the test script that will run (load/unload) the module
350 e.g. ``tools/testing/selftests/lib/bitmap.sh``
351
352 3. Add line to config file e.g. ``tools/testing/selftests/lib/config``
353
354 4. Add test script to makefile e.g. ``tools/testing/selftests/lib/Makefile``
355
356 5. Verify it works:
357
358 .. code-block:: sh
359
360 # Assumes you have booted a fresh build of this kernel tree
361 cd /path/to/linux/tree
362 make kselftest-merge
363 make modules
364 sudo make modules_install
365 make TARGETS=lib kselftest
366
367 Example Module
368 --------------
369
370 A bare bones test module might look like this:
371
372 .. code-block:: c
373
374 // SPDX-License-Identifier: GPL-2.0+
375
376 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
377
378 #include "../tools/testing/selftests/kselftest_module.h"
379
380 KSTM_MODULE_GLOBALS();
381
382 /*
383 * Kernel module for testing the foobinator
384 */
385
386 static int __init test_function()
387 {
388 ...
389 }
390
391 static void __init selftest(void)
392 {
393 KSTM_CHECK_ZERO(do_test_case("", 0));
394 }
395
396 KSTM_MODULE_LOADERS(test_foo);
397 MODULE_AUTHOR("John Developer <[email protected]>");
398 MODULE_LICENSE("GPL");
399 MODULE_INFO(test, "Y");
400
401 Example test script
402 -------------------
403
404 .. code-block:: sh
405
406 #!/bin/bash
407 # SPDX-License-Identifier: GPL-2.0+
408 $(dirname $0)/../kselftest/module.sh "foo" test_foo
409
410
411 Test Harness
412 ============
413
414 The kselftest_harness.h file contains useful helpers to build tests. The
415 test harness is for userspace testing, for kernel space testing see `Test
416 Module`_ above.
417
418 The tests from tools/testing/selftests/seccomp/seccomp_bpf.c can be used as
419 example.
420
421 Example
422 -------
423
424 .. kernel-doc:: tools/testing/selftests/kselftest_harness.h
425 :doc: example
426
427
428 Helpers
429 -------
430
431 .. kernel-doc:: tools/testing/selftests/kselftest_harness.h
432 :functions: TH_LOG TEST TEST_SIGNAL FIXTURE FIXTURE_DATA FIXTURE_SETUP
433 FIXTURE_TEARDOWN TEST_F TEST_HARNESS_MAIN FIXTURE_VARIANT
434 FIXTURE_VARIANT_ADD
435
436 Operators
437 ---------
438
439 .. kernel-doc:: tools/testing/selftests/kselftest_harness.h
440 :doc: operators
441
442 .. kernel-doc:: tools/testing/selftests/kselftest_harness.h
443 :functions: ASSERT_EQ ASSERT_NE ASSERT_LT ASSERT_LE ASSERT_GT ASSERT_GE
444 ASSERT_NULL ASSERT_TRUE ASSERT_NULL ASSERT_TRUE ASSERT_FALSE
445 ASSERT_STREQ ASSERT_STRNE EXPECT_EQ EXPECT_NE EXPECT_LT
446 EXPECT_LE EXPECT_GT EXPECT_GE EXPECT_NULL EXPECT_TRUE
447 EXPECT_FALSE EXPECT_STREQ EXPECT_STRNE
448

3. 한국어 전문 번역

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

Kselftest 개요와 테스트 문서

1-42

Linux Kernel Selftests

커널은 `tools/testing/selftests/` 디렉터리에 self test 모음을 포함합니다. 각각은 커널의 개별 코드 경로를 실행하는 작은 테스트이며 커널을 빌드하고 설치한 뒤 부팅한 상태에서 실행하도록 만들어졌습니다.

Mainline의 Kselftest는 더 오래된 stable kernel에서도 실행할 수 있습니다. Mainline 테스트를 실행할 때 가장 넓은 범위를 검사할 수 있으며 여러 test ring도 stable release에서 mainline kselftest suite를 실행합니다. 기존 코드의 버그를 회귀 검사하는 새 테스트가 추가되면 오래된 커널에서도 그 테스트를 실행할 수 있어야 하기 때문입니다. 따라서 오래된 커널을 계속 검사할 수 있는 코드를 유지하고, 더 새로운 release에서는 적용할 수 없는 테스트를 정상적으로 skip하도록 만드는 것이 중요합니다.

Kselftest framework와 framework를 이용한 새 테스트 작성 방법은 Kselftest wiki에서 더 자세히 볼 수 있습니다.

https://kselftest.wiki.kernel.org/

일부 시스템의 hot-plug 테스트는 CPU와 memory가 offline 준비 상태가 되기를 영원히 기다리며 멈출 수 있습니다. 전체 hot-plug 테스트를 실행하기 위한 특별한 hot-plug target이 제공됩니다. 기본 모드에서는 범위를 제한한 safe mode로 실행합니다. 이 제한 모드의 cpu-hotplug test는 hotplug 가능한 모든 CPU 대신 한 CPU에서만 실행하고, memory hotplug test는 hotplug 가능한 memory의 10% 대신 2%에서 실행합니다.

kselftest는 userspace process로 실행됩니다. userspace에서 작성하고 실행할 수 있는 테스트는 `Test Harness`를 사용할 수 있습니다. kernel space에서 실행해야 하는 테스트는 `Test Module`을 사용할 수 있습니다.

테스트 문서

각 kselftest 자체의 문서는 다음 항목을 참조하십시오.

.. toctree::

   testing-devices

전체 selftest 빌드와 실행

43-87

Selftest 실행, hotplug 테스트는 제한 모드

테스트를 빌드합니다.

$ make headers
$ make -C tools/testing/selftests

테스트를 실행합니다.

$ make -C tools/testing/selftests run_tests

하나의 명령으로 빌드하고 실행하려면 다음을 사용합니다.

$ make kselftest

일부 테스트에는 root 권한이 필요합니다.

Kselftest는 output file을 별도 디렉터리에 저장한 뒤 테스트를 실행할 수 있습니다. 별도 디렉터리를 지정하는 두 가지 문법을 지원하며 어느 방식을 사용하든 working directory는 kernel source의 root여야 합니다. 이 규칙은 뒤의 selftest 부분 집합 실행에도 적용됩니다.

`O=`를 사용해 별도 디렉터리에 output file을 저장합니다.

$ make O=/tmp/kselftest kselftest

KBUILD_OUTPUT을 사용해 별도 디렉터리에 저장합니다.

$ export KBUILD_OUTPUT=/tmp/kselftest; make kselftest

`O=` 할당은 KBUILD_OUTPUT environment variable보다 우선합니다.

위 명령은 기본적으로 테스트를 실행하고 전체 pass 또는 fail 보고서를 출력합니다. 결과를 더 쉽게 이해할 수 있도록 Kselftest는 `summary` option을 지원합니다. summary를 지정하면 각 테스트의 상세 결과는 `/tmp/testname` 파일에서 확인하십시오. 이 기능도 selftest 부분 집합 실행에 적용됩니다.

Summary option을 활성화해 kselftest를 실행합니다.

$ make summary=1 kselftest
기본 Kselftest 실행 흐름
커널 빌드와 부팅검사할 kernel 환경 준비
make headersuserspace test용 header 준비
selftest 빌드tools/testing/selftests target 생성
run_tests 또는 kselftestTAP 결과와 상세 로그 수집

커널 소스 루트에서 header와 test를 준비하고 실행 결과를 수집하는 순서입니다.

부분 집합, 제외 목록과 전체 hotplug 검사

88-142

Selftest 부분 집합 실행

make command line의 `TARGETS` variable로 실행할 단일 테스트나 테스트 목록을 지정할 수 있습니다.

한 subsystem을 대상으로 하는 테스트만 실행합니다.

$ make -C tools/testing/selftests TARGETS=ptrace run_tests

여러 테스트를 지정해 빌드하고 실행할 수 있습니다.

$  make TARGETS="size timers" kselftest

`O=`를 사용해 별도 디렉터리에 output file을 저장합니다.

$ make O=/tmp/kselftest TARGETS="size timers" kselftest

KBUILD_OUTPUT을 사용해 별도 디렉터리에 output file을 저장합니다.

$ export KBUILD_OUTPUT=/tmp/kselftest; make TARGETS="size timers" kselftest

또한 make command line의 `SKIP_TARGETS` variable로 TARGETS 목록에서 제외할 target 하나 이상을 지정할 수 있습니다.

하나의 subsystem만 제외하고 모든 테스트를 실행합니다.

$ make -C tools/testing/selftests SKIP_TARGETS=ptrace run_tests

여러 테스트를 건너뛸 수 있습니다.

$  make SKIP_TARGETS="size timers" kselftest

제한된 테스트 목록과 전용 skiplist를 함께 지정할 수도 있습니다.

$  make TARGETS="breakpoints size timers" SKIP_TARGETS=size kselftest

가능한 모든 target 목록은 최상위 `tools/testing/selftests/Makefile`을 참조하십시오.

전체 범위 hotplug selftest 실행

Hotplug 테스트를 빌드합니다.

$ make -C tools/testing/selftests hotplug

Hotplug 테스트를 실행합니다.

$ make -C tools/testing/selftests run_hotplug

일부 테스트에는 root 권한이 필요합니다.

Kselftest 대상 선택 변수
변수역할
TARGETS실행할 subsystem 선택ptrace, size timers
SKIP_TARGETS선택 목록에서 제외size
O=별도 output directory/tmp/kselftest
KBUILD_OUTPUT환경 변수 기반 output directory/tmp/kselftest

전체 suite에서 실행 또는 제외할 범위와 output 위치를 결정하는 make 변수를 정리했습니다.

설치와 설치된 테스트 실행

143-180

Selftest 설치

`make`의 `install` target은 `kselftest_install.sh`를 호출해 selftest를 기본 위치인 `tools/testing/selftests/kselftest_install`에 설치합니다. `INSTALL_PATH` make variable을 사용하면 사용자가 지정한 위치에 설치할 수 있습니다.

기본 위치에 selftest를 설치합니다.

$ make -C tools/testing/selftests install

사용자 지정 위치에 selftest를 설치합니다.

$ make -C tools/testing/selftests install INSTALL_PATH=/some/other/path

설치된 selftest 실행

설치 디렉터리와 Kselftest tarball에는 테스트를 실행하는 `run_kselftest.sh` script가 들어 있습니다.

설치된 Kselftest는 다음과 같이 실행합니다. 일부 테스트에는 root 권한이 필요합니다.

$ cd kselftest_install
$ ./run_kselftest.sh

사용 가능한 테스트 목록은 `-l` option으로 봅니다.

$ ./run_kselftest.sh -l

`-c` option은 test collection의 모든 테스트를 실행하고 `-t` option은 특정 단일 테스트를 실행합니다. 두 option 모두 여러 번 사용할 수 있습니다.

$ ./run_kselftest.sh -c size -c seccomp -t timers:posix_timers -t timer:nanosleep

다른 기능은 `-h` option으로 표시하는 script usage를 참조하십시오.

Timeout과 배포용 패키지

181-225

Selftest timeout

Selftest는 빠르게 끝나도록 설계되므로 각 테스트의 기본 timeout은 45초입니다. 테스트 디렉터리에 settings file을 추가하고 timeout variable을 원하는 최대 시간으로 설정하면 기본값을 재정의할 수 있습니다. 45초보다 긴 값을 쓰는 테스트는 소수이며 selftest는 이를 계속 적게 유지하려고 합니다.

테스트가 실행되는 시스템에 따라 예상 시간이 달라질 수 있으므로 selftest의 timeout은 fatal로 간주되지 않습니다. 실행 시스템을 제어할 수 있다면 test runner의 command line에 `-o` 또는 `--override-timeout`을 지정하여 더 길거나 짧은 timeout을 설정할 수 있습니다. 165초를 사용하려면 다음과 같이 실행합니다.

$ ./run_kselftest.sh --override-timeout 165

Timeout 발생 여부는 TAP output에서 확인할 수 있습니다. 특정 시간 안에 끝나야 한다는 것을 아는 test runner는 이 timeout을 선택적으로 fatal로 처리할 수 있습니다.

Selftest 패키징

다른 시스템에서 테스트해야 하는 경우처럼 패키징이 필요할 때는 다음 명령을 실행합니다.

$ make -C tools/testing/selftests gen_tar

이 명령은 `INSTALL_PATH/kselftest-packages` 디렉터리에 tarball을 생성합니다. 기본 형식은 `.gz`입니다. `FORMAT` make variable로 tar 압축 형식을 바꿀 수 있으며 `tar's auto-compress` option이 인식하는 모든 값을 지원합니다.

$ make -C tools/testing/selftests gen_tar FORMAT=.xz

`make gen_tar`는 `make install`을 호출하므로 selftest 부분 집합 실행 절에서 설명한 variable을 사용해 테스트 일부만 패키징할 수 있습니다.

$ make -C tools/testing/selftests gen_tar TARGETS="size" FORMAT=.xz

tar auto-compress 참고: https://www.gnu.org/software/tar/manual/html_node/gzip.html#auto_002dcompress

새 테스트 기여 원칙

226-246

새 테스트 기여

Selftest의 일반 규칙은 다음과 같습니다.

Root가 아니더라도 가능한 범위에서 최대한 많은 검사를 수행하십시오.

지나치게 오래 실행하지 마십시오.

어떤 architecture에서도 build를 깨뜨리지 마십시오.

검사할 기능이 구성되지 않았더라도 최상위 `make run_tests`가 실패하게 만들지 마십시오.

테스트 품질을 높이고 failure와 error를 구체적인 세부 정보와 함께 기록할 수 있도록 test output은 TAP 표준을 따라야 합니다. `kselftest.h`와 `kselftest_harness.h` header는 pass, fail, exit, skip message를 출력하는 wrapper를 제공하며 이를 사용해야 합니다. CI system은 TAP output message를 쉽게 parsing해 결과를 판별할 수 있습니다.

Makefile 변수와 빌드 검증

247-319

새 테스트 기여 상세

Makefile에서는 기능을 새로 구현하지 말고 `lib.mk`를 include하여 그 기능을 사용하십시오. 필요한 flag와 binary 생성 flag는 lib.mk를 include하기 전에 지정합니다.

CFLAGS = $(KHDR_INCLUDES)
TEST_GEN_PROGS := close_range_test
include ../lib.mk

Compile 중 binary나 file을 생성한다면 TEST_GEN_XXX 계열을 사용하십시오.

TEST_PROGS와 TEST_GEN_PROGS는 기본적으로 실행해 검사하는 executable을 뜻합니다.

TEST_GEN_MODS_DIR은 테스트 시작 전에 module을 build해야 하는 테스트에 사용합니다. 이 변수에는 module을 포함한 디렉터리 이름을 넣습니다.

TEST_CUSTOM_PROGS는 custom build rule이 필요하여 공통 build rule을 사용하지 않아야 하는 테스트에 씁니다.

TEST_PROGS는 test shell script용입니다. Shell script에 exec bit가 설정되어 있는지 확인하십시오. 그렇지 않으면 lib.mk의 run_tests가 warning을 냅니다.

TEST_CUSTOM_PROGS와 TEST_PROGS는 공통 run_tests가 실행합니다.

TEST_PROGS_EXTENDED와 TEST_GEN_PROGS_EXTENDED는 기본적으로 검사하지 않는 executable을 뜻합니다.

TEST_FILES와 TEST_GEN_FILES는 테스트가 사용하는 file을 뜻합니다.

TEST_INCLUDES는 TEST_FILES와 비슷하며 테스트를 export하거나 install할 때 포함할 file을 나열합니다. 다만 다른 디렉터리의 file을 가리키는 symbolic link를 보존하고, file을 output directory로 복사할 때 `tools/testing/selftests/` 아래의 경로 부분도 보존합니다.

TEST_INCLUDES는 selftest hierarchy의 다른 디렉터리에 있는 dependency를 나열하기 위한 변수입니다.

먼저 kernel source 또는 git repository 안의 header를 사용하고 그다음 system header를 사용하십시오. 회귀를 찾으려면 distribution이 설치한 header보다 검사 대상 kernel release의 header를 우선해야 합니다. Makefile에서 KHDR_INCLUDES를 사용해 kernel source의 header를 include하십시오.

테스트에 특정 kernel config option이 필요하면 test directory에 해당 option을 활성화하는 config file을 추가합니다. 예: `tools/testing/selftests/android/config`.

Test directory 안에 `.gitignore` file을 만들고 생성되는 모든 object를 추가합니다.

새 test 이름을 `selftests/Makefile`의 TARGETS에 추가합니다.

TARGETS += android

모든 변경은 다음 명령을 통과해야 합니다.

kselftest-{all,install,clean,gen_tar}
kselftest-{all,install,clean,gen_tar} O=abo_path
kselftest-{all,install,clean,gen_tar} O=rel_path
make -C tools/testing/selftests {all,install,clean,gen_tar}
make -C tools/testing/selftests {all,install,clean,gen_tar} O=abs_path
make -C tools/testing/selftests {all,install,clean,gen_tar} O=rel_path
Selftest Makefile 분류
변수대상기본 실행
TEST_PROGSShell test script
TEST_GEN_PROGS생성한 test executable
TEST_CUSTOM_PROGSCustom build rule 프로그램
TEST_PROGS_EXTENDED추가 test executable아니요
TEST_FILES테스트가 사용하는 file해당 없음
TEST_INCLUDES다른 selftest 디렉터리의 dependency해당 없음

생성물의 종류와 기본 실행 여부에 따라 사용해야 하는 lib.mk 변수를 구분합니다.

Kernel test module 작성 절차

320-366

Test Module

Kselftest는 userspace에서 커널을 검사합니다. 때로 kernel 내부에서 검사해야 할 항목이 있으며, 한 가지 방법은 test module을 만드는 것입니다. Shell script test runner로 module을 kselftest framework에 연결할 수 있습니다. `kselftest/module.sh`는 이 과정을 돕도록 설계되었습니다. Kselftest용 kernel module 작성을 돕는 header와 script도 제공됩니다.

`tools/testing/selftests/kselftest_module.h`

`tools/testing/selftests/kselftest/module.sh`

Test module은 TAINT_TEST로 kernel을 taint해야 합니다. `tools/testing/` 디렉터리 안의 module이나 위의 `kselftest_module.h` header를 사용하는 module은 자동으로 처리됩니다. 그 밖의 module은 source에 `MODULE_INFO(test, "Y")`를 추가해야 합니다.

Module을 load하지 않는 selftest는 일반적으로 kernel을 taint하지 않아야 합니다. 다만 test module이 아닌 module을 load하는 경우 userspace에서 `/proc/sys/kernel/tainted`에 써서 TEST_TAINT를 적용할 수 있습니다.

사용 방법

여기서는 test module을 만들고 kselftest에 연결하는 일반적인 단계를 `lib/`용 kselftest를 예로 설명합니다.

1. Test module을 만듭니다.

2. Module을 load하고 unload할 test script를 만듭니다. 예: `tools/testing/selftests/lib/bitmap.sh`.

3. Config file에 항목을 추가합니다. 예: `tools/testing/selftests/lib/config`.

4. Makefile에 test script를 추가합니다. 예: `tools/testing/selftests/lib/Makefile`.

5. 다음과 같이 동작을 검증합니다.

# Assumes you have booted a fresh build of this kernel tree
cd /path/to/linux/tree
make kselftest-merge
make modules
sudo make modules_install
make TARGETS=lib kselftest

Test module과 실행 script 예

367-410

Module 예

최소 구성의 test module은 다음과 같습니다.

// SPDX-License-Identifier: GPL-2.0+

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include "../tools/testing/selftests/kselftest_module.h"

KSTM_MODULE_GLOBALS();

/*
 * Kernel module for testing the foobinator
 */

static int __init test_function()
{
        ...
}

static void __init selftest(void)
{
        KSTM_CHECK_ZERO(do_test_case("", 0));
}

KSTM_MODULE_LOADERS(test_foo);
MODULE_AUTHOR("John Developer <[email protected]>");
MODULE_LICENSE("GPL");
MODULE_INFO(test, "Y");

Test script 예

#!/bin/bash
# SPDX-License-Identifier: GPL-2.0+
$(dirname $0)/../kselftest/module.sh "foo" test_foo

Userspace Test Harness API

411-447

Test Harness

`kselftest_harness.h` file은 테스트 빌드에 유용한 helper를 포함합니다. Test harness는 userspace 테스트용이며 kernel space 테스트에는 앞의 `Test Module`을 사용하십시오.

`tools/testing/selftests/seccomp/seccomp_bpf.c`의 테스트를 예제로 사용할 수 있습니다.

예제

.. kernel-doc:: tools/testing/selftests/kselftest_harness.h
    :doc: example

Helper

.. kernel-doc:: tools/testing/selftests/kselftest_harness.h
    :functions: TH_LOG TEST TEST_SIGNAL FIXTURE FIXTURE_DATA FIXTURE_SETUP
                FIXTURE_TEARDOWN TEST_F TEST_HARNESS_MAIN FIXTURE_VARIANT
                FIXTURE_VARIANT_ADD

Operator

.. kernel-doc:: tools/testing/selftests/kselftest_harness.h
    :doc: operators
.. kernel-doc:: tools/testing/selftests/kselftest_harness.h
    :functions: ASSERT_EQ ASSERT_NE ASSERT_LT ASSERT_LE ASSERT_GT ASSERT_GE
                ASSERT_NULL ASSERT_TRUE ASSERT_NULL ASSERT_TRUE ASSERT_FALSE
                ASSERT_STREQ ASSERT_STRNE EXPECT_EQ EXPECT_NE EXPECT_LT
                EXPECT_LE EXPECT_GT EXPECT_GE EXPECT_NULL EXPECT_TRUE
                EXPECT_FALSE EXPECT_STREQ EXPECT_STRNE