;sphinx.addnodesdocument)}( rawsourcechildren]( translations LanguagesNode)}(hhh](h pending_xref)}(hhh]docutils.nodesTextChinese (Simplified)}parenthsba attributes}(ids]classes]names]dupnames]backrefs] refdomainstdreftypedoc reftarget)/translations/zh_CN/dev-tools/kunit/usagemodnameN classnameN refexplicitutagnamehhh ubh)}(hhh]hChinese (Traditional)}hh2sbah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget)/translations/zh_TW/dev-tools/kunit/usagemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hItalian}hhFsbah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget)/translations/it_IT/dev-tools/kunit/usagemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hJapanese}hhZsbah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget)/translations/ja_JP/dev-tools/kunit/usagemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hKorean}hhnsbah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget)/translations/ko_KR/dev-tools/kunit/usagemodnameN classnameN refexplicituh1hhh ubh)}(hhh]hSpanish}hhsbah}(h]h ]h"]h$]h&] refdomainh)reftypeh+ reftarget)/translations/sp_SP/dev-tools/kunit/usagemodnameN classnameN refexplicituh1hhh ubeh}(h]h ]h"]h$]h&]current_languageEnglishuh1h hh _documenthsourceNlineNubhcomment)}(h SPDX-License-Identifier: GPL-2.0h]h SPDX-License-Identifier: GPL-2.0}hhsbah}(h]h ]h"]h$]h&] xml:spacepreserveuh1hhhhhhC/var/lib/git/docbuild/linux/Documentation/dev-tools/kunit/usage.rsthKubhsection)}(hhh](htitle)}(h Writing Testsh]h Writing Tests}(hhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(h Test Casesh]h Test Cases}(hhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhhhhhKubh paragraph)}(hThe fundamental unit in KUnit is the test case. A test case is a function with the signature ``void (*)(struct kunit *test)``. It calls the function under test and then sets *expectations* for what should happen. For example:h](h]The fundamental unit in KUnit is the test case. A test case is a function with the signature }(hhhhhNhNubhliteral)}(h ``void (*)(struct kunit *test)``h]hvoid (*)(struct kunit *test)}(hhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhubh1. It calls the function under test and then sets }(hhhhhNhNubhemphasis)}(h*expectations*h]h expectations}(hhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhubh% for what should happen. For example:}(hhhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhK hhhhubh literal_block)}(hvoid example_test_success(struct kunit *test) { } void example_test_failure(struct kunit *test) { KUNIT_FAIL(test, "This test never passes."); }h]hvoid example_test_success(struct kunit *test) { } void example_test_failure(struct kunit *test) { KUNIT_FAIL(test, "This test never passes."); }}hjsbah}(h]h ]h"]h$]h&]hhforcelanguagechighlight_args}uh1jhhhK hhhhubh)}(hXAIn the above example, ``example_test_success`` always passes because it does nothing; no expectations are set, and therefore all expectations pass. On the other hand ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``, which is a special expectation that logs a message and causes the test case to fail.h](hIn the above example, }(hj'hhhNhNubh)}(h``example_test_success``h]hexample_test_success}(hj/hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj'ubhx always passes because it does nothing; no expectations are set, and therefore all expectations pass. On the other hand }(hj'hhhNhNubh)}(h``example_test_failure``h]hexample_test_failure}(hjAhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj'ubh always fails because it calls }(hj'hhhNhNubh)}(h``KUNIT_FAIL``h]h KUNIT_FAIL}(hjShhhNhNubah}(h]h ]h"]h$]h&]uh1hhj'ubhV, which is a special expectation that logs a message and causes the test case to fail.}(hj'hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhhhhubh)}(hhh](h)}(h Expectationsh]h Expectations}(hjnhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjkhhhhhKubh)}(hXIAn *expectation* specifies that we expect a piece of code to do something in a test. An expectation is called like a function. A test is made by setting expectations about the behavior of a piece of code under test. When one or more expectations fail, the test case fails and information about the failure is logged. For example:h](hAn }(hj|hhhNhNubh)}(h *expectation*h]h expectation}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj|ubhX9 specifies that we expect a piece of code to do something in a test. An expectation is called like a function. A test is made by setting expectations about the behavior of a piece of code under test. When one or more expectations fail, the test case fails and information about the failure is logged. For example:}(hj|hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhK hjkhhubj)}(hvoid add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); }h]hvoid add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhK&hjkhhubh)}(hXIn the above example, ``add_test_basic`` makes a number of assertions about the behavior of a function called ``add``. The first parameter is always of type ``struct kunit *``, which contains information about the current test context. The second parameter, in this case, is what the value is expected to be. The last value is what the value actually is. If ``add`` passes all of these expectations, the test case, ``add_test_basic`` will pass; if any one of these expectations fails, the test case will fail.h](hIn the above example, }(hjhhhNhNubh)}(h``add_test_basic``h]hadd_test_basic}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhF makes a number of assertions about the behavior of a function called }(hjhhhNhNubh)}(h``add``h]hadd}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh(. The first parameter is always of type }(hjhhhNhNubh)}(h``struct kunit *``h]hstruct kunit *}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, which contains information about the current test context. The second parameter, in this case, is what the value is expected to be. The last value is what the value actually is. If }(hjhhhNhNubh)}(h``add``h]hadd}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh2 passes all of these expectations, the test case, }(hjhhhNhNubh)}(h``add_test_basic``h]hadd_test_basic}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhL will pass; if any one of these expectations fails, the test case will fail.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhK.hjkhhubh)}(hA test case *fails* when any expectation is violated; however, the test will continue to run, and try other expectations until the test case ends or is otherwise terminated. This is as opposed to *assertions* which are discussed later.h](h A test case }(hjhhhNhNubh)}(h*fails*h]hfails}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh when any expectation is violated; however, the test will continue to run, and try other expectations until the test case ends or is otherwise terminated. This is as opposed to }(hjhhhNhNubh)}(h *assertions*h]h assertions}(hj-hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh which are discussed later.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhK6hjkhhubh)}(hWTo learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst.h]hWTo learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst.}(hjEhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK;hjkhhubhnote)}(hYA single test case should be short, easy to understand, and focused on a single behavior.h]h)}(hYA single test case should be short, easy to understand, and focused on a single behavior.h]hYA single test case should be short, easy to understand, and focused on a single behavior.}(hjYhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK>hjUubah}(h]h ]h"]h$]h&]uh1jShjkhhhhhNubh)}(hFor example, if we want to rigorously test the ``add`` function above, create additional tests cases which would test each property that an ``add`` function should have as shown below:h](h/For example, if we want to rigorously test the }(hjmhhhNhNubh)}(h``add``h]hadd}(hjuhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjmubhV function above, create additional tests cases which would test each property that an }(hjmhhhNhNubh)}(h``add``h]hadd}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjmubh% function should have as shown below:}(hjmhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKAhjkhhubj)}(hXvoid add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } void add_test_negative(struct kunit *test) { KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); } void add_test_max(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); } void add_test_overflow(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1)); }h]hXvoid add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } void add_test_negative(struct kunit *test) { KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); } void add_test_max(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); } void add_test_overflow(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1)); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhKEhjkhhubeh}(h] expectationsah ]h"] expectationsah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(h Assertionsh]h Assertions}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhK^ubh)}(hAn assertion is like an expectation, except that the assertion immediately terminates the test case if the condition is not satisfied. For example:h]hAn assertion is like an expectation, except that the assertion immediately terminates the test case if the condition is not satisfied. For example:}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK`hjhhubj)}(hXstatic void test_sort(struct kunit *test) { int *a, i, r = 1; a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a); for (i = 0; i < TEST_LEN; i++) { r = (r * 725861) % 6599; a[i] = r; } sort(a, TEST_LEN, sizeof(*a), cmpint, NULL); for (i = 0; i < TEST_LEN-1; i++) KUNIT_EXPECT_LE(test, a[i], a[i + 1]); }h]hXstatic void test_sort(struct kunit *test) { int *a, i, r = 1; a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a); for (i = 0; i < TEST_LEN; i++) { r = (r * 725861) % 6599; a[i] = r; } sort(a, TEST_LEN, sizeof(*a), cmpint, NULL); for (i = 0; i < TEST_LEN-1; i++) KUNIT_EXPECT_LE(test, a[i], a[i + 1]); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhKchjhhubh)}(hIn this example, we need to be able to allocate an array to test the ``sort()`` function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_NULL()`` to abort the test if there's an allocation error.h](hEIn this example, we need to be able to allocate an array to test the }(hjhhhNhNubh)}(h ``sort()``h]hsort()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh function. So we use }(hjhhhNhNubh)}(h"``KUNIT_ASSERT_NOT_ERR_OR_NULL()``h]hKUNIT_ASSERT_NOT_ERR_OR_NULL()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh4 to abort the test if there’s an allocation error.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKshjhhubjT)}(hIn other test frameworks, ``ASSERT`` macros are often implemented by calling ``return`` so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere.h]h)}(hIn other test frameworks, ``ASSERT`` macros are often implemented by calling ``return`` so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere.h](hIn other test frameworks, }(hjhhhNhNubh)}(h ``ASSERT``h]hASSERT}(hj"hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh) macros are often implemented by calling }(hjhhhNhNubh)}(h ``return``h]hreturn}(hj4hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKxhjubah}(h]h ]h"]h$]h&]uh1jShjhhhhhNubjT)}(hX&Warning: There is an exception to the above rule. You shouldn't use assertions in the suite's exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak.h]h)}(hX&Warning: There is an exception to the above rule. You shouldn't use assertions in the suite's exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak.h]hX*Warning: There is an exception to the above rule. You shouldn’t use assertions in the suite’s exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak.}(hjVhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhK}hjRubah}(h]h ]h"]h$]h&]uh1jShjhhhhhNubeh}(h] assertionsah ]h"] assertionsah$]h&]uh1hhhhhhhhK^ubeh}(h] test-casesah ]h"] test casesah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(hCustomizing error messagesh]hCustomizing error messages}(hj}hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjzhhhhhKubh)}(hEach of the ``KUNIT_EXPECT`` and ``KUNIT_ASSERT`` macros have a ``_MSG`` variant. These take a format string and arguments to provide additional context to the automatically generated error messages.h](h Each of the }(hjhhhNhNubh)}(h``KUNIT_EXPECT``h]h KUNIT_EXPECT}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh and }(hjhhhNhNubh)}(h``KUNIT_ASSERT``h]h KUNIT_ASSERT}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh macros have a }(hjhhhNhNubh)}(h``_MSG``h]h_MSG}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh variant. These take a format string and arguments to provide additional context to the automatically generated error messages.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhjzhhubj)}(hXchar some_str[41]; generate_sha1_hex_string(some_str); /* Before. Not easy to tell why the test failed. */ KUNIT_EXPECT_EQ(test, strlen(some_str), 40); /* After. Now we see the offending string. */ KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str);h]hXchar some_str[41]; generate_sha1_hex_string(some_str); /* Before. Not easy to tell why the test failed. */ KUNIT_EXPECT_EQ(test, strlen(some_str), 40); /* After. Now we see the offending string. */ KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str);}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhKhjzhhubh)}(h_Alternatively, one can take full control over the error message by using ``KUNIT_FAIL()``, e.g.h](hIAlternatively, one can take full control over the error message by using }(hjhhhNhNubh)}(h``KUNIT_FAIL()``h]h KUNIT_FAIL()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, e.g.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhjzhhubj)}(h/* Before */ KUNIT_EXPECT_EQ(test, some_setup_function(), 0); /* After: full control over the failure message. */ if (some_setup_function()) KUNIT_FAIL(test, "Failed to setup thing for testing");h]h/* Before */ KUNIT_EXPECT_EQ(test, some_setup_function(), 0); /* After: full control over the failure message. */ if (some_setup_function()) KUNIT_FAIL(test, "Failed to setup thing for testing");}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhKhjzhhubh)}(hhh](h)}(h Test Suitesh]h Test Suites}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj hhhhhKubh)}(hXWe need many test cases covering all the unit's behaviors. It is common to have many similar tests. In order to reduce duplication in these closely related tests, most unit testing frameworks (including KUnit) provide the concept of a *test suite*. A test suite is a collection of test cases for a unit of code with optional setup and teardown functions that run before/after the whole suite and/or every test case.h](hWe need many test cases covering all the unit’s behaviors. It is common to have many similar tests. In order to reduce duplication in these closely related tests, most unit testing frameworks (including KUnit) provide the concept of a }(hjhhhNhNubh)}(h *test suite*h]h test suite}(hj&hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh. A test suite is a collection of test cases for a unit of code with optional setup and teardown functions that run before/after the whole suite and/or every test case.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhj hhubjT)}(h@A test case will only run if it is associated with a test suite.h]h)}(hj@h]h@A test case will only run if it is associated with a test suite.}(hjBhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj>ubah}(h]h ]h"]h$]h&]uh1jShj hhhhhNubh)}(h For example:h]h For example:}(hjUhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj hhubj)}(hXstatic struct kunit_case example_test_cases[] = { KUNIT_CASE(example_test_foo), KUNIT_CASE(example_test_bar), KUNIT_CASE(example_test_baz), {} }; static struct kunit_suite example_test_suite = { .name = "example", .init = example_test_init, .exit = example_test_exit, .suite_init = example_suite_init, .suite_exit = example_suite_exit, .test_cases = example_test_cases, }; kunit_test_suite(example_test_suite);h]hXstatic struct kunit_case example_test_cases[] = { KUNIT_CASE(example_test_foo), KUNIT_CASE(example_test_bar), KUNIT_CASE(example_test_baz), {} }; static struct kunit_suite example_test_suite = { .name = "example", .init = example_test_init, .exit = example_test_exit, .suite_init = example_suite_init, .suite_exit = example_suite_exit, .test_cases = example_test_cases, }; kunit_test_suite(example_test_suite);}hjcsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhKhj hhubh)}(hXIn the above example, the test suite ``example_test_suite`` would first run ``example_suite_init``, then run the test cases ``example_test_foo``, ``example_test_bar``, and ``example_test_baz``. Each would have ``example_test_init`` called immediately before it and ``example_test_exit`` called immediately after it. Finally, ``example_suite_exit`` would be called after everything else. ``kunit_test_suite(example_test_suite)`` registers the test suite with the KUnit test framework.h](h%In the above example, the test suite }(hjrhhhNhNubh)}(h``example_test_suite``h]hexample_test_suite}(hjzhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh would first run }(hjrhhhNhNubh)}(h``example_suite_init``h]hexample_suite_init}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh, then run the test cases }(hjrhhhNhNubh)}(h``example_test_foo``h]hexample_test_foo}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh, }(hjrhhhNhNubh)}(h``example_test_bar``h]hexample_test_bar}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh, and }(hjrhhhNhNubh)}(h``example_test_baz``h]hexample_test_baz}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh. Each would have }(hjrhhhNhNubh)}(h``example_test_init``h]hexample_test_init}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh" called immediately before it and }(hjrhhhNhNubh)}(h``example_test_exit``h]hexample_test_exit}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh' called immediately after it. Finally, }(hjrhhhNhNubh)}(h``example_suite_exit``h]hexample_suite_exit}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh( would be called after everything else. }(hjrhhhNhNubh)}(h(``kunit_test_suite(example_test_suite)``h]h$kunit_test_suite(example_test_suite)}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh8 registers the test suite with the KUnit test framework.}(hjrhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhj hhubjT)}(hThe ``exit`` and ``suite_exit`` functions will run even if ``init`` or ``suite_init`` fail. Make sure that they can handle any inconsistent state which may result from ``init`` or ``suite_init`` encountering errors or exiting early.h]h)}(hThe ``exit`` and ``suite_exit`` functions will run even if ``init`` or ``suite_init`` fail. Make sure that they can handle any inconsistent state which may result from ``init`` or ``suite_init`` encountering errors or exiting early.h](hThe }(hj&hhhNhNubh)}(h``exit``h]hexit}(hj.hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh and }(hj&hhhNhNubh)}(h``suite_exit``h]h suite_exit}(hj@hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh functions will run even if }(hj&hhhNhNubh)}(h``init``h]hinit}(hjRhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh or }(hj&hhhNhNubh)}(h``suite_init``h]h suite_init}(hjdhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubhS fail. Make sure that they can handle any inconsistent state which may result from }(hj&hhhNhNubh)}(h``init``h]hinit}(hjvhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh or }(hj&hhhNhNubh)}(h``suite_init``h]h suite_init}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh& encountering errors or exiting early.}(hj&hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhj"ubah}(h]h ]h"]h$]h&]uh1jShj hhhhhNubh)}(h``kunit_test_suite(...)`` is a macro which tells the linker to put the specified test suite in a special linker section so that it can be run by KUnit either after ``late_init``, or when the test module is loaded (if the test was built as a module).h](h)}(h``kunit_test_suite(...)``h]hkunit_test_suite(...)}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh is a macro which tells the linker to put the specified test suite in a special linker section so that it can be run by KUnit either after }(hjhhhNhNubh)}(h ``late_init``h]h late_init}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhH, or when the test module is loaded (if the test was built as a module).}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhj hhubh)}(hEFor more information, see Documentation/dev-tools/kunit/api/test.rst.h]hEFor more information, see Documentation/dev-tools/kunit/api/test.rst.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhj hhubhtarget)}(h.. _kunit-on-non-uml:h]h}(h]h ]h"]h$]h&]refidkunit-on-non-umluh1jhKhj hhhhubeh}(h] test-suitesah ]h"] test suitesah$]h&]uh1hhjzhhhhhKubeh}(h]customizing-error-messagesah ]h"]customizing error messagesah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(h%Writing Tests For Other Architecturesh]h%Writing Tests For Other Architectures}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKubh)}(hIt is better to write tests that run on UML to tests that only run under a particular architecture. It is better to write tests that run under QEMU or another easy to obtain (and monetarily free) software environment to a specific piece of hardware.h]hIt is better to write tests that run on UML to tests that only run under a particular architecture. It is better to write tests that run under QEMU or another easy to obtain (and monetarily free) software environment to a specific piece of hardware.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hXNevertheless, there are still valid reasons to write a test that is architecture or hardware specific. For example, we might want to test code that really belongs in ``arch/some-arch/*``. Even so, try to write the test so that it does not depend on physical hardware. Some of our test cases may not need hardware, only few tests actually require the hardware to test it. When hardware is not available, instead of disabling tests, we can skip them.h](hNevertheless, there are still valid reasons to write a test that is architecture or hardware specific. For example, we might want to test code that really belongs in }(hjhhhNhNubh)}(h``arch/some-arch/*``h]harch/some-arch/*}(hj'hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhX. Even so, try to write the test so that it does not depend on physical hardware. Some of our test cases may not need hardware, only few tests actually require the hardware to test it. When hardware is not available, instead of disabling tests, we can skip them.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hNow that we have narrowed down exactly what bits are hardware specific, the actual procedure for writing and running the tests is same as writing normal KUnit tests.h]hNow that we have narrowed down exactly what bits are hardware specific, the actual procedure for writing and running the tests is same as writing normal KUnit tests.}(hj?hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh important)}(hvWe may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation.h]h)}(hvWe may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation.h]hvWe may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation.}(hjShhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjOubah}(h]h ]h"]h$]h&]uh1jMhjhhhhhNubh)}(h`TODO(brendanhiggins@google.com): Add an actual example of an architecture- dependent KUnit test.h]h`TODO(brendanhiggins@google.com): Add an actual example of an architecture- dependent KUnit test.}hjgsbah}(h]h ]h"]h$]h&]hhuh1hhjhhhhhKubeh}(h](%writing-tests-for-other-architecturesjeh ]h"](%writing tests for other architectureskunit-on-non-umleh$]h&]uh1hhhhhhhhKیexpect_referenced_by_name}j{jsexpect_referenced_by_id}jjsubeh}(h] writing-testsah ]h"] writing testsah$]h&]uh1hhhhhhhhKubh)}(hhh](h)}(hCommon Patternsh]hCommon Patterns}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKubh)}(hhh](h)}(hIsolating Behaviorh]hIsolating Behavior}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhKubh)}(hXUnit testing limits the amount of code under test to a single unit. It controls what code gets run when the unit under test calls a function. Where a function is exposed as part of an API such that the definition of that function can be changed without affecting the rest of the code base. In the kernel, this comes from two constructs: classes, which are structs that contain function pointers provided by the implementer, and architecture-specific functions, which have definitions selected at compile time.h]hXUnit testing limits the amount of code under test to a single unit. It controls what code gets run when the unit under test calls a function. Where a function is exposed as part of an API such that the definition of that function can be changed without affecting the rest of the code base. In the kernel, this comes from two constructs: classes, which are structs that contain function pointers provided by the implementer, and architecture-specific functions, which have definitions selected at compile time.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhKhjhhubh)}(hhh](h)}(hClassesh]hClasses}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMubh)}(hX[Classes are not a construct that is built into the C programming language; however, it is an easily derived concept. Accordingly, in most cases, every project that does not use a standardized object oriented library (like GNOME's GObject) has their own slightly different way of doing object oriented programming; the Linux kernel is no exception.h]hX]Classes are not a construct that is built into the C programming language; however, it is an easily derived concept. Accordingly, in most cases, every project that does not use a standardized object oriented library (like GNOME’s GObject) has their own slightly different way of doing object oriented programming; the Linux kernel is no exception.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hX^The central concept in kernel object oriented programming is the class. In the kernel, a *class* is a struct that contains function pointers. This creates a contract between *implementers* and *users* since it forces them to use the same function signature without having to call the function directly. To be a class, the function pointers must specify that a pointer to the class, known as a *class handle*, be one of the parameters. Thus the member functions (also known as *methods*) have access to member variables (also known as *fields*) allowing the same implementation to have multiple *instances*.h](hYThe central concept in kernel object oriented programming is the class. In the kernel, a }(hjhhhNhNubh)}(h*class*h]hclass}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhN is a struct that contains function pointers. This creates a contract between }(hjhhhNhNubh)}(h*implementers*h]h implementers}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh and }(hjhhhNhNubh)}(h*users*h]husers}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh since it forces them to use the same function signature without having to call the function directly. To be a class, the function pointers must specify that a pointer to the class, known as a }(hjhhhNhNubh)}(h*class handle*h]h class handle}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhE, be one of the parameters. Thus the member functions (also known as }(hjhhhNhNubh)}(h *methods*h]hmethods}(hj)hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh1) have access to member variables (also known as }(hjhhhNhNubh)}(h*fields*h]hfields}(hj;hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh4) allowing the same implementation to have multiple }(hjhhhNhNubh)}(h *instances*h]h instances}(hjMhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM hjhhubh)}(hXA class can be *overridden* by *child classes* by embedding the *parent class* in the child class. Then when the child class *method* is called, the child implementation knows that the pointer passed to it is of a parent contained within the child. Thus, the child can compute the pointer to itself because the pointer to the parent is always a fixed offset from the pointer to the child. This offset is the offset of the parent contained in the child struct. For example:h](hA class can be }(hjehhhNhNubh)}(h *overridden*h]h overridden}(hjmhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjeubh by }(hjehhhNhNubh)}(h*child classes*h]h child classes}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjeubh by embedding the }(hjehhhNhNubh)}(h*parent class*h]h parent class}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjeubh/ in the child class. Then when the child class }(hjehhhNhNubh)}(h*method*h]hmethod}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjeubhXS is called, the child implementation knows that the pointer passed to it is of a parent contained within the child. Thus, the child can compute the pointer to itself because the pointer to the parent is always a fixed offset from the pointer to the child. This offset is the offset of the parent contained in the child struct. For example:}(hjehhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(hXstruct shape { int (*area)(struct shape *this); }; struct rectangle { struct shape parent; int length; int width; }; int rectangle_area(struct shape *this) { struct rectangle *self = container_of(this, struct rectangle, parent); return self->length * self->width; }; void rectangle_new(struct rectangle *self, int length, int width) { self->parent.area = rectangle_area; self->length = length; self->width = width; }h]hXstruct shape { int (*area)(struct shape *this); }; struct rectangle { struct shape parent; int length; int width; }; int rectangle_area(struct shape *this) { struct rectangle *self = container_of(this, struct rectangle, parent); return self->length * self->width; }; void rectangle_new(struct rectangle *self, int length, int width) { self->parent.area = rectangle_area; self->length = length; self->width = width; }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubh)}(hoIn this example, computing the pointer to the child from the pointer to the parent is done by ``container_of``.h](h^In this example, computing the pointer to the child from the pointer to the parent is done by }(hjhhhNhNubh)}(h``container_of``h]h container_of}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM6hjhhubeh}(h]classesah ]h"]classesah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(hFaking Classesh]hFaking Classes}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhM:ubh)}(hIn order to unit test a piece of code that calls a method in a class, the behavior of the method must be controllable, otherwise the test ceases to be a unit test and becomes an integration test.h]hIn order to unit test a piece of code that calls a method in a class, the behavior of the method must be controllable, otherwise the test ceases to be a unit test and becomes an integration test.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM<hjhhubh)}(hXtA fake class implements a piece of code that is different than what runs in a production instance, but behaves identical from the standpoint of the callers. This is done to replace a dependency that is hard to deal with, or is slow. For example, implementing a fake EEPROM that stores the "contents" in an internal buffer. Assume we have a class that represents an EEPROM:h]hXxA fake class implements a piece of code that is different than what runs in a production instance, but behaves identical from the standpoint of the callers. This is done to replace a dependency that is hard to deal with, or is slow. For example, implementing a fake EEPROM that stores the “contents” in an internal buffer. Assume we have a class that represents an EEPROM:}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM@hjhhubj)}(hstruct eeprom { ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count); ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count); };h]hstruct eeprom { ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count); ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count); };}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMFhjhhubh)}(h;And we want to test code that buffers writes to the EEPROM:h]h;And we want to test code that buffers writes to the EEPROM:}(hj.hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMMhjhhubj)}(hX_struct eeprom_buffer { ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count); int flush(struct eeprom_buffer *this); size_t flush_count; /* Flushes when buffer exceeds flush_count. */ }; struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom); void destroy_eeprom_buffer(struct eeprom *eeprom);h]hX_struct eeprom_buffer { ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count); int flush(struct eeprom_buffer *this); size_t flush_count; /* Flushes when buffer exceeds flush_count. */ }; struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom); void destroy_eeprom_buffer(struct eeprom *eeprom);}hj<sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMOhjhhubh)}(hcontents + offset, count); return count; } ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(this->contents + offset, buffer, count); return count; } void fake_eeprom_init(struct fake_eeprom *this) { this->parent.read = fake_eeprom_read; this->parent.write = fake_eeprom_write; memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE); }h]hXstruct fake_eeprom { struct eeprom parent; char contents[FAKE_EEPROM_CONTENTS_SIZE]; }; ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(buffer, this->contents + offset, count); return count; } ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(this->contents + offset, buffer, count); return count; } void fake_eeprom_init(struct fake_eeprom *this) { this->parent.read = fake_eeprom_read; this->parent.write = fake_eeprom_write; memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE); }}hjksbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhM\hjhhubh)}(h3We can now use it to test ``struct eeprom_buffer``:h](hWe can now use it to test }(hjzhhhNhNubh)}(h``struct eeprom_buffer``h]hstruct eeprom_buffer}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjzubh:}(hjzhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM~hjhhubj)}(hX struct eeprom_buffer_test { struct fake_eeprom *fake_eeprom; struct eeprom_buffer *eeprom_buffer; }; static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = SIZE_MAX; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0); eeprom_buffer->flush(eeprom_buffer); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff, 0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 2); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); /* Should have only flushed the first two bytes. */ KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0); } static int eeprom_buffer_test_init(struct kunit *test) { struct eeprom_buffer_test *ctx; ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom); fake_eeprom_init(ctx->fake_eeprom); ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer); test->priv = ctx; return 0; } static void eeprom_buffer_test_exit(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; destroy_eeprom_buffer(ctx->eeprom_buffer); }h]hX struct eeprom_buffer_test { struct fake_eeprom *fake_eeprom; struct eeprom_buffer *eeprom_buffer; }; static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = SIZE_MAX; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0); eeprom_buffer->flush(eeprom_buffer); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff, 0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 2); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); /* Should have only flushed the first two bytes. */ KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0); } static int eeprom_buffer_test_init(struct kunit *test) { struct eeprom_buffer_test *ctx; ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom); fake_eeprom_init(ctx->fake_eeprom); ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer); test->priv = ctx; return 0; } static void eeprom_buffer_test_exit(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; destroy_eeprom_buffer(ctx->eeprom_buffer); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubeh}(h]faking-classesah ]h"]faking classesah$]h&]uh1hhjhhhhhM:ubeh}(h]isolating-behaviorah ]h"]isolating behaviorah$]h&]uh1hhjhhhhhKubh)}(hhh](h)}(hTesting Against Multiple Inputsh]hTesting Against Multiple Inputs}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMubh)}(hvTesting just a few inputs is not enough to ensure that the code works correctly, for example: testing a hash function.h]hvTesting just a few inputs is not enough to ensure that the code works correctly, for example: testing a hash function.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hWe can write a helper macro or function. The function is called for each input. For example, to test ``sha1sum(1)``, we can write:h](heWe can write a helper macro or function. The function is called for each input. For example, to test }(hjhhhNhNubh)}(h``sha1sum(1)``h]h sha1sum(1)}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, we can write:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(hX#define TEST_SHA1(in, want) \ sha1sum(in, out); \ KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in); char out[40]; TEST_SHA1("hello world", "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"); TEST_SHA1("hello world!", "430ce34d020724ed75a196dfc2ad67c77772d169");h]hX#define TEST_SHA1(in, want) \ sha1sum(in, out); \ KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in); char out[40]; TEST_SHA1("hello world", "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"); TEST_SHA1("hello world!", "430ce34d020724ed75a196dfc2ad67c77772d169");}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubh)}(hNote the use of the ``_MSG`` version of ``KUNIT_EXPECT_STREQ`` to print a more detailed error and make the assertions clearer within the helper macros.h](hNote the use of the }(hj hhhNhNubh)}(h``_MSG``h]h_MSG}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh version of }(hj hhhNhNubh)}(h``KUNIT_EXPECT_STREQ``h]hKUNIT_EXPECT_STREQ}(hj! hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhY to print a more detailed error and make the assertions clearer within the helper macros.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hThe ``_MSG`` variants are useful when the same expectation is called multiple times (in a loop or helper function) and thus the line number is not enough to identify what failed, as shown below.h](hThe }(hj9 hhhNhNubh)}(h``_MSG``h]h_MSG}(hjA hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj9 ubh variants are useful when the same expectation is called multiple times (in a loop or helper function) and thus the line number is not enough to identify what failed, as shown below.}(hj9 hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hsIn complicated cases, we recommend using a *table-driven test* compared to the helper macro variation, for example:h](h+In complicated cases, we recommend using a }(hjY hhhNhNubh)}(h*table-driven test*h]htable-driven test}(hja hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjY ubh5 compared to the helper macro variation, for example:}(hjY hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(hXMint i; char out[40]; struct sha1_test_case { const char *str; const char *sha1; }; struct sha1_test_case cases[] = { { .str = "hello world", .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", }, { .str = "hello world!", .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169", }, }; for (i = 0; i < ARRAY_SIZE(cases); ++i) { sha1sum(cases[i].str, out); KUNIT_EXPECT_STREQ_MSG(test, out, cases[i].sha1, "sha1sum(%s)", cases[i].str); }h]hXMint i; char out[40]; struct sha1_test_case { const char *str; const char *sha1; }; struct sha1_test_case cases[] = { { .str = "hello world", .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", }, { .str = "hello world!", .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169", }, }; for (i = 0; i < ARRAY_SIZE(cases); ++i) { sha1sum(cases[i].str, out); KUNIT_EXPECT_STREQ_MSG(test, out, cases[i].sha1, "sha1sum(%s)", cases[i].str); }}hjy sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubh)}(h4There is more boilerplate code involved, but it can:h]h4There is more boilerplate code involved, but it can:}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh bullet_list)}(hhh](h list_item)}(h|be more readable when there are multiple inputs/outputs (due to field names). * For example, see ``fs/ext4/inode-test.c``. h](h)}(hMbe more readable when there are multiple inputs/outputs (due to field names).h]hMbe more readable when there are multiple inputs/outputs (due to field names).}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhj ubj )}(hhh]j )}(h+For example, see ``fs/ext4/inode-test.c``. h]h)}(h*For example, see ``fs/ext4/inode-test.c``.h](hFor example, see }(hj hhhNhNubh)}(h``fs/ext4/inode-test.c``h]hfs/ext4/inode-test.c}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj ubah}(h]h ]h"]h$]h&]uh1j hj ubah}(h]h ]h"]h$]h&]bullet*uh1j hhhMhj ubeh}(h]h ]h"]h$]h&]uh1j hj hhhNhNubj )}(hreduce duplication if test cases are shared across multiple tests. * For example: if we want to test ``sha256sum``, we could add a ``sha256`` field and reuse ``cases``. h](h)}(hBreduce duplication if test cases are shared across multiple tests.h]hBreduce duplication if test cases are shared across multiple tests.}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhj ubj )}(hhh]j )}(hdFor example: if we want to test ``sha256sum``, we could add a ``sha256`` field and reuse ``cases``. h]h)}(hcFor example: if we want to test ``sha256sum``, we could add a ``sha256`` field and reuse ``cases``.h](h For example: if we want to test }(hj hhhNhNubh)}(h ``sha256sum``h]h sha256sum}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh, we could add a }(hj hhhNhNubh)}(h ``sha256``h]hsha256}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh field and reuse }(hj hhhNhNubh)}(h ``cases``h]hcases}(hj/ hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj ubah}(h]h ]h"]h$]h&]uh1j hj ubah}(h]h ]h"]h$]h&]j j uh1j hhhMhj ubeh}(h]h ]h"]h$]h&]uh1j hj hhhNhNubj )}(h(be converted to a "parameterized test". h]h)}(h'be converted to a "parameterized test".h]h+be converted to a “parameterized test”.}(hj] hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjY ubah}(h]h ]h"]h$]h&]uh1j hj hhhhhNubeh}(h]h ]h"]h$]h&]j j uh1j hhhMhjhhubh)}(hhh](h)}(hParameterized Testingh]hParameterized Testing}(hjz hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjw hhhhhMubh)}(hXThe table-driven testing pattern is common enough that KUnit has special support for it.h]hXThe table-driven testing pattern is common enough that KUnit has special support for it.}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM!hjw hhubh)}(hsBy reusing the same ``cases`` array from above, we can write the test as a "parameterized test" with the following.h](hBy reusing the same }(hj hhhNhNubh)}(h ``cases``h]hcases}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhZ array from above, we can write the test as a “parameterized test” with the following.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM$hjw hhubj)}(hX0// This is copy-pasted from above. struct sha1_test_case { const char *str; const char *sha1; }; const struct sha1_test_case cases[] = { { .str = "hello world", .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", }, { .str = "hello world!", .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169", }, }; // Creates `sha1_gen_params()` to iterate over `cases` while using // the struct member `str` for the case description. KUNIT_ARRAY_PARAM_DESC(sha1, cases, str); // Looks no different from a normal test. static void sha1_test(struct kunit *test) { // This function can just contain the body of the for-loop. // The former `cases[i]` is accessible under test->param_value. char out[40]; struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value); sha1sum(test_param->str, out); KUNIT_EXPECT_STREQ_MSG(test, out, test_param->sha1, "sha1sum(%s)", test_param->str); } // Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the // function declared by KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC. static struct kunit_case sha1_test_cases[] = { KUNIT_CASE_PARAM(sha1_test, sha1_gen_params), {} };h]hX0// This is copy-pasted from above. struct sha1_test_case { const char *str; const char *sha1; }; const struct sha1_test_case cases[] = { { .str = "hello world", .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", }, { .str = "hello world!", .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169", }, }; // Creates `sha1_gen_params()` to iterate over `cases` while using // the struct member `str` for the case description. KUNIT_ARRAY_PARAM_DESC(sha1, cases, str); // Looks no different from a normal test. static void sha1_test(struct kunit *test) { // This function can just contain the body of the for-loop. // The former `cases[i]` is accessible under test->param_value. char out[40]; struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value); sha1sum(test_param->str, out); KUNIT_EXPECT_STREQ_MSG(test, out, test_param->sha1, "sha1sum(%s)", test_param->str); } // Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the // function declared by KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC. static struct kunit_case sha1_test_cases[] = { KUNIT_CASE_PARAM(sha1_test, sha1_gen_params), {} };}hj sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhM'hjw hhubeh}(h]parameterized-testingah ]h"]parameterized testingah$]h&]uh1hhjhhhhhMubeh}(h]testing-against-multiple-inputsah ]h"]testing against multiple inputsah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(hAllocating Memoryh]hAllocating Memory}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj hhhhhMRubh)}(hWhere you might use ``kzalloc``, you can instead use ``kunit_kzalloc`` as KUnit will then ensure that the memory is freed once the test completes.h](hWhere you might use }(hj hhhNhNubh)}(h ``kzalloc``h]hkzalloc}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh, you can instead use }(hj hhhNhNubh)}(h``kunit_kzalloc``h]h kunit_kzalloc}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhL as KUnit will then ensure that the memory is freed once the test completes.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMThj hhubh)}(hThis is useful because it lets us use the ``KUNIT_ASSERT_EQ`` macros to exit early from a test without having to worry about remembering to call ``kfree``. For example:h](h*This is useful because it lets us use the }(hj hhhNhNubh)}(h``KUNIT_ASSERT_EQ``h]hKUNIT_ASSERT_EQ}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhT macros to exit early from a test without having to worry about remembering to call }(hj hhhNhNubh)}(h ``kfree``h]hkfree}(hj2 hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh. For example:}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMWhj hhubj)}(hvoid example_test_allocation(struct kunit *test) { char *buffer = kunit_kzalloc(test, 16, GFP_KERNEL); /* Ensure allocation succeeded. */ KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buffer); KUNIT_ASSERT_STREQ(test, buffer, ""); }h]hvoid example_test_allocation(struct kunit *test) { char *buffer = kunit_kzalloc(test, 16, GFP_KERNEL); /* Ensure allocation succeeded. */ KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buffer); KUNIT_ASSERT_STREQ(test, buffer, ""); }}hjJ sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhM[hj hhubeh}(h]allocating-memoryah ]h"]allocating memoryah$]h&]uh1hhjhhhhhMRubh)}(hhh](h)}(hRegistering Cleanup Actionsh]hRegistering Cleanup Actions}(hjd hhhNhNubah}(h]h ]h"]h$]h&]uh1hhja hhhhhMgubh)}(hIf you need to perform some cleanup beyond simple use of ``kunit_kzalloc``, you can register a custom "deferred action", which is a cleanup function run when the test exits (whether cleanly, or via a failed assertion).h](h9If you need to perform some cleanup beyond simple use of }(hjr hhhNhNubh)}(h``kunit_kzalloc``h]h kunit_kzalloc}(hjz hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjr ubh, you can register a custom “deferred action”, which is a cleanup function run when the test exits (whether cleanly, or via a failed assertion).}(hjr hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMihja hhubh)}(hX Actions are simple functions with no return value, and a single ``void*`` context argument, and fulfill the same role as "cleanup" functions in Python and Go tests, "defer" statements in languages which support them, and (in some cases) destructors in RAII languages.h](h@Actions are simple functions with no return value, and a single }(hj hhhNhNubh)}(h ``void*``h]hvoid*}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh context argument, and fulfill the same role as “cleanup” functions in Python and Go tests, “defer” statements in languages which support them, and (in some cases) destructors in RAII languages.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMmhja hhubh)}(hyThese are very useful for unregistering things from global lists, closing files or other resources, or freeing resources.umh]hyThese are very useful for unregistering things from global lists, closing files or other resources, or freeing resources.}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMrhja hhubh)}(h For example:h]h For example:}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMuhja hhubj)}(hX%static void cleanup_device(void *ctx) { struct device *dev = (struct device *)ctx; device_unregister(dev); } void example_device_test(struct kunit *test) { struct my_device dev; device_register(&dev); kunit_add_action(test, &cleanup_device, &dev); }h]hX%static void cleanup_device(void *ctx) { struct device *dev = (struct device *)ctx; device_unregister(dev); } void example_device_test(struct kunit *test) { struct my_device dev; device_register(&dev); kunit_add_action(test, &cleanup_device, &dev); }}hj sbah}(h]h ]h"]h$]h&]hhj"j#Cj%}uh1jhhhMwhja hhubh)}(hNote that, for functions like device_unregister which only accept a single pointer-sized argument, it's possible to automatically generate a wrapper with the ``KUNIT_DEFINE_ACTION_WRAPPER()`` macro, for example:h](hNote that, for functions like device_unregister which only accept a single pointer-sized argument, it’s possible to automatically generate a wrapper with the }(hj hhhNhNubh)}(h!``KUNIT_DEFINE_ACTION_WRAPPER()``h]hKUNIT_DEFINE_ACTION_WRAPPER()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh macro, for example:}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhja hhubj)}(hKUNIT_DEFINE_ACTION_WRAPPER(device_unregister, device_unregister_wrapper, struct device *); kunit_add_action(test, &device_unregister_wrapper, &dev);h]hKUNIT_DEFINE_ACTION_WRAPPER(device_unregister, device_unregister_wrapper, struct device *); kunit_add_action(test, &device_unregister_wrapper, &dev);}hj sbah}(h]h ]h"]h$]h&]hhj"j#j j%}uh1jhhhMhja hhubh)}(hYou should do this in preference to manually casting to the ``kunit_action_t`` type, as casting function pointers will break Control Flow Integrity (CFI).h](h /* for kunit_get_current_test */ struct test_data { int foo_result; int want_foo_called_with; }; static int fake_foo(int arg) { struct kunit *test = kunit_get_current_test(); struct test_data *test_data = test->priv; KUNIT_EXPECT_EQ(test, test_data->want_foo_called_with, arg); return test_data->foo_result; } static void example_simple_test(struct kunit *test) { /* Assume priv (private, a member used to pass test data from * the init function) is allocated in the suite's .init */ struct test_data *test_data = test->priv; test_data->foo_result = 42; test_data->want_foo_called_with = 1; /* In a real test, we'd probably pass a pointer to fake_foo somewhere * like an ops struct, etc. instead of calling it directly. */ KUNIT_EXPECT_EQ(test, fake_foo(1), 42); }h]hX#include /* for kunit_get_current_test */ struct test_data { int foo_result; int want_foo_called_with; }; static int fake_foo(int arg) { struct kunit *test = kunit_get_current_test(); struct test_data *test_data = test->priv; KUNIT_EXPECT_EQ(test, test_data->want_foo_called_with, arg); return test_data->foo_result; } static void example_simple_test(struct kunit *test) { /* Assume priv (private, a member used to pass test data from * the init function) is allocated in the suite's .init */ struct test_data *test_data = test->priv; test_data->foo_result = 42; test_data->want_foo_called_with = 1; /* In a real test, we'd probably pass a pointer to fake_foo somewhere * like an ops struct, etc. instead of calling it directly. */ KUNIT_EXPECT_EQ(test, fake_foo(1), 42); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjb hhubh)}(hXIn this example, we are using the ``priv`` member of ``struct kunit`` as a way of passing data to the test from the init function. In general ``priv`` is pointer that can be used for any user data. This is preferred over static variables, as it avoids concurrency issues.h](h"In this example, we are using the }(hj&hhhNhNubh)}(h``priv``h]hpriv}(hj.hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubh member of }(hj&hhhNhNubh)}(h``struct kunit``h]h struct kunit}(hj@hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubhI as a way of passing data to the test from the init function. In general }(hj&hhhNhNubh)}(h``priv``h]hpriv}(hjRhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj&ubhy is pointer that can be used for any user data. This is preferred over static variables, as it avoids concurrency issues.}(hj&hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjb hhubh)}(hXHad we wanted something more flexible, we could have used a named ``kunit_resource``. Each test can have multiple resources which have string names providing the same flexibility as a ``priv`` member, but also, for example, allowing helper functions to create resources without conflicting with each other. It is also possible to define a clean up function for each resource, making it easy to avoid resource leaks. For more information, see Documentation/dev-tools/kunit/api/resource.rst.h](hBHad we wanted something more flexible, we could have used a named }(hjjhhhNhNubh)}(h``kunit_resource``h]hkunit_resource}(hjrhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjjubhd. Each test can have multiple resources which have string names providing the same flexibility as a }(hjjhhhNhNubh)}(h``priv``h]hpriv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjjubhX) member, but also, for example, allowing helper functions to create resources without conflicting with each other. It is also possible to define a clean up function for each resource, making it easy to avoid resource leaks. For more information, see Documentation/dev-tools/kunit/api/resource.rst.}(hjjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjb hhubeh}(h]accessing-the-current-testah ]h"]accessing the current testah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(hFailing The Current Testh]hFailing The Current Test}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMubh)}(hX!If we want to fail the current test, we can use ``kunit_fail_current_test(fmt, args...)`` which is defined in ```` and does not require pulling in ````. For example, we have an option to enable some extra debug checks on some data structures as shown below:h](h0If we want to fail the current test, we can use }(hjhhhNhNubh)}(h)``kunit_fail_current_test(fmt, args...)``h]h%kunit_fail_current_test(fmt, args...)}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh which is defined in }(hjhhhNhNubh)}(h````h]h}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh! and does not require pulling in }(hjhhhNhNubh)}(h````h]h}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhj. For example, we have an option to enable some extra debug checks on some data structures as shown below:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(hXU#include #ifdef CONFIG_EXTRA_DEBUG_CHECKS static void validate_my_data(struct data *data) { if (is_valid(data)) return; kunit_fail_current_test("data %p is invalid", data); /* Normal, non-KUnit, error reporting code here. */ } #else static void my_debug_function(void) { } #endifh]hXU#include #ifdef CONFIG_EXTRA_DEBUG_CHECKS static void validate_my_data(struct data *data) { if (is_valid(data)) return; kunit_fail_current_test("data %p is invalid", data); /* Normal, non-KUnit, error reporting code here. */ } #else static void my_debug_function(void) { } #endif}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubh)}(hX(``kunit_fail_current_test()`` is safe to call even if KUnit is not enabled. If KUnit is not enabled, or if no test is running in the current task, it will do nothing. This compiles down to either a no-op or a static key check, so will have a negligible performance impact when no test is running.h](h)}(h``kunit_fail_current_test()``h]hkunit_fail_current_test()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhX  is safe to call even if KUnit is not enabled. If KUnit is not enabled, or if no test is running in the current task, it will do nothing. This compiles down to either a no-op or a static key check, so will have a negligible performance impact when no test is running.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM'hjhhubeh}(h]failing-the-current-testah ]h"]failing the current testah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(h!Managing Fake Devices and Driversh]h!Managing Fake Devices and Drivers}(hj/hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj,hhhhhM-ubh)}(hXWhen testing drivers or code which interacts with drivers, many functions will require a ``struct device`` or ``struct device_driver``. In many cases, setting up a real device is not required to test any given function, so a fake device can be used instead.h](hYWhen testing drivers or code which interacts with drivers, many functions will require a }(hj=hhhNhNubh)}(h``struct device``h]h struct device}(hjEhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj=ubh or }(hj=hhhNhNubh)}(h``struct device_driver``h]hstruct device_driver}(hjWhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj=ubh{. In many cases, setting up a real device is not required to test any given function, so a fake device can be used instead.}(hj=hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM/hj,hhubh)}(hX%KUnit provides helper functions to create and manage these fake devices, which are internally of type ``struct kunit_device``, and are attached to a special ``kunit_bus``. These devices support managed device resources (devres), as described in Documentation/driver-api/driver-model/devres.rsth](hfKUnit provides helper functions to create and manage these fake devices, which are internally of type }(hjohhhNhNubh)}(h``struct kunit_device``h]hstruct kunit_device}(hjwhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjoubh , and are attached to a special }(hjohhhNhNubh)}(h ``kunit_bus``h]h kunit_bus}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjoubh{. These devices support managed device resources (devres), as described in Documentation/driver-api/driver-model/devres.rst}(hjohhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM4hj,hhubh)}(hX+To create a KUnit-managed ``struct device_driver``, use ``kunit_driver_create()``, which will create a driver with the given name, on the ``kunit_bus``. This driver will automatically be destroyed when the corresponding test finishes, but can also be manually destroyed with ``driver_unregister()``.h](hTo create a KUnit-managed }(hjhhhNhNubh)}(h``struct device_driver``h]hstruct device_driver}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, use }(hjhhhNhNubh)}(h``kunit_driver_create()``h]hkunit_driver_create()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh9, which will create a driver with the given name, on the }(hjhhhNhNubh)}(h ``kunit_bus``h]h kunit_bus}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh|. This driver will automatically be destroyed when the corresponding test finishes, but can also be manually destroyed with }(hjhhhNhNubh)}(h``driver_unregister()``h]hdriver_unregister()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM9hj,hhubh)}(hXTo create a fake device, use the ``kunit_device_register()``, which will create and register a device, using a new KUnit-managed driver created with ``kunit_driver_create()``. To provide a specific, non-KUnit-managed driver, use ``kunit_device_register_with_driver()`` instead. Like with managed drivers, KUnit-managed fake devices are automatically cleaned up when the test finishes, but can be manually cleaned up early with ``kunit_device_unregister()``.h](h!To create a fake device, use the }(hjhhhNhNubh)}(h``kunit_device_register()``h]hkunit_device_register()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhY, which will create and register a device, using a new KUnit-managed driver created with }(hjhhhNhNubh)}(h``kunit_driver_create()``h]hkunit_driver_create()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh7. To provide a specific, non-KUnit-managed driver, use }(hjhhhNhNubh)}(h'``kunit_device_register_with_driver()``h]h#kunit_device_register_with_driver()}(hj#hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh instead. Like with managed drivers, KUnit-managed fake devices are automatically cleaned up when the test finishes, but can be manually cleaned up early with }(hjhhhNhNubh)}(h``kunit_device_unregister()``h]hkunit_device_unregister()}(hj5hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM>hj,hhubh)}(hThe KUnit devices should be used in preference to ``root_device_register()``, and instead of ``platform_device_register()`` in cases where the device is not otherwise a platform device.h](h2The KUnit devices should be used in preference to }(hjMhhhNhNubh)}(h``root_device_register()``h]hroot_device_register()}(hjUhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjMubh, and instead of }(hjMhhhNhNubh)}(h``platform_device_register()``h]hplatform_device_register()}(hjghhhNhNubah}(h]h ]h"]h$]h&]uh1hhjMubh> in cases where the device is not otherwise a platform device.}(hjMhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMEhj,hhubh)}(h For example:h]h For example:}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMIhj,hhubj)}(hX#include static void test_my_device(struct kunit *test) { struct device *fake_device; const char *dev_managed_string; // Create a fake device. fake_device = kunit_device_register(test, "my_device"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fake_device) // Pass it to functions which need a device. dev_managed_string = devm_kstrdup(fake_device, "Hello, World!"); // Everything is cleaned up automatically when the test ends. }h]hX#include static void test_my_device(struct kunit *test) { struct device *fake_device; const char *dev_managed_string; // Create a fake device. fake_device = kunit_device_register(test, "my_device"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fake_device) // Pass it to functions which need a device. dev_managed_string = devm_kstrdup(fake_device, "Hello, World!"); // Everything is cleaned up automatically when the test ends. }}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMKhj,hhubeh}(h]!managing-fake-devices-and-driversah ]h"]!managing fake devices and driversah$]h&]uh1hhjhhhhhM-ubeh}(h]common-patternsah ]h"]common patternsah$]h&]uh1hhhhhhhhKubeh}(h]h ]h"]h$]h&]sourcehuh1hcurrent_sourceN current_lineNsettingsdocutils.frontendValues)}(hN generatorN datestampN source_linkN source_urlN toc_backlinksentryfootnote_backlinksK sectnum_xformKstrip_commentsNstrip_elements_with_classesN strip_classesN report_levelK halt_levelKexit_status_levelKdebugNwarning_streamN tracebackinput_encoding utf-8-siginput_encoding_error_handlerstrictoutput_encodingutf-8output_encoding_error_handlerjerror_encodingutf-8error_encoding_error_handlerbackslashreplace language_codeenrecord_dependenciesNconfigN id_prefixhauto_id_prefixid dump_settingsNdump_internalsNdump_transformsNdump_pseudo_xmlNexpose_internalsNstrict_visitorN_disable_configN_sourceh _destinationN _config_files]7/var/lib/git/docbuild/linux/Documentation/docutils.confafile_insertion_enabled raw_enabledKline_length_limitM'pep_referencesN pep_base_urlhttps://peps.python.org/pep_file_url_templatepep-%04drfc_referencesN rfc_base_url&https://datatracker.ietf.org/doc/html/ tab_widthKtrim_footnote_reference_spacesyntax_highlightlong smart_quotessmartquotes_locales]character_level_inline_markupdoctitle_xform docinfo_xformKsectsubtitle_xform image_loadinglinkembed_stylesheetcloak_email_addressessection_self_linkenvNubreporterNindirect_targets]substitution_defs}substitution_names}refnames}refids}j]jasnameids}(jjjwjtjjjojljjjjj{jjzjwjjjjjjjjj j j j j^ j[ j j j j j_ j\ jjj)j&jju nametypes}(jjwjjojjj{jzjjjjj j j^ j j j_ jj)juh}(jhjthjjkjljjjzjj jjjwjjjjjjjjjj jj jw j[ j j ja j j j\ j jjb j&jjj,u footnote_refs} citation_refs} autofootnotes]autofootnote_refs]symbol_footnotes]symbol_footnote_refs] footnotes] citations]autofootnote_startKsymbol_footnote_startK id_counter collectionsCounter}Rparse_messages]transform_messages]hsystem_message)}(hhh]h)}(hhh]h6Hyperlink target "kunit-on-non-uml" is not referenced.}hj9sbah}(h]h ]h"]h$]h&]uh1hhj6ubah}(h]h ]h"]h$]h&]levelKtypeINFOsourcehlineKuh1j4uba transformerN include_log] decorationNhhub.