~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/Documentation/dev-tools/kunit/usage.rst

Version: ~ [ linux-6.12-rc7 ] ~ [ linux-6.11.7 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.60 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.116 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.171 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.229 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.285 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.323 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.12 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /Documentation/dev-tools/kunit/usage.rst (Architecture m68k) and /Documentation/dev-tools/kunit/usage.rst (Architecture mips)


  1 .. SPDX-License-Identifier: GPL-2.0                 1 .. SPDX-License-Identifier: GPL-2.0
  2                                                     2 
  3 Writing Tests                                       3 Writing Tests
  4 =============                                       4 =============
  5                                                     5 
  6 Test Cases                                          6 Test Cases
  7 ----------                                          7 ----------
  8                                                     8 
  9 The fundamental unit in KUnit is the test case      9 The fundamental unit in KUnit is the test case. A test case is a function with
 10 the signature ``void (*)(struct kunit *test)``     10 the signature ``void (*)(struct kunit *test)``. It calls the function under test
 11 and then sets *expectations* for what should h     11 and then sets *expectations* for what should happen. For example:
 12                                                    12 
 13 .. code-block:: c                                  13 .. code-block:: c
 14                                                    14 
 15         void example_test_success(struct kunit     15         void example_test_success(struct kunit *test)
 16         {                                          16         {
 17         }                                          17         }
 18                                                    18 
 19         void example_test_failure(struct kunit     19         void example_test_failure(struct kunit *test)
 20         {                                          20         {
 21                 KUNIT_FAIL(test, "This test ne     21                 KUNIT_FAIL(test, "This test never passes.");
 22         }                                          22         }
 23                                                    23 
 24 In the above example, ``example_test_success``     24 In the above example, ``example_test_success`` always passes because it does
 25 nothing; no expectations are set, and therefor     25 nothing; no expectations are set, and therefore all expectations pass. On the
 26 other hand ``example_test_failure`` always fai     26 other hand ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``,
 27 which is a special expectation that logs a mes     27 which is a special expectation that logs a message and causes the test case to
 28 fail.                                              28 fail.
 29                                                    29 
 30 Expectations                                       30 Expectations
 31 ~~~~~~~~~~~~                                       31 ~~~~~~~~~~~~
 32 An *expectation* specifies that we expect a pi     32 An *expectation* specifies that we expect a piece of code to do something in a
 33 test. An expectation is called like a function     33 test. An expectation is called like a function. A test is made by setting
 34 expectations about the behavior of a piece of      34 expectations about the behavior of a piece of code under test. When one or more
 35 expectations fail, the test case fails and inf     35 expectations fail, the test case fails and information about the failure is
 36 logged. For example:                               36 logged. For example:
 37                                                    37 
 38 .. code-block:: c                                  38 .. code-block:: c
 39                                                    39 
 40         void add_test_basic(struct kunit *test     40         void add_test_basic(struct kunit *test)
 41         {                                          41         {
 42                 KUNIT_EXPECT_EQ(test, 1, add(1     42                 KUNIT_EXPECT_EQ(test, 1, add(1, 0));
 43                 KUNIT_EXPECT_EQ(test, 2, add(1     43                 KUNIT_EXPECT_EQ(test, 2, add(1, 1));
 44         }                                          44         }
 45                                                    45 
 46 In the above example, ``add_test_basic`` makes     46 In the above example, ``add_test_basic`` makes a number of assertions about the
 47 behavior of a function called ``add``. The fir     47 behavior of a function called ``add``. The first parameter is always of type
 48 ``struct kunit *``, which contains information     48 ``struct kunit *``, which contains information about the current test context.
 49 The second parameter, in this case, is what th     49 The second parameter, in this case, is what the value is expected to be. The
 50 last value is what the value actually is. If `     50 last value is what the value actually is. If ``add`` passes all of these
 51 expectations, the test case, ``add_test_basic`     51 expectations, the test case, ``add_test_basic`` will pass; if any one of these
 52 expectations fails, the test case will fail.       52 expectations fails, the test case will fail.
 53                                                    53 
 54 A test case *fails* when any expectation is vi     54 A test case *fails* when any expectation is violated; however, the test will
 55 continue to run, and try other expectations un     55 continue to run, and try other expectations until the test case ends or is
 56 otherwise terminated. This is as opposed to *a     56 otherwise terminated. This is as opposed to *assertions* which are discussed
 57 later.                                             57 later.
 58                                                    58 
 59 To learn about more KUnit expectations, see Do     59 To learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst.
 60                                                    60 
 61 .. note::                                          61 .. note::
 62    A single test case should be short, easy to     62    A single test case should be short, easy to understand, and focused on a
 63    single behavior.                                63    single behavior.
 64                                                    64 
 65 For example, if we want to rigorously test the     65 For example, if we want to rigorously test the ``add`` function above, create
 66 additional tests cases which would test each p     66 additional tests cases which would test each property that an ``add`` function
 67 should have as shown below:                        67 should have as shown below:
 68                                                    68 
 69 .. code-block:: c                                  69 .. code-block:: c
 70                                                    70 
 71         void add_test_basic(struct kunit *test     71         void add_test_basic(struct kunit *test)
 72         {                                          72         {
 73                 KUNIT_EXPECT_EQ(test, 1, add(1     73                 KUNIT_EXPECT_EQ(test, 1, add(1, 0));
 74                 KUNIT_EXPECT_EQ(test, 2, add(1     74                 KUNIT_EXPECT_EQ(test, 2, add(1, 1));
 75         }                                          75         }
 76                                                    76 
 77         void add_test_negative(struct kunit *t     77         void add_test_negative(struct kunit *test)
 78         {                                          78         {
 79                 KUNIT_EXPECT_EQ(test, 0, add(-     79                 KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
 80         }                                          80         }
 81                                                    81 
 82         void add_test_max(struct kunit *test)      82         void add_test_max(struct kunit *test)
 83         {                                          83         {
 84                 KUNIT_EXPECT_EQ(test, INT_MAX,     84                 KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
 85                 KUNIT_EXPECT_EQ(test, -1, add(     85                 KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
 86         }                                          86         }
 87                                                    87 
 88         void add_test_overflow(struct kunit *t     88         void add_test_overflow(struct kunit *test)
 89         {                                          89         {
 90                 KUNIT_EXPECT_EQ(test, INT_MIN,     90                 KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1));
 91         }                                          91         }
 92                                                    92 
 93 Assertions                                         93 Assertions
 94 ~~~~~~~~~~                                         94 ~~~~~~~~~~
 95                                                    95 
 96 An assertion is like an expectation, except th     96 An assertion is like an expectation, except that the assertion immediately
 97 terminates the test case if the condition is n     97 terminates the test case if the condition is not satisfied. For example:
 98                                                    98 
 99 .. code-block:: c                                  99 .. code-block:: c
100                                                   100 
101         static void test_sort(struct kunit *te    101         static void test_sort(struct kunit *test)
102         {                                         102         {
103                 int *a, i, r = 1;                 103                 int *a, i, r = 1;
104                 a = kunit_kmalloc_array(test,     104                 a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL);
105                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    105                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a);
106                 for (i = 0; i < TEST_LEN; i++)    106                 for (i = 0; i < TEST_LEN; i++) {
107                         r = (r * 725861) % 659    107                         r = (r * 725861) % 6599;
108                         a[i] = r;                 108                         a[i] = r;
109                 }                                 109                 }
110                 sort(a, TEST_LEN, sizeof(*a),     110                 sort(a, TEST_LEN, sizeof(*a), cmpint, NULL);
111                 for (i = 0; i < TEST_LEN-1; i+    111                 for (i = 0; i < TEST_LEN-1; i++)
112                         KUNIT_EXPECT_LE(test,     112                         KUNIT_EXPECT_LE(test, a[i], a[i + 1]);
113         }                                         113         }
114                                                   114 
115 In this example, we need to be able to allocat    115 In this example, we need to be able to allocate an array to test the ``sort()``
116 function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_    116 function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_NULL()`` to abort the test if
117 there's an allocation error.                      117 there's an allocation error.
118                                                   118 
119 .. note::                                         119 .. note::
120    In other test frameworks, ``ASSERT`` macros    120    In other test frameworks, ``ASSERT`` macros are often implemented by calling
121    ``return`` so they only work from the test     121    ``return`` so they only work from the test function. In KUnit, we stop the
122    current kthread on failure, so you can call    122    current kthread on failure, so you can call them from anywhere.
123                                                   123 
124 .. note::                                         124 .. note::
125    Warning: There is an exception to the above    125    Warning: There is an exception to the above rule. You shouldn't use assertions
126    in the suite's exit() function, or in the f    126    in the suite's exit() function, or in the free function for a resource. These
127    run when a test is shutting down, and an as    127    run when a test is shutting down, and an assertion here prevents further
128    cleanup code from running, potentially lead    128    cleanup code from running, potentially leading to a memory leak.
129                                                   129 
130 Customizing error messages                        130 Customizing error messages
131 --------------------------                        131 --------------------------
132                                                   132 
133 Each of the ``KUNIT_EXPECT`` and ``KUNIT_ASSER    133 Each of the ``KUNIT_EXPECT`` and ``KUNIT_ASSERT`` macros have a ``_MSG``
134 variant.  These take a format string and argum    134 variant.  These take a format string and arguments to provide additional
135 context to the automatically generated error m    135 context to the automatically generated error messages.
136                                                   136 
137 .. code-block:: c                                 137 .. code-block:: c
138                                                   138 
139         char some_str[41];                        139         char some_str[41];
140         generate_sha1_hex_string(some_str);       140         generate_sha1_hex_string(some_str);
141                                                   141 
142         /* Before. Not easy to tell why the te    142         /* Before. Not easy to tell why the test failed. */
143         KUNIT_EXPECT_EQ(test, strlen(some_str)    143         KUNIT_EXPECT_EQ(test, strlen(some_str), 40);
144                                                   144 
145         /* After. Now we see the offending str    145         /* After. Now we see the offending string. */
146         KUNIT_EXPECT_EQ_MSG(test, strlen(some_    146         KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str);
147                                                   147 
148 Alternatively, one can take full control over     148 Alternatively, one can take full control over the error message by using
149 ``KUNIT_FAIL()``, e.g.                            149 ``KUNIT_FAIL()``, e.g.
150                                                   150 
151 .. code-block:: c                                 151 .. code-block:: c
152                                                   152 
153         /* Before */                              153         /* Before */
154         KUNIT_EXPECT_EQ(test, some_setup_funct    154         KUNIT_EXPECT_EQ(test, some_setup_function(), 0);
155                                                   155 
156         /* After: full control over the failur    156         /* After: full control over the failure message. */
157         if (some_setup_function())                157         if (some_setup_function())
158                 KUNIT_FAIL(test, "Failed to se    158                 KUNIT_FAIL(test, "Failed to setup thing for testing");
159                                                   159 
160                                                   160 
161 Test Suites                                       161 Test Suites
162 ~~~~~~~~~~~                                       162 ~~~~~~~~~~~
163                                                   163 
164 We need many test cases covering all the unit'    164 We need many test cases covering all the unit's behaviors. It is common to have
165 many similar tests. In order to reduce duplica    165 many similar tests. In order to reduce duplication in these closely related
166 tests, most unit testing frameworks (including    166 tests, most unit testing frameworks (including KUnit) provide the concept of a
167 *test suite*. A test suite is a collection of     167 *test suite*. A test suite is a collection of test cases for a unit of code
168 with optional setup and teardown functions tha    168 with optional setup and teardown functions that run before/after the whole
169 suite and/or every test case.                     169 suite and/or every test case.
170                                                   170 
171 .. note::                                         171 .. note::
172    A test case will only run if it is associat    172    A test case will only run if it is associated with a test suite.
173                                                   173 
174 For example:                                      174 For example:
175                                                   175 
176 .. code-block:: c                                 176 .. code-block:: c
177                                                   177 
178         static struct kunit_case example_test_    178         static struct kunit_case example_test_cases[] = {
179                 KUNIT_CASE(example_test_foo),     179                 KUNIT_CASE(example_test_foo),
180                 KUNIT_CASE(example_test_bar),     180                 KUNIT_CASE(example_test_bar),
181                 KUNIT_CASE(example_test_baz),     181                 KUNIT_CASE(example_test_baz),
182                 {}                                182                 {}
183         };                                        183         };
184                                                   184 
185         static struct kunit_suite example_test    185         static struct kunit_suite example_test_suite = {
186                 .name = "example",                186                 .name = "example",
187                 .init = example_test_init,        187                 .init = example_test_init,
188                 .exit = example_test_exit,        188                 .exit = example_test_exit,
189                 .suite_init = example_suite_in    189                 .suite_init = example_suite_init,
190                 .suite_exit = example_suite_ex    190                 .suite_exit = example_suite_exit,
191                 .test_cases = example_test_cas    191                 .test_cases = example_test_cases,
192         };                                        192         };
193         kunit_test_suite(example_test_suite);     193         kunit_test_suite(example_test_suite);
194                                                   194 
195 In the above example, the test suite ``example    195 In the above example, the test suite ``example_test_suite`` would first run
196 ``example_suite_init``, then run the test case    196 ``example_suite_init``, then run the test cases ``example_test_foo``,
197 ``example_test_bar``, and ``example_test_baz``    197 ``example_test_bar``, and ``example_test_baz``. Each would have
198 ``example_test_init`` called immediately befor    198 ``example_test_init`` called immediately before it and ``example_test_exit``
199 called immediately after it. Finally, ``exampl    199 called immediately after it. Finally, ``example_suite_exit`` would be called
200 after everything else. ``kunit_test_suite(exam    200 after everything else. ``kunit_test_suite(example_test_suite)`` registers the
201 test suite with the KUnit test framework.         201 test suite with the KUnit test framework.
202                                                   202 
203 .. note::                                         203 .. note::
204    The ``exit`` and ``suite_exit`` functions w    204    The ``exit`` and ``suite_exit`` functions will run even if ``init`` or
205    ``suite_init`` fail. Make sure that they ca    205    ``suite_init`` fail. Make sure that they can handle any inconsistent
206    state which may result from ``init`` or ``s    206    state which may result from ``init`` or ``suite_init`` encountering errors
207    or exiting early.                              207    or exiting early.
208                                                   208 
209 ``kunit_test_suite(...)`` is a macro which tel    209 ``kunit_test_suite(...)`` is a macro which tells the linker to put the
210 specified test suite in a special linker secti    210 specified test suite in a special linker section so that it can be run by KUnit
211 either after ``late_init``, or when the test m    211 either after ``late_init``, or when the test module is loaded (if the test was
212 built as a module).                               212 built as a module).
213                                                   213 
214 For more information, see Documentation/dev-to    214 For more information, see Documentation/dev-tools/kunit/api/test.rst.
215                                                   215 
216 .. _kunit-on-non-uml:                             216 .. _kunit-on-non-uml:
217                                                   217 
218 Writing Tests For Other Architectures             218 Writing Tests For Other Architectures
219 -------------------------------------             219 -------------------------------------
220                                                   220 
221 It is better to write tests that run on UML to    221 It is better to write tests that run on UML to tests that only run under a
222 particular architecture. It is better to write    222 particular architecture. It is better to write tests that run under QEMU or
223 another easy to obtain (and monetarily free) s    223 another easy to obtain (and monetarily free) software environment to a specific
224 piece of hardware.                                224 piece of hardware.
225                                                   225 
226 Nevertheless, there are still valid reasons to    226 Nevertheless, there are still valid reasons to write a test that is architecture
227 or hardware specific. For example, we might wa    227 or hardware specific. For example, we might want to test code that really
228 belongs in ``arch/some-arch/*``. Even so, try     228 belongs in ``arch/some-arch/*``. Even so, try to write the test so that it does
229 not depend on physical hardware. Some of our t    229 not depend on physical hardware. Some of our test cases may not need hardware,
230 only few tests actually require the hardware t    230 only few tests actually require the hardware to test it. When hardware is not
231 available, instead of disabling tests, we can     231 available, instead of disabling tests, we can skip them.
232                                                   232 
233 Now that we have narrowed down exactly what bi    233 Now that we have narrowed down exactly what bits are hardware specific, the
234 actual procedure for writing and running the t    234 actual procedure for writing and running the tests is same as writing normal
235 KUnit tests.                                      235 KUnit tests.
236                                                   236 
237 .. important::                                    237 .. important::
238    We may have to reset hardware state. If thi    238    We may have to reset hardware state. If this is not possible, we may only
239    be able to run one test case per invocation    239    be able to run one test case per invocation.
240                                                   240 
241 .. TODO(brendanhiggins@google.com): Add an act    241 .. TODO(brendanhiggins@google.com): Add an actual example of an architecture-
242    dependent KUnit test.                          242    dependent KUnit test.
243                                                   243 
244 Common Patterns                                   244 Common Patterns
245 ===============                                   245 ===============
246                                                   246 
247 Isolating Behavior                                247 Isolating Behavior
248 ------------------                                248 ------------------
249                                                   249 
250 Unit testing limits the amount of code under t    250 Unit testing limits the amount of code under test to a single unit. It controls
251 what code gets run when the unit under test ca    251 what code gets run when the unit under test calls a function. Where a function
252 is exposed as part of an API such that the def    252 is exposed as part of an API such that the definition of that function can be
253 changed without affecting the rest of the code    253 changed without affecting the rest of the code base. In the kernel, this comes
254 from two constructs: classes, which are struct    254 from two constructs: classes, which are structs that contain function pointers
255 provided by the implementer, and architecture-    255 provided by the implementer, and architecture-specific functions, which have
256 definitions selected at compile time.             256 definitions selected at compile time.
257                                                   257 
258 Classes                                           258 Classes
259 ~~~~~~~                                           259 ~~~~~~~
260                                                   260 
261 Classes are not a construct that is built into    261 Classes are not a construct that is built into the C programming language;
262 however, it is an easily derived concept. Acco    262 however, it is an easily derived concept. Accordingly, in most cases, every
263 project that does not use a standardized objec    263 project that does not use a standardized object oriented library (like GNOME's
264 GObject) has their own slightly different way     264 GObject) has their own slightly different way of doing object oriented
265 programming; the Linux kernel is no exception.    265 programming; the Linux kernel is no exception.
266                                                   266 
267 The central concept in kernel object oriented     267 The central concept in kernel object oriented programming is the class. In the
268 kernel, a *class* is a struct that contains fu    268 kernel, a *class* is a struct that contains function pointers. This creates a
269 contract between *implementers* and *users* si    269 contract between *implementers* and *users* since it forces them to use the
270 same function signature without having to call    270 same function signature without having to call the function directly. To be a
271 class, the function pointers must specify that    271 class, the function pointers must specify that a pointer to the class, known as
272 a *class handle*, be one of the parameters. Th    272 a *class handle*, be one of the parameters. Thus the member functions (also
273 known as *methods*) have access to member vari    273 known as *methods*) have access to member variables (also known as *fields*)
274 allowing the same implementation to have multi    274 allowing the same implementation to have multiple *instances*.
275                                                   275 
276 A class can be *overridden* by *child classes*    276 A class can be *overridden* by *child classes* by embedding the *parent class*
277 in the child class. Then when the child class     277 in the child class. Then when the child class *method* is called, the child
278 implementation knows that the pointer passed t    278 implementation knows that the pointer passed to it is of a parent contained
279 within the child. Thus, the child can compute     279 within the child. Thus, the child can compute the pointer to itself because the
280 pointer to the parent is always a fixed offset    280 pointer to the parent is always a fixed offset from the pointer to the child.
281 This offset is the offset of the parent contai    281 This offset is the offset of the parent contained in the child struct. For
282 example:                                          282 example:
283                                                   283 
284 .. code-block:: c                                 284 .. code-block:: c
285                                                   285 
286         struct shape {                            286         struct shape {
287                 int (*area)(struct shape *this    287                 int (*area)(struct shape *this);
288         };                                        288         };
289                                                   289 
290         struct rectangle {                        290         struct rectangle {
291                 struct shape parent;              291                 struct shape parent;
292                 int length;                       292                 int length;
293                 int width;                        293                 int width;
294         };                                        294         };
295                                                   295 
296         int rectangle_area(struct shape *this)    296         int rectangle_area(struct shape *this)
297         {                                         297         {
298                 struct rectangle *self = conta    298                 struct rectangle *self = container_of(this, struct rectangle, parent);
299                                                   299 
300                 return self->length * self->wi    300                 return self->length * self->width;
301         };                                        301         };
302                                                   302 
303         void rectangle_new(struct rectangle *s    303         void rectangle_new(struct rectangle *self, int length, int width)
304         {                                         304         {
305                 self->parent.area = rectangle_    305                 self->parent.area = rectangle_area;
306                 self->length = length;            306                 self->length = length;
307                 self->width = width;              307                 self->width = width;
308         }                                         308         }
309                                                   309 
310 In this example, computing the pointer to the     310 In this example, computing the pointer to the child from the pointer to the
311 parent is done by ``container_of``.               311 parent is done by ``container_of``.
312                                                   312 
313 Faking Classes                                    313 Faking Classes
314 ~~~~~~~~~~~~~~                                    314 ~~~~~~~~~~~~~~
315                                                   315 
316 In order to unit test a piece of code that cal    316 In order to unit test a piece of code that calls a method in a class, the
317 behavior of the method must be controllable, o    317 behavior of the method must be controllable, otherwise the test ceases to be a
318 unit test and becomes an integration test.        318 unit test and becomes an integration test.
319                                                   319 
320 A fake class implements a piece of code that i    320 A fake class implements a piece of code that is different than what runs in a
321 production instance, but behaves identical fro    321 production instance, but behaves identical from the standpoint of the callers.
322 This is done to replace a dependency that is h    322 This is done to replace a dependency that is hard to deal with, or is slow. For
323 example, implementing a fake EEPROM that store    323 example, implementing a fake EEPROM that stores the "contents" in an
324 internal buffer. Assume we have a class that r    324 internal buffer. Assume we have a class that represents an EEPROM:
325                                                   325 
326 .. code-block:: c                                 326 .. code-block:: c
327                                                   327 
328         struct eeprom {                           328         struct eeprom {
329                 ssize_t (*read)(struct eeprom     329                 ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count);
330                 ssize_t (*write)(struct eeprom    330                 ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count);
331         };                                        331         };
332                                                   332 
333 And we want to test code that buffers writes t    333 And we want to test code that buffers writes to the EEPROM:
334                                                   334 
335 .. code-block:: c                                 335 .. code-block:: c
336                                                   336 
337         struct eeprom_buffer {                    337         struct eeprom_buffer {
338                 ssize_t (*write)(struct eeprom    338                 ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count);
339                 int flush(struct eeprom_buffer    339                 int flush(struct eeprom_buffer *this);
340                 size_t flush_count; /* Flushes    340                 size_t flush_count; /* Flushes when buffer exceeds flush_count. */
341         };                                        341         };
342                                                   342 
343         struct eeprom_buffer *new_eeprom_buffe    343         struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom);
344         void destroy_eeprom_buffer(struct eepr    344         void destroy_eeprom_buffer(struct eeprom *eeprom);
345                                                   345 
346 We can test this code by *faking out* the unde    346 We can test this code by *faking out* the underlying EEPROM:
347                                                   347 
348 .. code-block:: c                                 348 .. code-block:: c
349                                                   349 
350         struct fake_eeprom {                      350         struct fake_eeprom {
351                 struct eeprom parent;             351                 struct eeprom parent;
352                 char contents[FAKE_EEPROM_CONT    352                 char contents[FAKE_EEPROM_CONTENTS_SIZE];
353         };                                        353         };
354                                                   354 
355         ssize_t fake_eeprom_read(struct eeprom    355         ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count)
356         {                                         356         {
357                 struct fake_eeprom *this = con    357                 struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
358                                                   358 
359                 count = min(count, FAKE_EEPROM    359                 count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
360                 memcpy(buffer, this->contents     360                 memcpy(buffer, this->contents + offset, count);
361                                                   361 
362                 return count;                     362                 return count;
363         }                                         363         }
364                                                   364 
365         ssize_t fake_eeprom_write(struct eepro    365         ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count)
366         {                                         366         {
367                 struct fake_eeprom *this = con    367                 struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
368                                                   368 
369                 count = min(count, FAKE_EEPROM    369                 count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
370                 memcpy(this->contents + offset    370                 memcpy(this->contents + offset, buffer, count);
371                                                   371 
372                 return count;                     372                 return count;
373         }                                         373         }
374                                                   374 
375         void fake_eeprom_init(struct fake_eepr    375         void fake_eeprom_init(struct fake_eeprom *this)
376         {                                         376         {
377                 this->parent.read = fake_eepro    377                 this->parent.read = fake_eeprom_read;
378                 this->parent.write = fake_eepr    378                 this->parent.write = fake_eeprom_write;
379                 memset(this->contents, 0, FAKE    379                 memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE);
380         }                                         380         }
381                                                   381 
382 We can now use it to test ``struct eeprom_buff    382 We can now use it to test ``struct eeprom_buffer``:
383                                                   383 
384 .. code-block:: c                                 384 .. code-block:: c
385                                                   385 
386         struct eeprom_buffer_test {               386         struct eeprom_buffer_test {
387                 struct fake_eeprom *fake_eepro    387                 struct fake_eeprom *fake_eeprom;
388                 struct eeprom_buffer *eeprom_b    388                 struct eeprom_buffer *eeprom_buffer;
389         };                                        389         };
390                                                   390 
391         static void eeprom_buffer_test_does_no    391         static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test)
392         {                                         392         {
393                 struct eeprom_buffer_test *ctx    393                 struct eeprom_buffer_test *ctx = test->priv;
394                 struct eeprom_buffer *eeprom_b    394                 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
395                 struct fake_eeprom *fake_eepro    395                 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
396                 char buffer[] = {0xff};           396                 char buffer[] = {0xff};
397                                                   397 
398                 eeprom_buffer->flush_count = S    398                 eeprom_buffer->flush_count = SIZE_MAX;
399                                                   399 
400                 eeprom_buffer->write(eeprom_bu    400                 eeprom_buffer->write(eeprom_buffer, buffer, 1);
401                 KUNIT_EXPECT_EQ(test, fake_eep    401                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
402                                                   402 
403                 eeprom_buffer->write(eeprom_bu    403                 eeprom_buffer->write(eeprom_buffer, buffer, 1);
404                 KUNIT_EXPECT_EQ(test, fake_eep    404                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0);
405                                                   405 
406                 eeprom_buffer->flush(eeprom_bu    406                 eeprom_buffer->flush(eeprom_buffer);
407                 KUNIT_EXPECT_EQ(test, fake_eep    407                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
408                 KUNIT_EXPECT_EQ(test, fake_eep    408                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
409         }                                         409         }
410                                                   410 
411         static void eeprom_buffer_test_flushes    411         static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test)
412         {                                         412         {
413                 struct eeprom_buffer_test *ctx    413                 struct eeprom_buffer_test *ctx = test->priv;
414                 struct eeprom_buffer *eeprom_b    414                 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
415                 struct fake_eeprom *fake_eepro    415                 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
416                 char buffer[] = {0xff};           416                 char buffer[] = {0xff};
417                                                   417 
418                 eeprom_buffer->flush_count = 2    418                 eeprom_buffer->flush_count = 2;
419                                                   419 
420                 eeprom_buffer->write(eeprom_bu    420                 eeprom_buffer->write(eeprom_buffer, buffer, 1);
421                 KUNIT_EXPECT_EQ(test, fake_eep    421                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
422                                                   422 
423                 eeprom_buffer->write(eeprom_bu    423                 eeprom_buffer->write(eeprom_buffer, buffer, 1);
424                 KUNIT_EXPECT_EQ(test, fake_eep    424                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
425                 KUNIT_EXPECT_EQ(test, fake_eep    425                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
426         }                                         426         }
427                                                   427 
428         static void eeprom_buffer_test_flushes    428         static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test)
429         {                                         429         {
430                 struct eeprom_buffer_test *ctx    430                 struct eeprom_buffer_test *ctx = test->priv;
431                 struct eeprom_buffer *eeprom_b    431                 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
432                 struct fake_eeprom *fake_eepro    432                 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
433                 char buffer[] = {0xff, 0xff};     433                 char buffer[] = {0xff, 0xff};
434                                                   434 
435                 eeprom_buffer->flush_count = 2    435                 eeprom_buffer->flush_count = 2;
436                                                   436 
437                 eeprom_buffer->write(eeprom_bu    437                 eeprom_buffer->write(eeprom_buffer, buffer, 1);
438                 KUNIT_EXPECT_EQ(test, fake_eep    438                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
439                                                   439 
440                 eeprom_buffer->write(eeprom_bu    440                 eeprom_buffer->write(eeprom_buffer, buffer, 2);
441                 KUNIT_EXPECT_EQ(test, fake_eep    441                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
442                 KUNIT_EXPECT_EQ(test, fake_eep    442                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
443                 /* Should have only flushed th    443                 /* Should have only flushed the first two bytes. */
444                 KUNIT_EXPECT_EQ(test, fake_eep    444                 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0);
445         }                                         445         }
446                                                   446 
447         static int eeprom_buffer_test_init(str    447         static int eeprom_buffer_test_init(struct kunit *test)
448         {                                         448         {
449                 struct eeprom_buffer_test *ctx    449                 struct eeprom_buffer_test *ctx;
450                                                   450 
451                 ctx = kunit_kzalloc(test, size    451                 ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
452                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    452                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);
453                                                   453 
454                 ctx->fake_eeprom = kunit_kzall    454                 ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL);
455                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    455                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom);
456                 fake_eeprom_init(ctx->fake_eep    456                 fake_eeprom_init(ctx->fake_eeprom);
457                                                   457 
458                 ctx->eeprom_buffer = new_eepro    458                 ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent);
459                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    459                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer);
460                                                   460 
461                 test->priv = ctx;                 461                 test->priv = ctx;
462                                                   462 
463                 return 0;                         463                 return 0;
464         }                                         464         }
465                                                   465 
466         static void eeprom_buffer_test_exit(st    466         static void eeprom_buffer_test_exit(struct kunit *test)
467         {                                         467         {
468                 struct eeprom_buffer_test *ctx    468                 struct eeprom_buffer_test *ctx = test->priv;
469                                                   469 
470                 destroy_eeprom_buffer(ctx->eep    470                 destroy_eeprom_buffer(ctx->eeprom_buffer);
471         }                                         471         }
472                                                   472 
473 Testing Against Multiple Inputs                   473 Testing Against Multiple Inputs
474 -------------------------------                   474 -------------------------------
475                                                   475 
476 Testing just a few inputs is not enough to ens    476 Testing just a few inputs is not enough to ensure that the code works correctly,
477 for example: testing a hash function.             477 for example: testing a hash function.
478                                                   478 
479 We can write a helper macro or function. The f    479 We can write a helper macro or function. The function is called for each input.
480 For example, to test ``sha1sum(1)``, we can wr    480 For example, to test ``sha1sum(1)``, we can write:
481                                                   481 
482 .. code-block:: c                                 482 .. code-block:: c
483                                                   483 
484         #define TEST_SHA1(in, want) \             484         #define TEST_SHA1(in, want) \
485                 sha1sum(in, out); \               485                 sha1sum(in, out); \
486                 KUNIT_EXPECT_STREQ_MSG(test, o    486                 KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in);
487                                                   487 
488         char out[40];                             488         char out[40];
489         TEST_SHA1("hello world",  "2aae6c35c94    489         TEST_SHA1("hello world",  "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
490         TEST_SHA1("hello world!", "430ce34d020    490         TEST_SHA1("hello world!", "430ce34d020724ed75a196dfc2ad67c77772d169");
491                                                   491 
492 Note the use of the ``_MSG`` version of ``KUNI    492 Note the use of the ``_MSG`` version of ``KUNIT_EXPECT_STREQ`` to print a more
493 detailed error and make the assertions clearer    493 detailed error and make the assertions clearer within the helper macros.
494                                                   494 
495 The ``_MSG`` variants are useful when the same    495 The ``_MSG`` variants are useful when the same expectation is called multiple
496 times (in a loop or helper function) and thus     496 times (in a loop or helper function) and thus the line number is not enough to
497 identify what failed, as shown below.             497 identify what failed, as shown below.
498                                                   498 
499 In complicated cases, we recommend using a *ta    499 In complicated cases, we recommend using a *table-driven test* compared to the
500 helper macro variation, for example:              500 helper macro variation, for example:
501                                                   501 
502 .. code-block:: c                                 502 .. code-block:: c
503                                                   503 
504         int i;                                    504         int i;
505         char out[40];                             505         char out[40];
506                                                   506 
507         struct sha1_test_case {                   507         struct sha1_test_case {
508                 const char *str;                  508                 const char *str;
509                 const char *sha1;                 509                 const char *sha1;
510         };                                        510         };
511                                                   511 
512         struct sha1_test_case cases[] = {         512         struct sha1_test_case cases[] = {
513                 {                                 513                 {
514                         .str = "hello world",     514                         .str = "hello world",
515                         .sha1 = "2aae6c35c94fc    515                         .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
516                 },                                516                 },
517                 {                                 517                 {
518                         .str = "hello world!",    518                         .str = "hello world!",
519                         .sha1 = "430ce34d02072    519                         .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
520                 },                                520                 },
521         };                                        521         };
522         for (i = 0; i < ARRAY_SIZE(cases); ++i    522         for (i = 0; i < ARRAY_SIZE(cases); ++i) {
523                 sha1sum(cases[i].str, out);       523                 sha1sum(cases[i].str, out);
524                 KUNIT_EXPECT_STREQ_MSG(test, o    524                 KUNIT_EXPECT_STREQ_MSG(test, out, cases[i].sha1,
525                                       "sha1sum    525                                       "sha1sum(%s)", cases[i].str);
526         }                                         526         }
527                                                   527 
528                                                   528 
529 There is more boilerplate code involved, but i    529 There is more boilerplate code involved, but it can:
530                                                   530 
531 * be more readable when there are multiple inp    531 * be more readable when there are multiple inputs/outputs (due to field names).
532                                                   532 
533   * For example, see ``fs/ext4/inode-test.c``.    533   * For example, see ``fs/ext4/inode-test.c``.
534                                                   534 
535 * reduce duplication if test cases are shared     535 * reduce duplication if test cases are shared across multiple tests.
536                                                   536 
537   * For example: if we want to test ``sha256su    537   * For example: if we want to test ``sha256sum``, we could add a ``sha256``
538     field and reuse ``cases``.                    538     field and reuse ``cases``.
539                                                   539 
540 * be converted to a "parameterized test".         540 * be converted to a "parameterized test".
541                                                   541 
542 Parameterized Testing                             542 Parameterized Testing
543 ~~~~~~~~~~~~~~~~~~~~~                             543 ~~~~~~~~~~~~~~~~~~~~~
544                                                   544 
545 The table-driven testing pattern is common eno    545 The table-driven testing pattern is common enough that KUnit has special
546 support for it.                                   546 support for it.
547                                                   547 
548 By reusing the same ``cases`` array from above    548 By reusing the same ``cases`` array from above, we can write the test as a
549 "parameterized test" with the following.          549 "parameterized test" with the following.
550                                                   550 
551 .. code-block:: c                                 551 .. code-block:: c
552                                                   552 
553         // This is copy-pasted from above.        553         // This is copy-pasted from above.
554         struct sha1_test_case {                   554         struct sha1_test_case {
555                 const char *str;                  555                 const char *str;
556                 const char *sha1;                 556                 const char *sha1;
557         };                                        557         };
558         const struct sha1_test_case cases[] =     558         const struct sha1_test_case cases[] = {
559                 {                                 559                 {
560                         .str = "hello world",     560                         .str = "hello world",
561                         .sha1 = "2aae6c35c94fc    561                         .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
562                 },                                562                 },
563                 {                                 563                 {
564                         .str = "hello world!",    564                         .str = "hello world!",
565                         .sha1 = "430ce34d02072    565                         .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
566                 },                                566                 },
567         };                                        567         };
568                                                   568 
569         // Creates `sha1_gen_params()` to iter    569         // Creates `sha1_gen_params()` to iterate over `cases` while using
570         // the struct member `str` for the cas    570         // the struct member `str` for the case description.
571         KUNIT_ARRAY_PARAM_DESC(sha1, cases, st    571         KUNIT_ARRAY_PARAM_DESC(sha1, cases, str);
572                                                   572 
573         // Looks no different from a normal te    573         // Looks no different from a normal test.
574         static void sha1_test(struct kunit *te    574         static void sha1_test(struct kunit *test)
575         {                                         575         {
576                 // This function can just cont    576                 // This function can just contain the body of the for-loop.
577                 // The former `cases[i]` is ac    577                 // The former `cases[i]` is accessible under test->param_value.
578                 char out[40];                     578                 char out[40];
579                 struct sha1_test_case *test_pa    579                 struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value);
580                                                   580 
581                 sha1sum(test_param->str, out);    581                 sha1sum(test_param->str, out);
582                 KUNIT_EXPECT_STREQ_MSG(test, o    582                 KUNIT_EXPECT_STREQ_MSG(test, out, test_param->sha1,
583                                       "sha1sum    583                                       "sha1sum(%s)", test_param->str);
584         }                                         584         }
585                                                   585 
586         // Instead of KUNIT_CASE, we use KUNIT    586         // Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the
587         // function declared by KUNIT_ARRAY_PA    587         // function declared by KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC.
588         static struct kunit_case sha1_test_cas    588         static struct kunit_case sha1_test_cases[] = {
589                 KUNIT_CASE_PARAM(sha1_test, sh    589                 KUNIT_CASE_PARAM(sha1_test, sha1_gen_params),
590                 {}                                590                 {}
591         };                                        591         };
592                                                   592 
593 Allocating Memory                                 593 Allocating Memory
594 -----------------                                 594 -----------------
595                                                   595 
596 Where you might use ``kzalloc``, you can inste    596 Where you might use ``kzalloc``, you can instead use ``kunit_kzalloc`` as KUnit
597 will then ensure that the memory is freed once    597 will then ensure that the memory is freed once the test completes.
598                                                   598 
599 This is useful because it lets us use the ``KU    599 This is useful because it lets us use the ``KUNIT_ASSERT_EQ`` macros to exit
600 early from a test without having to worry abou    600 early from a test without having to worry about remembering to call ``kfree``.
601 For example:                                      601 For example:
602                                                   602 
603 .. code-block:: c                                 603 .. code-block:: c
604                                                   604 
605         void example_test_allocation(struct ku    605         void example_test_allocation(struct kunit *test)
606         {                                         606         {
607                 char *buffer = kunit_kzalloc(t    607                 char *buffer = kunit_kzalloc(test, 16, GFP_KERNEL);
608                 /* Ensure allocation succeeded    608                 /* Ensure allocation succeeded. */
609                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    609                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buffer);
610                                                   610 
611                 KUNIT_ASSERT_STREQ(test, buffe    611                 KUNIT_ASSERT_STREQ(test, buffer, "");
612         }                                         612         }
613                                                   613 
614 Registering Cleanup Actions                       614 Registering Cleanup Actions
615 ---------------------------                       615 ---------------------------
616                                                   616 
617 If you need to perform some cleanup beyond sim    617 If you need to perform some cleanup beyond simple use of ``kunit_kzalloc``,
618 you can register a custom "deferred action", w    618 you can register a custom "deferred action", which is a cleanup function
619 run when the test exits (whether cleanly, or v    619 run when the test exits (whether cleanly, or via a failed assertion).
620                                                   620 
621 Actions are simple functions with no return va    621 Actions are simple functions with no return value, and a single ``void*``
622 context argument, and fulfill the same role as    622 context argument, and fulfill the same role as "cleanup" functions in Python
623 and Go tests, "defer" statements in languages     623 and Go tests, "defer" statements in languages which support them, and
624 (in some cases) destructors in RAII languages.    624 (in some cases) destructors in RAII languages.
625                                                   625 
626 These are very useful for unregistering things    626 These are very useful for unregistering things from global lists, closing
627 files or other resources, or freeing resources    627 files or other resources, or freeing resources.
628                                                   628 
629 For example:                                      629 For example:
630                                                   630 
631 .. code-block:: C                                 631 .. code-block:: C
632                                                   632 
633         static void cleanup_device(void *ctx)     633         static void cleanup_device(void *ctx)
634         {                                         634         {
635                 struct device *dev = (struct d    635                 struct device *dev = (struct device *)ctx;
636                                                   636 
637                 device_unregister(dev);           637                 device_unregister(dev);
638         }                                         638         }
639                                                   639 
640         void example_device_test(struct kunit     640         void example_device_test(struct kunit *test)
641         {                                         641         {
642                 struct my_device dev;             642                 struct my_device dev;
643                                                   643 
644                 device_register(&dev);            644                 device_register(&dev);
645                                                   645 
646                 kunit_add_action(test, &cleanu    646                 kunit_add_action(test, &cleanup_device, &dev);
647         }                                         647         }
648                                                   648 
649 Note that, for functions like device_unregiste    649 Note that, for functions like device_unregister which only accept a single
650 pointer-sized argument, it's possible to autom    650 pointer-sized argument, it's possible to automatically generate a wrapper
651 with the ``KUNIT_DEFINE_ACTION_WRAPPER()`` mac    651 with the ``KUNIT_DEFINE_ACTION_WRAPPER()`` macro, for example:
652                                                   652 
653 .. code-block:: C                                 653 .. code-block:: C
654                                                   654 
655         KUNIT_DEFINE_ACTION_WRAPPER(device_unr    655         KUNIT_DEFINE_ACTION_WRAPPER(device_unregister, device_unregister_wrapper, struct device *);
656         kunit_add_action(test, &device_unregis    656         kunit_add_action(test, &device_unregister_wrapper, &dev);
657                                                   657 
658 You should do this in preference to manually c    658 You should do this in preference to manually casting to the ``kunit_action_t`` type,
659 as casting function pointers will break Contro    659 as casting function pointers will break Control Flow Integrity (CFI).
660                                                   660 
661 ``kunit_add_action`` can fail if, for example,    661 ``kunit_add_action`` can fail if, for example, the system is out of memory.
662 You can use ``kunit_add_action_or_reset`` inst    662 You can use ``kunit_add_action_or_reset`` instead which runs the action
663 immediately if it cannot be deferred.             663 immediately if it cannot be deferred.
664                                                   664 
665 If you need more control over when the cleanup    665 If you need more control over when the cleanup function is called, you
666 can trigger it early using ``kunit_release_act    666 can trigger it early using ``kunit_release_action``, or cancel it entirely
667 with ``kunit_remove_action``.                     667 with ``kunit_remove_action``.
668                                                   668 
669                                                   669 
670 Testing Static Functions                          670 Testing Static Functions
671 ------------------------                          671 ------------------------
672                                                   672 
673 If we do not want to expose functions or varia    673 If we do not want to expose functions or variables for testing, one option is to
674 conditionally export the used symbol. For exam    674 conditionally export the used symbol. For example:
675                                                   675 
676 .. code-block:: c                                 676 .. code-block:: c
677                                                   677 
678         /* In my_file.c */                        678         /* In my_file.c */
679                                                   679 
680         VISIBLE_IF_KUNIT int do_interesting_th    680         VISIBLE_IF_KUNIT int do_interesting_thing();
681         EXPORT_SYMBOL_IF_KUNIT(do_interesting_    681         EXPORT_SYMBOL_IF_KUNIT(do_interesting_thing);
682                                                   682 
683         /* In my_file.h */                        683         /* In my_file.h */
684                                                   684 
685         #if IS_ENABLED(CONFIG_KUNIT)              685         #if IS_ENABLED(CONFIG_KUNIT)
686                 int do_interesting_thing(void)    686                 int do_interesting_thing(void);
687         #endif                                    687         #endif
688                                                   688 
689 Alternatively, you could conditionally ``#incl    689 Alternatively, you could conditionally ``#include`` the test file at the end of
690 your .c file. For example:                        690 your .c file. For example:
691                                                   691 
692 .. code-block:: c                                 692 .. code-block:: c
693                                                   693 
694         /* In my_file.c */                        694         /* In my_file.c */
695                                                   695 
696         static int do_interesting_thing();        696         static int do_interesting_thing();
697                                                   697 
698         #ifdef CONFIG_MY_KUNIT_TEST               698         #ifdef CONFIG_MY_KUNIT_TEST
699         #include "my_kunit_test.c"                699         #include "my_kunit_test.c"
700         #endif                                    700         #endif
701                                                   701 
702 Injecting Test-Only Code                          702 Injecting Test-Only Code
703 ------------------------                          703 ------------------------
704                                                   704 
705 Similar to as shown above, we can add test-spe    705 Similar to as shown above, we can add test-specific logic. For example:
706                                                   706 
707 .. code-block:: c                                 707 .. code-block:: c
708                                                   708 
709         /* In my_file.h */                        709         /* In my_file.h */
710                                                   710 
711         #ifdef CONFIG_MY_KUNIT_TEST               711         #ifdef CONFIG_MY_KUNIT_TEST
712         /* Defined in my_kunit_test.c */          712         /* Defined in my_kunit_test.c */
713         void test_only_hook(void);                713         void test_only_hook(void);
714         #else                                     714         #else
715         void test_only_hook(void) { }             715         void test_only_hook(void) { }
716         #endif                                    716         #endif
717                                                   717 
718 This test-only code can be made more useful by    718 This test-only code can be made more useful by accessing the current ``kunit_test``
719 as shown in next section: *Accessing The Curre    719 as shown in next section: *Accessing The Current Test*.
720                                                   720 
721 Accessing The Current Test                        721 Accessing The Current Test
722 --------------------------                        722 --------------------------
723                                                   723 
724 In some cases, we need to call test-only code     724 In some cases, we need to call test-only code from outside the test file.  This
725 is helpful, for example, when providing a fake    725 is helpful, for example, when providing a fake implementation of a function, or
726 to fail any current test from within an error     726 to fail any current test from within an error handler.
727 We can do this via the ``kunit_test`` field in    727 We can do this via the ``kunit_test`` field in ``task_struct``, which we can
728 access using the ``kunit_get_current_test()``     728 access using the ``kunit_get_current_test()`` function in ``kunit/test-bug.h``.
729                                                   729 
730 ``kunit_get_current_test()`` is safe to call e    730 ``kunit_get_current_test()`` is safe to call even if KUnit is not enabled. If
731 KUnit is not enabled, or if no test is running    731 KUnit is not enabled, or if no test is running in the current task, it will
732 return ``NULL``. This compiles down to either     732 return ``NULL``. This compiles down to either a no-op or a static key check,
733 so will have a negligible performance impact w    733 so will have a negligible performance impact when no test is running.
734                                                   734 
735 The example below uses this to implement a "mo    735 The example below uses this to implement a "mock" implementation of a function, ``foo``:
736                                                   736 
737 .. code-block:: c                                 737 .. code-block:: c
738                                                   738 
739         #include <kunit/test-bug.h> /* for kun    739         #include <kunit/test-bug.h> /* for kunit_get_current_test */
740                                                   740 
741         struct test_data {                        741         struct test_data {
742                 int foo_result;                   742                 int foo_result;
743                 int want_foo_called_with;         743                 int want_foo_called_with;
744         };                                        744         };
745                                                   745 
746         static int fake_foo(int arg)              746         static int fake_foo(int arg)
747         {                                         747         {
748                 struct kunit *test = kunit_get    748                 struct kunit *test = kunit_get_current_test();
749                 struct test_data *test_data =     749                 struct test_data *test_data = test->priv;
750                                                   750 
751                 KUNIT_EXPECT_EQ(test, test_dat    751                 KUNIT_EXPECT_EQ(test, test_data->want_foo_called_with, arg);
752                 return test_data->foo_result;     752                 return test_data->foo_result;
753         }                                         753         }
754                                                   754 
755         static void example_simple_test(struct    755         static void example_simple_test(struct kunit *test)
756         {                                         756         {
757                 /* Assume priv (private, a mem    757                 /* Assume priv (private, a member used to pass test data from
758                  * the init function) is alloc    758                  * the init function) is allocated in the suite's .init */
759                 struct test_data *test_data =     759                 struct test_data *test_data = test->priv;
760                                                   760 
761                 test_data->foo_result = 42;       761                 test_data->foo_result = 42;
762                 test_data->want_foo_called_wit    762                 test_data->want_foo_called_with = 1;
763                                                   763 
764                 /* In a real test, we'd probab    764                 /* In a real test, we'd probably pass a pointer to fake_foo somewhere
765                  * like an ops struct, etc. in    765                  * like an ops struct, etc. instead of calling it directly. */
766                 KUNIT_EXPECT_EQ(test, fake_foo    766                 KUNIT_EXPECT_EQ(test, fake_foo(1), 42);
767         }                                         767         }
768                                                   768 
769 In this example, we are using the ``priv`` mem    769 In this example, we are using the ``priv`` member of ``struct kunit`` as a way
770 of passing data to the test from the init func    770 of passing data to the test from the init function. In general ``priv`` is
771 pointer that can be used for any user data. Th    771 pointer that can be used for any user data. This is preferred over static
772 variables, as it avoids concurrency issues.       772 variables, as it avoids concurrency issues.
773                                                   773 
774 Had we wanted something more flexible, we coul    774 Had we wanted something more flexible, we could have used a named ``kunit_resource``.
775 Each test can have multiple resources which ha    775 Each test can have multiple resources which have string names providing the same
776 flexibility as a ``priv`` member, but also, fo    776 flexibility as a ``priv`` member, but also, for example, allowing helper
777 functions to create resources without conflict    777 functions to create resources without conflicting with each other. It is also
778 possible to define a clean up function for eac    778 possible to define a clean up function for each resource, making it easy to
779 avoid resource leaks. For more information, se    779 avoid resource leaks. For more information, see Documentation/dev-tools/kunit/api/resource.rst.
780                                                   780 
781 Failing The Current Test                          781 Failing The Current Test
782 ------------------------                          782 ------------------------
783                                                   783 
784 If we want to fail the current test, we can us    784 If we want to fail the current test, we can use ``kunit_fail_current_test(fmt, args...)``
785 which is defined in ``<kunit/test-bug.h>`` and    785 which is defined in ``<kunit/test-bug.h>`` and does not require pulling in ``<kunit/test.h>``.
786 For example, we have an option to enable some     786 For example, we have an option to enable some extra debug checks on some data
787 structures as shown below:                        787 structures as shown below:
788                                                   788 
789 .. code-block:: c                                 789 .. code-block:: c
790                                                   790 
791         #include <kunit/test-bug.h>               791         #include <kunit/test-bug.h>
792                                                   792 
793         #ifdef CONFIG_EXTRA_DEBUG_CHECKS          793         #ifdef CONFIG_EXTRA_DEBUG_CHECKS
794         static void validate_my_data(struct da    794         static void validate_my_data(struct data *data)
795         {                                         795         {
796                 if (is_valid(data))               796                 if (is_valid(data))
797                         return;                   797                         return;
798                                                   798 
799                 kunit_fail_current_test("data     799                 kunit_fail_current_test("data %p is invalid", data);
800                                                   800 
801                 /* Normal, non-KUnit, error re    801                 /* Normal, non-KUnit, error reporting code here. */
802         }                                         802         }
803         #else                                     803         #else
804         static void my_debug_function(void) {     804         static void my_debug_function(void) { }
805         #endif                                    805         #endif
806                                                   806 
807 ``kunit_fail_current_test()`` is safe to call     807 ``kunit_fail_current_test()`` is safe to call even if KUnit is not enabled. If
808 KUnit is not enabled, or if no test is running    808 KUnit is not enabled, or if no test is running in the current task, it will do
809 nothing. This compiles down to either a no-op     809 nothing. This compiles down to either a no-op or a static key check, so will
810 have a negligible performance impact when no t    810 have a negligible performance impact when no test is running.
811                                                   811 
812 Managing Fake Devices and Drivers                 812 Managing Fake Devices and Drivers
813 ---------------------------------                 813 ---------------------------------
814                                                   814 
815 When testing drivers or code which interacts w    815 When testing drivers or code which interacts with drivers, many functions will
816 require a ``struct device`` or ``struct device    816 require a ``struct device`` or ``struct device_driver``. In many cases, setting
817 up a real device is not required to test any g    817 up a real device is not required to test any given function, so a fake device
818 can be used instead.                              818 can be used instead.
819                                                   819 
820 KUnit provides helper functions to create and     820 KUnit provides helper functions to create and manage these fake devices, which
821 are internally of type ``struct kunit_device``    821 are internally of type ``struct kunit_device``, and are attached to a special
822 ``kunit_bus``. These devices support managed d    822 ``kunit_bus``. These devices support managed device resources (devres), as
823 described in Documentation/driver-api/driver-m    823 described in Documentation/driver-api/driver-model/devres.rst
824                                                   824 
825 To create a KUnit-managed ``struct device_driv    825 To create a KUnit-managed ``struct device_driver``, use ``kunit_driver_create()``,
826 which will create a driver with the given name    826 which will create a driver with the given name, on the ``kunit_bus``. This driver
827 will automatically be destroyed when the corre    827 will automatically be destroyed when the corresponding test finishes, but can also
828 be manually destroyed with ``driver_unregister    828 be manually destroyed with ``driver_unregister()``.
829                                                   829 
830 To create a fake device, use the ``kunit_devic    830 To create a fake device, use the ``kunit_device_register()``, which will create
831 and register a device, using a new KUnit-manag    831 and register a device, using a new KUnit-managed driver created with ``kunit_driver_create()``.
832 To provide a specific, non-KUnit-managed drive    832 To provide a specific, non-KUnit-managed driver, use ``kunit_device_register_with_driver()``
833 instead. Like with managed drivers, KUnit-mana    833 instead. Like with managed drivers, KUnit-managed fake devices are automatically
834 cleaned up when the test finishes, but can be     834 cleaned up when the test finishes, but can be manually cleaned up early with
835 ``kunit_device_unregister()``.                    835 ``kunit_device_unregister()``.
836                                                   836 
837 The KUnit devices should be used in preference    837 The KUnit devices should be used in preference to ``root_device_register()``, and
838 instead of ``platform_device_register()`` in c    838 instead of ``platform_device_register()`` in cases where the device is not otherwise
839 a platform device.                                839 a platform device.
840                                                   840 
841 For example:                                      841 For example:
842                                                   842 
843 .. code-block:: c                                 843 .. code-block:: c
844                                                   844 
845         #include <kunit/device.h>                 845         #include <kunit/device.h>
846                                                   846 
847         static void test_my_device(struct kuni    847         static void test_my_device(struct kunit *test)
848         {                                         848         {
849                 struct device *fake_device;       849                 struct device *fake_device;
850                 const char *dev_managed_string    850                 const char *dev_managed_string;
851                                                   851 
852                 // Create a fake device.          852                 // Create a fake device.
853                 fake_device = kunit_device_reg    853                 fake_device = kunit_device_register(test, "my_device");
854                 KUNIT_ASSERT_NOT_ERR_OR_NULL(t    854                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fake_device)
855                                                   855 
856                 // Pass it to functions which     856                 // Pass it to functions which need a device.
857                 dev_managed_string = devm_kstr    857                 dev_managed_string = devm_kstrdup(fake_device, "Hello, World!");
858                                                   858 
859                 // Everything is cleaned up au    859                 // Everything is cleaned up automatically when the test ends.
860         }                                         860         }
                                                      

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php