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)}(hTo run a test case against multiple inputs, KUnit provides a parameterized testing framework. This feature formalizes and extends the concept of table-driven tests discussed previously.h]hTo run a test case against multiple inputs, KUnit provides a parameterized testing framework. This feature formalizes and extends the concept of table-driven tests discussed previously.}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM!hjw hhubh)}(hXaA KUnit test is determined to be parameterized if a parameter generator function is provided when registering the test case. A test user can either write their own generator function or use one that is provided by KUnit. The generator function is stored in ``kunit_case->generate_params`` and can be set using the macros described in the section below.h](hXA KUnit test is determined to be parameterized if a parameter generator function is provided when registering the test case. A test user can either write their own generator function or use one that is provided by KUnit. The generator function is stored in }(hj hhhNhNubh)}(h``kunit_case->generate_params``h]hkunit_case->generate_params}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh@ and can be set using the macros described in the section below.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM%hjw hhubh)}(hX7To establish the terminology, a "parameterized test" is a test which is run multiple times (once per "parameter" or "parameter run"). Each parameter run has both its own independent ``struct kunit`` (the "parameter run context") and access to a shared parent ``struct kunit`` (the "parameterized test context").h](hTo establish the terminology, a “parameterized test” is a test which is run multiple times (once per “parameter” or “parameter run”). Each parameter run has both its own independent }(hj hhhNhNubh)}(h``struct kunit``h]h struct kunit}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhA (the “parameter run context”) and access to a shared parent }(hj hhhNhNubh)}(h``struct kunit``h]h struct kunit}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh( (the “parameterized test context”).}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM+hjw hhubh)}(hhh](h)}(hPassing Parameters to a Testh]hPassing Parameters to a Test}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj hhhhhM1ubh)}(h9There are three ways to provide the parameters to a test:h]h9There are three ways to provide the parameters to a test:}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM2hj hhubh)}(hArray Parameter Macros:h]hArray Parameter Macros:}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM4hj hhubh block_quote)}(hKUnit provides special support for the common table-driven testing pattern. By applying either ``KUNIT_ARRAY_PARAM`` or ``KUNIT_ARRAY_PARAM_DESC`` to the ``cases`` array from the previous section, we can create a parameterized test as shown below: h]h)}(hKUnit provides special support for the common table-driven testing pattern. By applying either ``KUNIT_ARRAY_PARAM`` or ``KUNIT_ARRAY_PARAM_DESC`` to the ``cases`` array from the previous section, we can create a parameterized test as shown below:h](h_KUnit provides special support for the common table-driven testing pattern. By applying either }(hj hhhNhNubh)}(h``KUNIT_ARRAY_PARAM``h]hKUNIT_ARRAY_PARAM}(hj# hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh or }(hj hhhNhNubh)}(h``KUNIT_ARRAY_PARAM_DESC``h]hKUNIT_ARRAY_PARAM_DESC}(hj5 hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh to the }(hj hhhNhNubh)}(h ``cases``h]hcases}(hjG hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhT array from the previous section, we can create a parameterized test as shown below:}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM6hj ubah}(h]h ]h"]h$]h&]uh1j hhhM6hj hhubj)}(hX7// This is copy-pasted from above. struct sha1_test_case { const char *str; const char *sha1; }; static 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]hX7// This is copy-pasted from above. struct sha1_test_case { const char *str; const char *sha1; }; static 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), {} };}hje sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhM;hj hhubh)}(h$Custom Parameter Generator Function:h]h$Custom Parameter Generator Function:}(hjt hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMehj hhubj )}(hXThe generator function is responsible for generating parameters one-by-one and has the following signature: ``const void* (*)(struct kunit *test, const void *prev, char *desc)``. You can pass the generator function to the ``KUNIT_CASE_PARAM`` or ``KUNIT_CASE_PARAM_WITH_INIT`` macros. The function receives the previously generated parameter as the ``prev`` argument (which is ``NULL`` on the first call) and can also access the parameterized test context passed as the ``test`` argument. KUnit calls this function repeatedly until it returns ``NULL``, which signifies that a parameterized test ended. Below is an example of how it works: Sh](h)}(hXThe generator function is responsible for generating parameters one-by-one and has the following signature: ``const void* (*)(struct kunit *test, const void *prev, char *desc)``. You can pass the generator function to the ``KUNIT_CASE_PARAM`` or ``KUNIT_CASE_PARAM_WITH_INIT`` macros.h](hlThe generator function is responsible for generating parameters one-by-one and has the following signature: }(hj hhhNhNubh)}(hE``const void* (*)(struct kunit *test, const void *prev, char *desc)``h]hAconst void* (*)(struct kunit *test, const void *prev, char *desc)}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh-. You can pass the generator function to the }(hj hhhNhNubh)}(h``KUNIT_CASE_PARAM``h]hKUNIT_CASE_PARAM}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh or }(hj hhhNhNubh)}(h``KUNIT_CASE_PARAM_WITH_INIT``h]hKUNIT_CASE_PARAM_WITH_INIT}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh macros.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMghj ubh)}(hX<The function receives the previously generated parameter as the ``prev`` argument (which is ``NULL`` on the first call) and can also access the parameterized test context passed as the ``test`` argument. KUnit calls this function repeatedly until it returns ``NULL``, which signifies that a parameterized test ended.h](h@The function receives the previously generated parameter as the }(hj hhhNhNubh)}(h``prev``h]hprev}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh argument (which is }(hj hhhNhNubh)}(h``NULL``h]hNULL}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhU on the first call) and can also access the parameterized test context passed as the }(hj hhhNhNubh)}(h``test``h]htest}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhA argument. KUnit calls this function repeatedly until it returns }(hj hhhNhNubh)}(h``NULL``h]hNULL}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh2, which signifies that a parameterized test ended.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMmhj ubh)}(h$Below is an example of how it works:h]h$Below is an example of how it works:}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMshj ubeh}(h]h ]h"]h$]h&]uh1j hhhMghj hhubj)}(hX9#define MAX_TEST_BUFFER_SIZE 8 // Example generator function. It produces a sequence of buffer sizes that // are powers of two, starting at 1 (e.g., 1, 2, 4, 8). static const void *buffer_size_gen_params(struct kunit *test, const void *prev, char *desc) { long prev_buffer_size = (long)prev; long next_buffer_size = 1; // Start with an initial size of 1. // Stop generating parameters if the limit is reached or exceeded. if (prev_buffer_size >= MAX_TEST_BUFFER_SIZE) return NULL; // For subsequent calls, calculate the next size by doubling the previous one. if (prev) next_buffer_size = prev_buffer_size << 1; return (void *)next_buffer_size; } // Simple test to validate that kunit_kzalloc provides zeroed memory. static void buffer_zero_test(struct kunit *test) { long buffer_size = (long)test->param_value; // Use kunit_kzalloc to allocate a zero-initialized buffer. This makes the // memory "parameter run managed," meaning it's automatically cleaned up at // the end of each parameter run. int *buf = kunit_kzalloc(test, buffer_size * sizeof(int), GFP_KERNEL); // Ensure the allocation was successful. KUNIT_ASSERT_NOT_NULL(test, buf); // Loop through the buffer and confirm every element is zero. for (int i = 0; i < buffer_size; i++) KUNIT_EXPECT_EQ(test, buf[i], 0); } static struct kunit_case buffer_test_cases[] = { KUNIT_CASE_PARAM(buffer_zero_test, buffer_size_gen_params), {} };h]hX9#define MAX_TEST_BUFFER_SIZE 8 // Example generator function. It produces a sequence of buffer sizes that // are powers of two, starting at 1 (e.g., 1, 2, 4, 8). static const void *buffer_size_gen_params(struct kunit *test, const void *prev, char *desc) { long prev_buffer_size = (long)prev; long next_buffer_size = 1; // Start with an initial size of 1. // Stop generating parameters if the limit is reached or exceeded. if (prev_buffer_size >= MAX_TEST_BUFFER_SIZE) return NULL; // For subsequent calls, calculate the next size by doubling the previous one. if (prev) next_buffer_size = prev_buffer_size << 1; return (void *)next_buffer_size; } // Simple test to validate that kunit_kzalloc provides zeroed memory. static void buffer_zero_test(struct kunit *test) { long buffer_size = (long)test->param_value; // Use kunit_kzalloc to allocate a zero-initialized buffer. This makes the // memory "parameter run managed," meaning it's automatically cleaned up at // the end of each parameter run. int *buf = kunit_kzalloc(test, buffer_size * sizeof(int), GFP_KERNEL); // Ensure the allocation was successful. KUNIT_ASSERT_NOT_NULL(test, buf); // Loop through the buffer and confirm every element is zero. for (int i = 0; i < buffer_size; i++) KUNIT_EXPECT_EQ(test, buf[i], 0); } static struct kunit_case buffer_test_cases[] = { KUNIT_CASE_PARAM(buffer_zero_test, buffer_size_gen_params), {} };}hj4 sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMuhj hhubh)}(h:Runtime Parameter Array Registration in the Init Function:h]h:Runtime Parameter Array Registration in the Init Function:}(hjC hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhj hhubj )}(hXFor scenarios where you might need to initialize a parameterized test, you can directly register a parameter array to the parameterized test context. To do this, you must pass the parameterized test context, the array itself, the array size, and a ``get_description()`` function to the ``kunit_register_params_array()`` macro. This macro populates ``struct kunit_params`` within the parameterized test context, effectively storing a parameter array object. The ``get_description()`` function will be used for populating parameter descriptions and has the following signature: ``void (*)(struct kunit *test, const void *param, char *desc)``. Note that it also has access to the parameterized test context. .. important:: When using this way to register a parameter array, you will need to manually pass ``kunit_array_gen_params()`` as the generator function to ``KUNIT_CASE_PARAM_WITH_INIT``. ``kunit_array_gen_params()`` is a KUnit helper that will use the registered array to generate the parameters. If needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use ``test->params_array.params``. The ``kunit_register_params_array()`` macro should be called within a ``param_init()`` function that initializes the parameterized test and has the following signature ``int (*)(struct kunit *test)``. For a detailed explanation of this mechanism please refer to the "Adding Shared Resources" section that is after this one. This method supports registering both dynamically built and static parameter arrays. The code snippet below shows the ``example_param_init_dynamic_arr`` test that utilizes ``make_fibonacci_params()`` to create a dynamic array, which is then registered using ``kunit_register_params_array()``. To see the full code please refer to lib/kunit/kunit-example-test.c. h](h)}(hFor scenarios where you might need to initialize a parameterized test, you can directly register a parameter array to the parameterized test context.h]hFor scenarios where you might need to initialize a parameterized test, you can directly register a parameter array to the parameterized test context.}(hjU hhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjQ ubh)}(hX*To do this, you must pass the parameterized test context, the array itself, the array size, and a ``get_description()`` function to the ``kunit_register_params_array()`` macro. This macro populates ``struct kunit_params`` within the parameterized test context, effectively storing a parameter array object. The ``get_description()`` function will be used for populating parameter descriptions and has the following signature: ``void (*)(struct kunit *test, const void *param, char *desc)``. Note that it also has access to the parameterized test context.h](hbTo do this, you must pass the parameterized test context, the array itself, the array size, and a }(hjc hhhNhNubh)}(h``get_description()``h]hget_description()}(hjk hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjc ubh function to the }(hjc hhhNhNubh)}(h!``kunit_register_params_array()``h]hkunit_register_params_array()}(hj} hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjc ubh macro. This macro populates }(hjc hhhNhNubh)}(h``struct kunit_params``h]hstruct kunit_params}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjc ubhZ within the parameterized test context, effectively storing a parameter array object. The }(hjc hhhNhNubh)}(h``get_description()``h]hget_description()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjc ubh^ function will be used for populating parameter descriptions and has the following signature: }(hjc hhhNhNubh)}(h?``void (*)(struct kunit *test, const void *param, char *desc)``h]h;void (*)(struct kunit *test, const void *param, char *desc)}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjc ubhA. Note that it also has access to the parameterized test context.}(hjc hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjQ ubj )}(hX8.. important:: When using this way to register a parameter array, you will need to manually pass ``kunit_array_gen_params()`` as the generator function to ``KUNIT_CASE_PARAM_WITH_INIT``. ``kunit_array_gen_params()`` is a KUnit helper that will use the registered array to generate the parameters. If needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use ``test->params_array.params``. h]jN)}(hXWhen using this way to register a parameter array, you will need to manually pass ``kunit_array_gen_params()`` as the generator function to ``KUNIT_CASE_PARAM_WITH_INIT``. ``kunit_array_gen_params()`` is a KUnit helper that will use the registered array to generate the parameters. If needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use ``test->params_array.params``.h](h)}(hXWhen using this way to register a parameter array, you will need to manually pass ``kunit_array_gen_params()`` as the generator function to ``KUNIT_CASE_PARAM_WITH_INIT``. ``kunit_array_gen_params()`` is a KUnit helper that will use the registered array to generate the parameters.h](hRWhen using this way to register a parameter array, you will need to manually pass }(hj hhhNhNubh)}(h``kunit_array_gen_params()``h]hkunit_array_gen_params()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh as the generator function to }(hj hhhNhNubh)}(h``KUNIT_CASE_PARAM_WITH_INIT``h]hKUNIT_CASE_PARAM_WITH_INIT}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh. }(hj hhhNhNubh)}(h``kunit_array_gen_params()``h]hkunit_array_gen_params()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhQ is a KUnit helper that will use the registered array to generate the parameters.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj ubh)}(hIf needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use ``test->params_array.params``.h](hIf needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use }(hj hhhNhNubh)}(h``test->params_array.params``h]htest->params_array.params}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj ubeh}(h]h ]h"]h$]h&]uh1jMhj ubah}(h]h ]h"]h$]h&]uh1j hhhMhjQ ubh)}(hXThe ``kunit_register_params_array()`` macro should be called within a ``param_init()`` function that initializes the parameterized test and has the following signature ``int (*)(struct kunit *test)``. For a detailed explanation of this mechanism please refer to the "Adding Shared Resources" section that is after this one. This method supports registering both dynamically built and static parameter arrays.h](hThe }(hjC hhhNhNubh)}(h!``kunit_register_params_array()``h]hkunit_register_params_array()}(hjK hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjC ubh! macro should be called within a }(hjC hhhNhNubh)}(h``param_init()``h]h param_init()}(hj] hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjC ubhR function that initializes the parameterized test and has the following signature }(hjC hhhNhNubh)}(h``int (*)(struct kunit *test)``h]hint (*)(struct kunit *test)}(hjo hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjC ubh. For a detailed explanation of this mechanism please refer to the “Adding Shared Resources” section that is after this one. This method supports registering both dynamically built and static parameter arrays.}(hjC hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjQ ubh)}(hXThe code snippet below shows the ``example_param_init_dynamic_arr`` test that utilizes ``make_fibonacci_params()`` to create a dynamic array, which is then registered using ``kunit_register_params_array()``. To see the full code please refer to lib/kunit/kunit-example-test.c.h](h!The code snippet below shows the }(hj hhhNhNubh)}(h"``example_param_init_dynamic_arr``h]hexample_param_init_dynamic_arr}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh test that utilizes }(hj hhhNhNubh)}(h``make_fibonacci_params()``h]hmake_fibonacci_params()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh; to create a dynamic array, which is then registered using }(hj hhhNhNubh)}(h!``kunit_register_params_array()``h]hkunit_register_params_array()}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubhF. To see the full code please refer to lib/kunit/kunit-example-test.c.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjQ ubeh}(h]h ]h"]h$]h&]uh1j hhhMhj hhubj)}(hX/* * Example of a parameterized test param_init() function that registers a dynamic * array of parameters. */ static int example_param_init_dynamic_arr(struct kunit *test) { size_t seq_size; int *fibonacci_params; kunit_info(test, "initializing parameterized test\n"); seq_size = 6; fibonacci_params = make_fibonacci_params(test, seq_size); if (!fibonacci_params) return -ENOMEM; /* * Passes the dynamic parameter array information to the parameterized test * context struct kunit. The array and its metadata will be stored in * test->parent->params_array. The array itself will be located in * params_data.params. */ kunit_register_params_array(test, fibonacci_params, seq_size, example_param_dynamic_arr_get_desc); return 0; } static struct kunit_case example_test_cases[] = { /* * Note how we pass kunit_array_gen_params() to use the array we * registered in example_param_init_dynamic_arr() to generate * parameters. */ KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr, kunit_array_gen_params, example_param_init_dynamic_arr, example_param_exit_dynamic_arr), {} };h]hX/* * Example of a parameterized test param_init() function that registers a dynamic * array of parameters. */ static int example_param_init_dynamic_arr(struct kunit *test) { size_t seq_size; int *fibonacci_params; kunit_info(test, "initializing parameterized test\n"); seq_size = 6; fibonacci_params = make_fibonacci_params(test, seq_size); if (!fibonacci_params) return -ENOMEM; /* * Passes the dynamic parameter array information to the parameterized test * context struct kunit. The array and its metadata will be stored in * test->parent->params_array. The array itself will be located in * params_data.params. */ kunit_register_params_array(test, fibonacci_params, seq_size, example_param_dynamic_arr_get_desc); return 0; } static struct kunit_case example_test_cases[] = { /* * Note how we pass kunit_array_gen_params() to use the array we * registered in example_param_init_dynamic_arr() to generate * parameters. */ KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr, kunit_array_gen_params, example_param_init_dynamic_arr, example_param_exit_dynamic_arr), {} };}hj sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhj hhubeh}(h]passing-parameters-to-a-testah ]h"]passing parameters to a testah$]h&]uh1hhjw hhhhhM1ubh)}(hhh](h)}(hAdding Shared Resourcesh]hAdding Shared Resources}(hj hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj hhhhhMubh)}(hXAll parameter runs in this framework hold a reference to the parameterized test context, which can be accessed using the parent ``struct kunit`` pointer. The parameterized test context is not used to execute any test logic itself; instead, it serves as a container for shared resources.h](hAll parameter runs in this framework hold a reference to the parameterized test context, which can be accessed using the parent }(hj hhhNhNubh)}(h``struct kunit``h]h struct kunit}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj ubh pointer. The parameterized test context is not used to execute any test logic itself; instead, it serves as a container for shared resources.}(hj hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj hhubh)}(hX"It's possible to add resources to share between parameter runs within a parameterized test by using ``KUNIT_CASE_PARAM_WITH_INIT``, to which you pass custom ``param_init()`` and ``param_exit()`` functions. These functions run once before and once after the parameterized test, respectively.h](hfIt’s possible to add resources to share between parameter runs within a parameterized test by using }(hjhhhNhNubh)}(h``KUNIT_CASE_PARAM_WITH_INIT``h]hKUNIT_CASE_PARAM_WITH_INIT}(hj!hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, to which you pass custom }(hjhhhNhNubh)}(h``param_init()``h]h param_init()}(hj3hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh and }(hjhhhNhNubh)}(h``param_exit()``h]h param_exit()}(hjEhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh` functions. These functions run once before and once after the parameterized test, respectively.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj hhubh)}(hXThe ``param_init()`` function, with the signature ``int (*)(struct kunit *test)``, can be used for adding resources to the ``resources`` or ``priv`` fields of the parameterized test context, registering the parameter array, and any other initialization logic.h](hThe }(hj]hhhNhNubh)}(h``param_init()``h]h param_init()}(hjehhhNhNubah}(h]h ]h"]h$]h&]uh1hhj]ubh function, with the signature }(hj]hhhNhNubh)}(h``int (*)(struct kunit *test)``h]hint (*)(struct kunit *test)}(hjwhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj]ubh*, can be used for adding resources to the }(hj]hhhNhNubh)}(h ``resources``h]h resources}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj]ubh or }(hj]hhhNhNubh)}(h``priv``h]hpriv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj]ubho fields of the parameterized test context, registering the parameter array, and any other initialization logic.}(hj]hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj hhubh)}(hXThe ``param_exit()`` function, with the signature ``void (*)(struct kunit *test)``, can be used to release any resources that were not parameterized test managed (i.e. not automatically cleaned up after the parameterized test ends) and for any other exit logic.h](hThe }(hjhhhNhNubh)}(h``param_exit()``h]h param_exit()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh function, with the signature }(hjhhhNhNubh)}(h ``void (*)(struct kunit *test)``h]hvoid (*)(struct kunit *test)}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, can be used to release any resources that were not parameterized test managed (i.e. not automatically cleaned up after the parameterized test ends) and for any other exit logic.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj hhubh)}(hXBoth ``param_init()`` and ``param_exit()`` are passed the parameterized test context behind the scenes. However, the test case function receives the parameter run context. Therefore, to manage and access shared resources from within a test case function, you must use ``test->parent``.h](hBoth }(hjhhhNhNubh)}(h``param_init()``h]h param_init()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh and }(hjhhhNhNubh)}(h``param_exit()``h]h param_exit()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh are passed the parameterized test context behind the scenes. However, the test case function receives the parameter run context. Therefore, to manage and access shared resources from within a test case function, you must use }(hjhhhNhNubh)}(h``test->parent``h]h test->parent}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhj hhubh)}(hXFor instance, finding a shared resource allocated by the Resource API requires passing ``test->parent`` to ``kunit_find_resource()``. This principle extends to all other APIs that might be used in the test case function, including ``kunit_kzalloc()``, ``kunit_kmalloc_array()``, and others (see Documentation/dev-tools/kunit/api/test.rst and the Documentation/dev-tools/kunit/api/resource.rst).h](hWFor instance, finding a shared resource allocated by the Resource API requires passing }(hj)hhhNhNubh)}(h``test->parent``h]h test->parent}(hj1hhhNhNubah}(h]h ]h"]h$]h&]uh1hhj)ubh to }(hj)hhhNhNubh)}(h``kunit_find_resource()``h]hkunit_find_resource()}(hjChhhNhNubah}(h]h ]h"]h$]h&]uh1hhj)ubhc. This principle extends to all other APIs that might be used in the test case function, including }(hj)hhhNhNubh)}(h``kunit_kzalloc()``h]hkunit_kzalloc()}(hjUhhhNhNubah}(h]h ]h"]h$]h&]uh1hhj)ubh, }(hj)hhhNhNubh)}(h``kunit_kmalloc_array()``h]hkunit_kmalloc_array()}(hjghhhNhNubah}(h]h ]h"]h$]h&]uh1hhj)ubhu, and others (see Documentation/dev-tools/kunit/api/test.rst and the Documentation/dev-tools/kunit/api/resource.rst).}(hj)hhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM hj hhubjT)}(hThe ``suite->init()`` function, which executes before each parameter run, receives the parameter run context. Therefore, any resources set up in ``suite->init()`` are cleaned up after each parameter run.h]h)}(hThe ``suite->init()`` function, which executes before each parameter run, receives the parameter run context. Therefore, any resources set up in ``suite->init()`` are cleaned up after each parameter run.h](hThe }(hjhhhNhNubh)}(h``suite->init()``h]h suite->init()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh| function, which executes before each parameter run, receives the parameter run context. Therefore, any resources set up in }(hjhhhNhNubh)}(h``suite->init()``h]h suite->init()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh) are cleaned up after each parameter run.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjubah}(h]h ]h"]h$]h&]uh1jShj hhhhhNubh)}(hXThe code below shows how you can add the shared resources. Note that this code utilizes the Resource API, which you can read more about here: Documentation/dev-tools/kunit/api/resource.rst. To see the full version of this code please refer to lib/kunit/kunit-example-test.c.h]hXThe code below shows how you can add the shared resources. Note that this code utilizes the Resource API, which you can read more about here: Documentation/dev-tools/kunit/api/resource.rst. To see the full version of this code please refer to lib/kunit/kunit-example-test.c.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhj hhubj)}(hXstatic int example_resource_init(struct kunit_resource *res, void *context) { ... /* Code that allocates memory and stores context in res->data. */ } /* This function deallocates memory for the kunit_resource->data field. */ static void example_resource_free(struct kunit_resource *res) { kfree(res->data); } /* This match function locates a test resource based on defined criteria. */ static bool example_resource_alloc_match(struct kunit *test, struct kunit_resource *res, void *match_data) { return res->data && res->free == example_resource_free; } /* Function to initialize the parameterized test. */ static int example_param_init(struct kunit *test) { int ctx = 3; /* Data to be stored. */ void *data = kunit_alloc_resource(test, example_resource_init, example_resource_free, GFP_KERNEL, &ctx); if (!data) return -ENOMEM; kunit_register_params_array(test, example_params_array, ARRAY_SIZE(example_params_array)); return 0; } /* Example test that uses shared resources in test->resources. */ static void example_params_test_with_init(struct kunit *test) { int threshold; const struct example_param *param = test->param_value; /* Here we pass test->parent to access the parameterized test context. */ struct kunit_resource *res = kunit_find_resource(test->parent, example_resource_alloc_match, NULL); threshold = *((int *)res->data); KUNIT_ASSERT_LE(test, param->value, threshold); kunit_put_resource(res); } static struct kunit_case example_test_cases[] = { KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_gen_params, example_param_init, NULL), {} };h]hXstatic int example_resource_init(struct kunit_resource *res, void *context) { ... /* Code that allocates memory and stores context in res->data. */ } /* This function deallocates memory for the kunit_resource->data field. */ static void example_resource_free(struct kunit_resource *res) { kfree(res->data); } /* This match function locates a test resource based on defined criteria. */ static bool example_resource_alloc_match(struct kunit *test, struct kunit_resource *res, void *match_data) { return res->data && res->free == example_resource_free; } /* Function to initialize the parameterized test. */ static int example_param_init(struct kunit *test) { int ctx = 3; /* Data to be stored. */ void *data = kunit_alloc_resource(test, example_resource_init, example_resource_free, GFP_KERNEL, &ctx); if (!data) return -ENOMEM; kunit_register_params_array(test, example_params_array, ARRAY_SIZE(example_params_array)); return 0; } /* Example test that uses shared resources in test->resources. */ static void example_params_test_with_init(struct kunit *test) { int threshold; const struct example_param *param = test->param_value; /* Here we pass test->parent to access the parameterized test context. */ struct kunit_resource *res = kunit_find_resource(test->parent, example_resource_alloc_match, NULL); threshold = *((int *)res->data); KUNIT_ASSERT_LE(test, param->value, threshold); kunit_put_resource(res); } static struct kunit_case example_test_cases[] = { KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_gen_params, example_param_init, NULL), {} };}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhj hhubh)}(hAs an alternative to using the KUnit Resource API for sharing resources, you can place them in ``test->parent->priv``. This serves as a more lightweight method for resource storage, best for scenarios where complex resource management is not required.h](h_As an alternative to using the KUnit Resource API for sharing resources, you can place them in }(hjhhhNhNubh)}(h``test->parent->priv``h]htest->parent->priv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh. This serves as a more lightweight method for resource storage, best for scenarios where complex resource management is not required.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMRhj hhubh)}(hXAs stated previously ``param_init()`` and ``param_exit()`` get the parameterized test context. So, you can directly use ``test->priv`` within ``param_init/exit`` to manage shared resources. However, from within the test case function, you must navigate up to the parent ``struct kunit`` i.e. the parameterized test context. Therefore, you need to use ``test->parent->priv`` to access those same resources.h](hAs stated previously }(hjhhhNhNubh)}(h``param_init()``h]h param_init()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh and }(hjhhhNhNubh)}(h``param_exit()``h]h param_exit()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh> get the parameterized test context. So, you can directly use }(hjhhhNhNubh)}(h``test->priv``h]h test->priv}(hj$hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh within }(hjhhhNhNubh)}(h``param_init/exit``h]hparam_init/exit}(hj6hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhm to manage shared resources. However, from within the test case function, you must navigate up to the parent }(hjhhhNhNubh)}(h``struct kunit``h]h struct kunit}(hjHhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhA i.e. the parameterized test context. Therefore, you need to use }(hjhhhNhNubh)}(h``test->parent->priv``h]htest->parent->priv}(hjZhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh to access those same resources.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMWhj hhubh)}(hXThe resources placed in ``test->parent->priv`` will need to be allocated in memory to persist across the parameter runs. If memory is allocated using the KUnit memory allocation APIs (described more in the "Allocating Memory" section below), you won't need to worry about deallocation. The APIs will make the memory parameterized test 'managed', ensuring that it will automatically get cleaned up after the parameterized test concludes.h](hThe resources placed in }(hjrhhhNhNubh)}(h``test->parent->priv``h]htest->parent->priv}(hjzhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubhX will need to be allocated in memory to persist across the parameter runs. If memory is allocated using the KUnit memory allocation APIs (described more in the “Allocating Memory” section below), you won’t need to worry about deallocation. The APIs will make the memory parameterized test ‘managed’, ensuring that it will automatically get cleaned up after the parameterized test concludes.}(hjrhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM^hj hhubh)}(hUThe code below demonstrates example usage of the ``priv`` field for shared resources:h](h1The code below demonstrates example usage of the }(hjhhhNhNubh)}(h``priv``h]hpriv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh field for shared resources:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMehj hhubj)}(hXvstatic const struct example_param { int value; } example_params_array[] = { { .value = 3, }, { .value = 2, }, { .value = 1, }, { .value = 0, }, }; /* Initialize the parameterized test context. */ static int example_param_init_priv(struct kunit *test) { int ctx = 3; /* Data to be stored. */ int arr_size = ARRAY_SIZE(example_params_array); /* * Allocate memory using kunit_kzalloc(). Since the `param_init` * function receives the parameterized test context, this memory * allocation will be scoped to the lifetime of the parameterized test. */ test->priv = kunit_kzalloc(test, sizeof(int), GFP_KERNEL); /* Assign the context value to test->priv.*/ *((int *)test->priv) = ctx; /* Register the parameter array. */ kunit_register_params_array(test, example_params_array, arr_size, NULL); return 0; } static void example_params_test_with_init_priv(struct kunit *test) { int threshold; const struct example_param *param = test->param_value; /* By design, test->parent will not be NULL. */ KUNIT_ASSERT_NOT_NULL(test, test->parent); /* Here we use test->parent->priv to access the shared resource. */ threshold = *(int *)test->parent->priv; KUNIT_ASSERT_LE(test, param->value, threshold); } static struct kunit_case example_tests[] = { KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_priv, kunit_array_gen_params, example_param_init_priv, NULL), {} };h]hXvstatic const struct example_param { int value; } example_params_array[] = { { .value = 3, }, { .value = 2, }, { .value = 1, }, { .value = 0, }, }; /* Initialize the parameterized test context. */ static int example_param_init_priv(struct kunit *test) { int ctx = 3; /* Data to be stored. */ int arr_size = ARRAY_SIZE(example_params_array); /* * Allocate memory using kunit_kzalloc(). Since the `param_init` * function receives the parameterized test context, this memory * allocation will be scoped to the lifetime of the parameterized test. */ test->priv = kunit_kzalloc(test, sizeof(int), GFP_KERNEL); /* Assign the context value to test->priv.*/ *((int *)test->priv) = ctx; /* Register the parameter array. */ kunit_register_params_array(test, example_params_array, arr_size, NULL); return 0; } static void example_params_test_with_init_priv(struct kunit *test) { int threshold; const struct example_param *param = test->param_value; /* By design, test->parent will not be NULL. */ KUNIT_ASSERT_NOT_NULL(test, test->parent); /* Here we use test->parent->priv to access the shared resource. */ threshold = *(int *)test->parent->priv; KUNIT_ASSERT_LE(test, param->value, threshold); } static struct kunit_case example_tests[] = { KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_priv, kunit_array_gen_params, example_param_init_priv, NULL), {} };}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhhj hhubeh}(h]adding-shared-resourcesah ]h"]adding shared resourcesah$]h&]uh1hhjw hhhhhMubeh}(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}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMubh)}(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 }(hjhhhNhNubh)}(h ``kzalloc``h]hkzalloc}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, you can instead use }(hjhhhNhNubh)}(h``kunit_kzalloc``h]h kunit_kzalloc}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhL as KUnit will then ensure that the memory is freed once the test completes.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(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 }(hjhhhNhNubh)}(h``KUNIT_ASSERT_EQ``h]hKUNIT_ASSERT_EQ}(hj$hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhT macros to exit early from a test without having to worry about remembering to call }(hjhhhNhNubh)}(h ``kfree``h]hkfree}(hj6hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh. For example:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(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, ""); }}hjNsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubeh}(h]allocating-memoryah ]h"]allocating memoryah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(hRegistering Cleanup Actionsh]hRegistering Cleanup Actions}(hjhhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjehhhhhMubh)}(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 }(hjvhhhNhNubh)}(h``kunit_kzalloc``h]h kunit_kzalloc}(hj~hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjvubh, you can register a custom “deferred action”, which is a cleanup function run when the test exits (whether cleanly, or via a failed assertion).}(hjvhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjehhubh)}(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 }(hjhhhNhNubh)}(h ``void*``h]hvoid*}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh 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.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjehhubh)}(hyThese are very useful for unregistering things from global lists, closing files or other resources, or freeing resources.h]hyThese are very useful for unregistering things from global lists, closing files or other resources, or freeing resources.}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjehhubh)}(h For example:h]h For example:}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjehhubj)}(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); }}hjsbah}(h]h ]h"]h$]h&]hhj"j#Cj%}uh1jhhhMhjehhubh)}(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 }(hjhhhNhNubh)}(h!``KUNIT_DEFINE_ACTION_WRAPPER()``h]hKUNIT_DEFINE_ACTION_WRAPPER()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh macro, for example:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjehhubj)}(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);}hjsbah}(h]h ]h"]h$]h&]hhj"j#jj%}uh1jhhhMhjehhubh)}(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 #include ... VISIBLE_IF_KUNIT int do_interesting_thing() { ... } EXPORT_SYMBOL_IF_KUNIT(do_interesting_thing); /* In the header file "my_file.h" */ #if IS_ENABLED(CONFIG_KUNIT) int do_interesting_thing(void); #endif /* In the KUnit test file "my_file_test.c" */ #include #include ... MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); ... // Use do_interesting_thing() in testsh]hX /* In the file containing functions to test "my_file.c" */ #include #include ... VISIBLE_IF_KUNIT int do_interesting_thing() { ... } EXPORT_SYMBOL_IF_KUNIT(do_interesting_thing); /* In the header file "my_file.h" */ #if IS_ENABLED(CONFIG_KUNIT) int do_interesting_thing(void); #endif /* In the KUnit test file "my_file_test.c" */ #include #include ... MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); ... // Use do_interesting_thing() in tests}hjsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubh)}(hFor a full example, see this `patch `_ where a test is modified to conditionally expose static functions for testing using the macros above.h](hFor a full example, see this }(hjhhhNhNubh reference)}(hP`patch `_h]hpatch}(hjhhhNhNubah}(h]h ]h"]h$]h&]namepatchrefuriEhttps://lore.kernel.org/all/20221207014024.340230-3-rmoar@google.com/uh1jhjubj)}(hH h]h}(h]patchah ]h"]patchah$]h&]refurijuh1j referencedKhjubhf where a test is modified to conditionally expose static functions for testing using the macros above.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubh)}(hAs an **alternative** to the method above, you could conditionally ``#include`` the test file at the end of your .c file. This is not recommended but works if needed. For example:h](hAs an }(hjhhhNhNubhstrong)}(h**alternative**h]h alternative}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1jhjubh. to the method above, you could conditionally }(hjhhhNhNubh)}(h ``#include``h]h#include}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhd the test file at the end of your .c file. This is not recommended but works if needed. For example:}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubj)}(hw/* In "my_file.c" */ static int do_interesting_thing(); #ifdef CONFIG_MY_KUNIT_TEST #include "my_kunit_test.c" #endifh]hw/* In "my_file.c" */ static int do_interesting_thing(); #ifdef CONFIG_MY_KUNIT_TEST #include "my_kunit_test.c" #endif}hj/sbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMhjhhubeh}(h]testing-static-functionsah ]h"]testing static functionsah$]h&]uh1hhjhhhhhMubh)}(hhh](h)}(hInjecting Test-Only Codeh]hInjecting Test-Only Code}(hjIhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjFhhhhhM!ubh)}(hGSimilar to as shown above, we can add test-specific logic. For example:h]hGSimilar to as shown above, we can add test-specific logic. For example:}(hjWhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhM#hjFhhubj)}(h/* In my_file.h */ #ifdef CONFIG_MY_KUNIT_TEST /* Defined in my_kunit_test.c */ void test_only_hook(void); #else void test_only_hook(void) { } #endifh]h/* In my_file.h */ #ifdef CONFIG_MY_KUNIT_TEST /* Defined in my_kunit_test.c */ void test_only_hook(void); #else void test_only_hook(void) { } #endif}hjesbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhM%hjFhhubh)}(hThis test-only code can be made more useful by accessing the current ``kunit_test`` as shown in next section: *Accessing The Current Test*.h](hEThis test-only code can be made more useful by accessing the current }(hjthhhNhNubh)}(h``kunit_test``h]h kunit_test}(hj|hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjtubh as shown in next section: }(hjthhhNhNubh)}(h*Accessing The Current Test*h]hAccessing The Current Test}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjtubh.}(hjthhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM0hjFhhubeh}(h]injecting-test-only-codeah ]h"]injecting test-only codeah$]h&]uh1hhjhhhhhM!ubh)}(hhh](h)}(hAccessing The Current Testh]hAccessing The Current Test}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhM4ubh)}(hXsIn some cases, we need to call test-only code from outside the test file. This is helpful, for example, when providing a fake implementation of a function, or to fail any current test from within an error handler. We can do this via the ``kunit_test`` field in ``task_struct``, which we can access using the ``kunit_get_current_test()`` function in ``kunit/test-bug.h``.h](hIn some cases, we need to call test-only code from outside the test file. This is helpful, for example, when providing a fake implementation of a function, or to fail any current test from within an error handler. We can do this via the }(hjhhhNhNubh)}(h``kunit_test``h]h kunit_test}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh field in }(hjhhhNhNubh)}(h``task_struct``h]h task_struct}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh , which we can access using the }(hjhhhNhNubh)}(h``kunit_get_current_test()``h]hkunit_get_current_test()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh function in }(hjhhhNhNubh)}(h``kunit/test-bug.h``h]hkunit/test-bug.h}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhM6hjhhubh)}(hX,``kunit_get_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 return ``NULL``. 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_get_current_test()``h]hkunit_get_current_test()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh 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 return }(hjhhhNhNubh)}(h``NULL``h]hNULL}(hj+hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh. 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<hjhhubh)}(hXThe example below uses this to implement a "mock" implementation of a function, ``foo``:h](hTThe example below uses this to implement a “mock” implementation of a function, }(hjChhhNhNubh)}(h``foo``h]hfoo}(hjKhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjCubh:}(hjChhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMAhjhhubj)}(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); }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); }}hjcsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMChjhhubh)}(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 }(hjrhhhNhNubh)}(h``priv``h]hpriv}(hjzhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubh member of }(hjrhhhNhNubh)}(h``struct kunit``h]h struct kunit}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubhI as a way of passing data to the test from the init function. In general }(hjrhhhNhNubh)}(h``priv``h]hpriv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjrubhy is pointer that can be used for any user data. This is preferred over static variables, as it avoids concurrency issues.}(hjrhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMchjhhubh)}(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 }(hjhhhNhNubh)}(h``kunit_resource``h]hkunit_resource}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhd. Each test can have multiple resources which have string names providing the same flexibility as a }(hjhhhNhNubh)}(h``priv``h]hpriv}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubhX) 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.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhhjhhubeh}(h]accessing-the-current-testah ]h"]accessing the current testah$]h&]uh1hhjhhhhhM4ubh)}(hhh](h)}(hFailing The Current Testh]hFailing The Current Test}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjhhhhhMpubh)}(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...)}(hj hhhNhNubah}(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}(hj-hhhNhNubah}(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&]uh1hhhhMrhjhhubj)}(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}hjEsbah}(h]h ]h"]h$]h&]hhj"j#j$j%}uh1jhhhMwhjhhubh)}(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()}(hjXhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjTubhX  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.}(hjThhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjhhubeh}(h]failing-the-current-testah ]h"]failing the current testah$]h&]uh1hhjhhhhhMpubh)}(hhh](h)}(h!Managing Fake Devices and Driversh]h!Managing Fake Devices and Drivers}(hj{hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjxhhhhhMubh)}(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 }(hjhhhNhNubh)}(h``struct device``h]h struct device}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh or }(hjhhhNhNubh)}(h``struct device_driver``h]hstruct device_driver}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh{. In many cases, setting up a real device is not required to test any given function, so a fake device can be used instead.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubh)}(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 }(hjhhhNhNubh)}(h``struct kunit_device``h]hstruct kunit_device}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh , and are attached to a special }(hjhhhNhNubh)}(h ``kunit_bus``h]h kunit_bus}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh{. These devices support managed device resources (devres), as described in Documentation/driver-api/driver-model/devres.rst3}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubh)}(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()}(hj+hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubh)}(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 }(hjChhhNhNubh)}(h``kunit_device_register()``h]hkunit_device_register()}(hjKhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjCubhY, which will create and register a device, using a new KUnit-managed driver created with }(hjChhhNhNubh)}(h``kunit_driver_create()``h]hkunit_driver_create()}(hj]hhhNhNubah}(h]h ]h"]h$]h&]uh1hhjCubh7. To provide a specific, non-KUnit-managed driver, use }(hjChhhNhNubh)}(h'``kunit_device_register_with_driver()``h]h#kunit_device_register_with_driver()}(hjohhhNhNubah}(h]h ]h"]h$]h&]uh1hhjCubh 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 }(hjChhhNhNubh)}(h``kunit_device_unregister()``h]hkunit_device_unregister()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjCubh.}(hjChhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubh)}(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 }(hjhhhNhNubh)}(h``root_device_register()``h]hroot_device_register()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh, and instead of }(hjhhhNhNubh)}(h``platform_device_register()``h]hplatform_device_register()}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhjubh> in cases where the device is not otherwise a platform device.}(hjhhhNhNubeh}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubh)}(h For example:h]h For example:}(hjhhhNhNubah}(h]h ]h"]h$]h&]uh1hhhhMhjxhhubj)}(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%}uh1jhhhMhjxhhubeh}(h]!managing-fake-devices-and-driversah ]h"]!managing fake devices and driversah$]h&]uh1hhjhhhhhMubeh}(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{jjzjwjjjjjjjjjjjjj j jjjbj_jjjCj@jjjjjjjujrjju nametypes}(jjwjjojjj{jzjjjjjjj jjbjjCjjjjujuh}(jhjthjjkjljjjzjj jjjwjjjjjjjjjjjjjw j j jj j_jjjej@jjjjjFjjjrjjjxu 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.}hjsbah}(h]h ]h"]h$]h&]uh1hhjubah}(h]h ]h"]h$]h&]levelKtypeINFOsourcehlineKuh1juba transformerN include_log] decorationNhhub.