요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
======================
Linux Kernel Selftests
======================
The kernel contains a set of "self tests" under the tools/testing/selftests/
directory. These are intended to be small tests to exercise individual code
paths in the kernel. Tests are intended to be run after building, installing
and booting a kernel.
Kselftest from mainline can be run on older stable kernels. Running tests
from mainline offers the best coverage. Several test rings run mainline
kselftest suite on stable releases. The reason is that when a new test
gets added to test existing code to regression test a bug, we should be
able to run that test on an older kernel. Hence, it is important to keep
code that can still test an older kernel and make sure it skips the test
gracefully on newer releases.
You can find additional information on Kselftest framework, how to
write new tests using the framework on Kselftest wiki:
https://kselftest.wiki.kernel.org/
On some systems, hot-plug tests could hang forever waiting for cpu and
memory to be ready to be offlined. A special hot-plug target is created
to run the full range of hot-plug tests. In default mode, hot-plug tests run
in safe mode with a limited scope. In limited mode, cpu-hotplug test is
run on a single cpu as opposed to all hotplug capable cpus, and memory
hotplug test is run on 2% of hotplug capable memory instead of 10%.
kselftest runs as a userspace process. Tests that can be written/run in
userspace may wish to use the `Test Harness`_. Tests that need to be
run in kernel space may wish to use a `Test Module`_.
Documentation on the tests
==========================
For documentation on the kselftests themselves, see:
.. toctree::
testing-devices
Running the selftests (hotplug tests are run in limited mode)
=============================================================
To build the tests::
$ make headers
$ make -C tools/testing/selftests
To run the tests::
$ make -C tools/testing/selftests run_tests
To build and run the tests with a single command, use::
$ make kselftest
Note that some tests will require root privileges.
Kselftest supports saving output files in a separate directory and then
running tests. To locate output files in a separate directory two syntaxes
are supported. In both cases the working directory must be the root of the
kernel src. This is applicable to "Running a subset of selftests" section
below.
To build, save output files in a separate directory with O= ::
$ make O=/tmp/kselftest kselftest
To build, save output files in a separate directory with KBUILD_OUTPUT ::
$ export KBUILD_OUTPUT=/tmp/kselftest; make kselftest
The O= assignment takes precedence over the KBUILD_OUTPUT environment
variable.
The above commands by default run the tests and print full pass/fail report.
Kselftest supports "summary" option to make it easier to understand the test
results. Please find the detailed individual test results for each test in
/tmp/testname file(s) when summary option is specified. This is applicable
to "Running a subset of selftests" section below.
To run kselftest with summary option enabled ::
$ make summary=1 kselftest
Running a subset of selftests
=============================
You can use the "TARGETS" variable on the make command line to specify
single test to run, or a list of tests to run.
To run only tests targeted for a single subsystem::
$ make -C tools/testing/selftests TARGETS=ptrace run_tests
You can specify multiple tests to build and run::
$ make TARGETS="size timers" kselftest
To build, save output files in a separate directory with O= ::
$ make O=/tmp/kselftest TARGETS="size timers" kselftest
To build, save output files in a separate directory with KBUILD_OUTPUT ::
$ export KBUILD_OUTPUT=/tmp/kselftest; make TARGETS="size timers" kselftest
Additionally you can use the "SKIP_TARGETS" variable on the make command
line to specify one or more targets to exclude from the TARGETS list.
To run all tests but a single subsystem::
$ make -C tools/testing/selftests SKIP_TARGETS=ptrace run_tests
You can specify multiple tests to skip::
$ make SKIP_TARGETS="size timers" kselftest
You can also specify a restricted list of tests to run together with a
dedicated skiplist::
$ make TARGETS="breakpoints size timers" SKIP_TARGETS=size kselftest
See the top-level tools/testing/selftests/Makefile for the list of all
possible targets.
Running the full range hotplug selftests
========================================
To build the hotplug tests::
$ make -C tools/testing/selftests hotplug
To run the hotplug tests::
$ make -C tools/testing/selftests run_hotplug
Note that some tests will require root privileges.
Install selftests
=================
You can use the "install" target of "make" (which calls the `kselftest_install.sh`
tool) to install selftests in the default location (`tools/testing/selftests/kselftest_install`),
or in a user specified location via the `INSTALL_PATH` "make" variable.
To install selftests in default location::
$ make -C tools/testing/selftests install
To install selftests in a user specified location::
$ make -C tools/testing/selftests install INSTALL_PATH=/some/other/path
Running installed selftests
===========================
Found in the install directory, as well as in the Kselftest tarball,
is a script named `run_kselftest.sh` to run the tests.
You can simply do the following to run the installed Kselftests. Please
note some tests will require root privileges::
$ cd kselftest_install
$ ./run_kselftest.sh
To see the list of available tests, the `-l` option can be used::
$ ./run_kselftest.sh -l
The `-c` option can be used to run all the tests from a test collection, or
the `-t` option for specific single tests. Either can be used multiple times::
$ ./run_kselftest.sh -c size -c seccomp -t timers:posix_timers -t timer:nanosleep
For other features see the script usage output, seen with the `-h` option.
Timeout for selftests
=====================
Selftests are designed to be quick and so a default timeout is used of 45
seconds for each test. Tests can override the default timeout by adding
a settings file in their directory and set a timeout variable there to the
configured a desired upper timeout for the test. Only a few tests override
the timeout with a value higher than 45 seconds, selftests strives to keep
it that way. Timeouts in selftests are not considered fatal because the
system under which a test runs may change and this can also modify the
expected time it takes to run a test. If you have control over the systems
which will run the tests you can configure a test runner on those systems to
use a greater or lower timeout on the command line as with the `-o` or
the `--override-timeout` argument. For example to use 165 seconds instead
one would use::
$ ./run_kselftest.sh --override-timeout 165
You can look at the TAP output to see if you ran into the timeout. Test
runners which know a test must run under a specific time can then optionally
treat these timeouts then as fatal.
Packaging selftests
===================
In some cases packaging is desired, such as when tests need to run on a
different system. To package selftests, run::
$ make -C tools/testing/selftests gen_tar
This generates a tarball in the `INSTALL_PATH/kselftest-packages` directory. By
default, `.gz` format is used. The tar compression format can be overridden by
specifying a `FORMAT` make variable. Any value recognized by `tar's auto-compress`_
option is supported, such as::
$ make -C tools/testing/selftests gen_tar FORMAT=.xz
`make gen_tar` invokes `make install` so you can use it to package a subset of
tests by using variables specified in `Running a subset of selftests`_
section::
$ make -C tools/testing/selftests gen_tar TARGETS="size" FORMAT=.xz
.. _tar's auto-compress: https://www.gnu.org/software/tar/manual/html_node/gzip.html#auto_002dcompress
Contributing new tests
======================
In general, the rules for selftests are
* Do as much as you can if you're not root;
* Don't take too long;
* Don't break the build on any architecture, and
* Don't cause the top-level "make run_tests" to fail if your feature is
unconfigured.
* The output of tests must conform to the TAP standard to ensure high
testing quality and to capture failures/errors with specific details.
The kselftest.h and kselftest_harness.h headers provide wrappers for
outputting test results. These wrappers should be used for pass,
fail, exit, and skip messages. CI systems can easily parse TAP output
messages to detect test results.
Contributing new tests (details)
================================
* In your Makefile, use facilities from lib.mk by including it instead of
reinventing the wheel. Specify flags and binaries generation flags on
need basis before including lib.mk. ::
CFLAGS = $(KHDR_INCLUDES)
TEST_GEN_PROGS := close_range_test
include ../lib.mk
* Use TEST_GEN_XXX if such binaries or files are generated during
compiling.
TEST_PROGS, TEST_GEN_PROGS mean it is the executable tested by
default.
TEST_GEN_MODS_DIR should be used by tests that require modules to be built
before the test starts. The variable will contain the name of the directory
containing the modules.
TEST_CUSTOM_PROGS should be used by tests that require custom build
rules and prevent common build rule use.
TEST_PROGS are for test shell scripts. Please ensure shell script has
its exec bit set. Otherwise, lib.mk run_tests will generate a warning.
TEST_CUSTOM_PROGS and TEST_PROGS will be run by common run_tests.
TEST_PROGS_EXTENDED, TEST_GEN_PROGS_EXTENDED mean it is the
executable which is not tested by default.
TEST_FILES, TEST_GEN_FILES mean it is the file which is used by
test.
TEST_INCLUDES is similar to TEST_FILES, it lists files which should be
included when exporting or installing the tests, with the following
differences:
* symlinks to files in other directories are preserved
* the part of paths below tools/testing/selftests/ is preserved when
copying the files to the output directory
TEST_INCLUDES is meant to list dependencies located in other directories of
the selftests hierarchy.
* First use the headers inside the kernel source and/or git repo, and then the
system headers. Headers for the kernel release as opposed to headers
installed by the distro on the system should be the primary focus to be able
to find regressions. Use KHDR_INCLUDES in Makefile to include headers from
the kernel source.
* If a test needs specific kernel config options enabled, add a config file in
the test directory to enable them.
e.g: tools/testing/selftests/android/config
* Create a .gitignore file inside test directory and add all generated objects
in it.
* Add new test name in TARGETS in selftests/Makefile::
TARGETS += android
* All changes should pass::
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
Test Module
===========
Kselftest tests the kernel from userspace. Sometimes things need
testing from within the kernel, one method of doing this is to create a
test module. We can tie the module into the kselftest framework by
using a shell script test runner. ``kselftest/module.sh`` is designed
to facilitate this process. There is also a header file provided to
assist writing kernel modules that are for use with kselftest:
- ``tools/testing/selftests/kselftest_module.h``
- ``tools/testing/selftests/kselftest/module.sh``
Note that test modules should taint the kernel with TAINT_TEST. This will
happen automatically for modules which are in the ``tools/testing/``
directory, or for modules which use the ``kselftest_module.h`` header above.
Otherwise, you'll need to add ``MODULE_INFO(test, "Y")`` to your module
source. selftests which do not load modules typically should not taint the
kernel, but in cases where a non-test module is loaded, TEST_TAINT can be
applied from userspace by writing to ``/proc/sys/kernel/tainted``.
How to use
----------
Here we show the typical steps to create a test module and tie it into
kselftest. We use kselftests for lib/ as an example.
1. Create the test module
2. Create the test script that will run (load/unload) the module
e.g. ``tools/testing/selftests/lib/bitmap.sh``
3. Add line to config file e.g. ``tools/testing/selftests/lib/config``
4. Add test script to makefile e.g. ``tools/testing/selftests/lib/Makefile``
5. Verify it works:
.. code-block:: sh
# 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
Example Module
--------------
A bare bones test module might look like this:
.. code-block:: c
// 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");
Example test script
-------------------
.. code-block:: sh
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0+
$(dirname $0)/../kselftest/module.sh "foo" test_foo
Test Harness
============
The kselftest_harness.h file contains useful helpers to build tests. The
test harness is for userspace testing, for kernel space testing see `Test
Module`_ above.
The tests from tools/testing/selftests/seccomp/seccomp_bpf.c can be used as
example.
Example
-------
.. kernel-doc:: tools/testing/selftests/kselftest_harness.h
:doc: example
Helpers
-------
.. 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
Operators
---------
.. 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
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Kselftest 개요와 테스트 문서
1-42Linux 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-87Selftest 실행, 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
커널 소스 루트에서 header와 test를 준비하고 실행 결과를 수집하는 순서입니다.
부분 집합, 제외 목록과 전체 hotplug 검사
88-142Selftest 부분 집합 실행
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 권한이 필요합니다.
전체 suite에서 실행 또는 제외할 범위와 output 위치를 결정하는 make 변수를 정리했습니다.
설치와 설치된 테스트 실행
143-180Selftest 설치
`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-225Selftest 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
생성물의 종류와 기본 실행 여부에 따라 사용해야 하는 lib.mk 변수를 구분합니다.
Kernel test module 작성 절차
320-366Test 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-410Module 예
최소 구성의 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-447Test 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
요약과 해설
kselftest.rst:1-447Kselftest는 부팅한 커널의 개별 코드 경로를 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를 사용합니다.