1 .. SPDX-License-Identifier: GPL-2.0
7 The purpose of this document is to describe what KUnit is, how it works, how it
8 is intended to be used, and all the concepts and terminology that are needed to
9 understand it. This guide assumes a working knowledge of the Linux kernel and
10 some basic knowledge of testing.
12 For a high level introduction to KUnit, including setting up KUnit for your
13 project, see :doc:`start`.
15 Organization of this document
16 =============================
18 This document is organized into two main sections: Testing and Isolating
19 Behavior. The first covers what unit tests are and how to use KUnit to write
20 them. The second covers how to use KUnit to isolate code and make it possible
21 to unit test code that was otherwise un-unit-testable.
29 "K" is short for "kernel" so "KUnit" is the "(Linux) Kernel Unit Testing
30 Framework." KUnit is intended first and foremost for writing unit tests; it is
31 general enough that it can be used to write integration tests; however, this is
32 a secondary goal. KUnit has no ambition of being the only testing framework for
33 the kernel; for example, it does not intend to be an end-to-end testing
39 A `unit test <https://martinfowler.com/bliki/UnitTest.html>`_ is a test that
40 tests code at the smallest possible scope, a *unit* of code. In the C
41 programming language that's a function.
43 Unit tests should be written for all the publicly exposed functions in a
44 compilation unit; so that is all the functions that are exported in either a
45 *class* (defined below) or all functions which are **not** static.
53 The fundamental unit in KUnit is the test case. A test case is a function with
54 the signature ``void (*)(struct kunit *test)``. It calls a function to be tested
55 and then sets *expectations* for what should happen. For example:
59 void example_test_success(struct kunit *test)
63 void example_test_failure(struct kunit *test)
65 KUNIT_FAIL(test, "This test never passes.");
68 In the above example ``example_test_success`` always passes because it does
69 nothing; no expectations are set, so all expectations pass. On the other hand
70 ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``, which is
71 a special expectation that logs a message and causes the test case to fail.
75 An *expectation* is a way to specify that you expect a piece of code to do
76 something in a test. An expectation is called like a function. A test is made
77 by setting expectations about the behavior of a piece of code under test; when
78 one or more of the expectations fail, the test case fails and information about
79 the failure is logged. For example:
83 void add_test_basic(struct kunit *test)
85 KUNIT_EXPECT_EQ(test, 1, add(1, 0));
86 KUNIT_EXPECT_EQ(test, 2, add(1, 1));
89 In the above example ``add_test_basic`` makes a number of assertions about the
90 behavior of a function called ``add``; the first parameter is always of type
91 ``struct kunit *``, which contains information about the current test context;
92 the second parameter, in this case, is what the value is expected to be; the
93 last value is what the value actually is. If ``add`` passes all of these
94 expectations, the test case, ``add_test_basic`` will pass; if any one of these
95 expectations fail, the test case will fail.
97 It is important to understand that a test case *fails* when any expectation is
98 violated; however, the test will continue running, potentially trying other
99 expectations until the test case ends or is otherwise terminated. This is as
100 opposed to *assertions* which are discussed later.
102 To learn about more expectations supported by KUnit, see :doc:`api/test`.
105 A single test case should be pretty short, pretty easy to understand,
106 focused on a single behavior.
108 For example, if we wanted to properly test the add function above, we would
109 create additional tests cases which would each test a different property that an
110 add function should have like this:
114 void add_test_basic(struct kunit *test)
116 KUNIT_EXPECT_EQ(test, 1, add(1, 0));
117 KUNIT_EXPECT_EQ(test, 2, add(1, 1));
120 void add_test_negative(struct kunit *test)
122 KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
125 void add_test_max(struct kunit *test)
127 KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
128 KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
131 void add_test_overflow(struct kunit *test)
133 KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1));
136 Notice how it is immediately obvious what all the properties that we are testing
142 KUnit also has the concept of an *assertion*. An assertion is just like an
143 expectation except the assertion immediately terminates the test case if it is
150 static void mock_test_do_expect_default_return(struct kunit *test)
152 struct mock_test_context *ctx = test->priv;
153 struct mock *mock = ctx->mock;
154 int param0 = 5, param1 = -5;
155 const char *two_param_types[] = {"int", "int"};
156 const void *two_params[] = {¶m0, ¶m1};
159 ret = mock->do_expect(mock,
160 "test_printk", test_printk,
161 two_param_types, two_params,
162 ARRAY_SIZE(two_params));
163 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ret);
164 KUNIT_EXPECT_EQ(test, -4, *((int *) ret));
167 In this example, the method under test should return a pointer to a value, so
168 if the pointer returned by the method is null or an errno, we don't want to
169 bother continuing the test since the following expectation could crash the test
170 case. `ASSERT_NOT_ERR_OR_NULL(...)` allows us to bail out of the test case if
171 the appropriate conditions have not been satisfied to complete the test.
176 Now obviously one unit test isn't very helpful; the power comes from having
177 many test cases covering all of a unit's behaviors. Consequently it is common
178 to have many *similar* tests; in order to reduce duplication in these closely
179 related tests most unit testing frameworks - including KUnit - provide the
180 concept of a *test suite*. A *test suite* is just a collection of test cases
181 for a unit of code with a set up function that gets invoked before every test
182 case and then a tear down function that gets invoked after every test case
189 static struct kunit_case example_test_cases[] = {
190 KUNIT_CASE(example_test_foo),
191 KUNIT_CASE(example_test_bar),
192 KUNIT_CASE(example_test_baz),
196 static struct kunit_suite example_test_suite = {
198 .init = example_test_init,
199 .exit = example_test_exit,
200 .test_cases = example_test_cases,
202 kunit_test_suite(example_test_suite);
204 In the above example the test suite, ``example_test_suite``, would run the test
205 cases ``example_test_foo``, ``example_test_bar``, and ``example_test_baz``,
206 each would have ``example_test_init`` called immediately before it and would
207 have ``example_test_exit`` called immediately after it.
208 ``kunit_test_suite(example_test_suite)`` registers the test suite with the
209 KUnit test framework.
212 A test case will only be run if it is associated with a test suite.
214 For more information on these types of things see the :doc:`api/test`.
219 The most important aspect of unit testing that other forms of testing do not
220 provide is the ability to limit the amount of code under test to a single unit.
221 In practice, this is only possible by being able to control what code gets run
222 when the unit under test calls a function and this is usually accomplished
223 through some sort of indirection where a function is exposed as part of an API
224 such that the definition of that function can be changed without affecting the
225 rest of the code base. In the kernel this primarily comes from two constructs,
226 classes, structs that contain function pointers that are provided by the
227 implementer, and architecture specific functions which have definitions selected
233 Classes are not a construct that is built into the C programming language;
234 however, it is an easily derived concept. Accordingly, pretty much every project
235 that does not use a standardized object oriented library (like GNOME's GObject)
236 has their own slightly different way of doing object oriented programming; the
237 Linux kernel is no exception.
239 The central concept in kernel object oriented programming is the class. In the
240 kernel, a *class* is a struct that contains function pointers. This creates a
241 contract between *implementers* and *users* since it forces them to use the
242 same function signature without having to call the function directly. In order
243 for it to truly be a class, the function pointers must specify that a pointer
244 to the class, known as a *class handle*, be one of the parameters; this makes
245 it possible for the member functions (also known as *methods*) to have access
246 to member variables (more commonly known as *fields*) allowing the same
247 implementation to have multiple *instances*.
249 Typically a class can be *overridden* by *child classes* by embedding the
250 *parent class* in the child class. Then when a method provided by the child
251 class is called, the child implementation knows that the pointer passed to it is
252 of a parent contained within the child; because of this, the child can compute
253 the pointer to itself because the pointer to the parent is always a fixed offset
254 from the pointer to the child; this offset is the offset of the parent contained
255 in the child struct. For example:
260 int (*area)(struct shape *this);
269 int rectangle_area(struct shape *this)
271 struct rectangle *self = container_of(this, struct shape, parent);
273 return self->length * self->width;
276 void rectangle_new(struct rectangle *self, int length, int width)
278 self->parent.area = rectangle_area;
279 self->length = length;
283 In this example (as in most kernel code) the operation of computing the pointer
284 to the child from the pointer to the parent is done by ``container_of``.
289 In order to unit test a piece of code that calls a method in a class, the
290 behavior of the method must be controllable, otherwise the test ceases to be a
291 unit test and becomes an integration test.
293 A fake just provides an implementation of a piece of code that is different than
294 what runs in a production instance, but behaves identically from the standpoint
295 of the callers; this is usually done to replace a dependency that is hard to
296 deal with, or is slow.
298 A good example for this might be implementing a fake EEPROM that just stores the
299 "contents" in an internal buffer. For example, let's assume we have a class that
300 represents an EEPROM:
305 ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count);
306 ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count);
309 And we want to test some code that buffers writes to the EEPROM:
313 struct eeprom_buffer {
314 ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count);
315 int flush(struct eeprom_buffer *this);
316 size_t flush_count; /* Flushes when buffer exceeds flush_count. */
319 struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom);
320 void destroy_eeprom_buffer(struct eeprom *eeprom);
322 We can easily test this code by *faking out* the underlying EEPROM:
327 struct eeprom parent;
328 char contents[FAKE_EEPROM_CONTENTS_SIZE];
331 ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count)
333 struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
335 count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
336 memcpy(buffer, this->contents + offset, count);
341 ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count)
343 struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
345 count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
346 memcpy(this->contents + offset, buffer, count);
351 void fake_eeprom_init(struct fake_eeprom *this)
353 this->parent.read = fake_eeprom_read;
354 this->parent.write = fake_eeprom_write;
355 memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE);
358 We can now use it to test ``struct eeprom_buffer``:
362 struct eeprom_buffer_test {
363 struct fake_eeprom *fake_eeprom;
364 struct eeprom_buffer *eeprom_buffer;
367 static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test)
369 struct eeprom_buffer_test *ctx = test->priv;
370 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
371 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
372 char buffer[] = {0xff};
374 eeprom_buffer->flush_count = SIZE_MAX;
376 eeprom_buffer->write(eeprom_buffer, buffer, 1);
377 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
379 eeprom_buffer->write(eeprom_buffer, buffer, 1);
380 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0);
382 eeprom_buffer->flush(eeprom_buffer);
383 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
384 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
387 static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test)
389 struct eeprom_buffer_test *ctx = test->priv;
390 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
391 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
392 char buffer[] = {0xff};
394 eeprom_buffer->flush_count = 2;
396 eeprom_buffer->write(eeprom_buffer, buffer, 1);
397 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
399 eeprom_buffer->write(eeprom_buffer, buffer, 1);
400 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
401 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
404 static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test)
406 struct eeprom_buffer_test *ctx = test->priv;
407 struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
408 struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
409 char buffer[] = {0xff, 0xff};
411 eeprom_buffer->flush_count = 2;
413 eeprom_buffer->write(eeprom_buffer, buffer, 1);
414 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
416 eeprom_buffer->write(eeprom_buffer, buffer, 2);
417 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
418 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
419 /* Should have only flushed the first two bytes. */
420 KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0);
423 static int eeprom_buffer_test_init(struct kunit *test)
425 struct eeprom_buffer_test *ctx;
427 ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
428 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);
430 ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL);
431 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom);
432 fake_eeprom_init(ctx->fake_eeprom);
434 ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent);
435 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer);
442 static void eeprom_buffer_test_exit(struct kunit *test)
444 struct eeprom_buffer_test *ctx = test->priv;
446 destroy_eeprom_buffer(ctx->eeprom_buffer);
449 .. _kunit-on-non-uml:
451 KUnit on non-UML architectures
452 ==============================
454 By default KUnit uses UML as a way to provide dependencies for code under test.
455 Under most circumstances KUnit's usage of UML should be treated as an
456 implementation detail of how KUnit works under the hood. Nevertheless, there
457 are instances where being able to run architecture specific code or test
458 against real hardware is desirable. For these reasons KUnit supports running on
461 Running existing KUnit tests on non-UML architectures
462 -----------------------------------------------------
464 There are some special considerations when running existing KUnit tests on
465 non-UML architectures:
467 * Hardware may not be deterministic, so a test that always passes or fails
468 when run under UML may not always do so on real hardware.
469 * Hardware and VM environments may not be hermetic. KUnit tries its best to
470 provide a hermetic environment to run tests; however, it cannot manage state
471 that it doesn't know about outside of the kernel. Consequently, tests that
472 may be hermetic on UML may not be hermetic on other architectures.
473 * Some features and tooling may not be supported outside of UML.
474 * Hardware and VMs are slower than UML.
476 None of these are reasons not to run your KUnit tests on real hardware; they are
477 only things to be aware of when doing so.
479 The biggest impediment will likely be that certain KUnit features and
480 infrastructure may not support your target environment. For example, at this
481 time the KUnit Wrapper (``tools/testing/kunit/kunit.py``) does not work outside
482 of UML. Unfortunately, there is no way around this. Using UML (or even just a
483 particular architecture) allows us to make a lot of assumptions that make it
484 possible to do things which might otherwise be impossible.
486 Nevertheless, all core KUnit framework features are fully supported on all
487 architectures, and using them is straightforward: all you need to do is to take
488 your kunitconfig, your Kconfig options for the tests you would like to run, and
489 merge them into whatever config your are using for your platform. That's it!
491 For example, let's say you have the following kunitconfig:
496 CONFIG_KUNIT_EXAMPLE_TEST=y
498 If you wanted to run this test on an x86 VM, you might add the following config
499 options to your ``.config``:
504 CONFIG_KUNIT_EXAMPLE_TEST=y
506 CONFIG_SERIAL_8250_CONSOLE=y
508 All these new options do is enable support for a common serial console needed
511 Next, you could build a kernel with these tests as follows:
516 make ARCH=x86 olddefconfig
519 Once you have built a kernel, you could run it on QEMU as follows:
523 qemu-system-x86_64 -enable-kvm \
525 -kernel arch/x86_64/boot/bzImage \
526 -append 'console=ttyS0' \
529 Interspersed in the kernel logs you might see the following:
536 # example_simple_test: initializing
537 ok 1 - example_simple_test
540 Congratulations, you just ran a KUnit test on the x86 architecture!
542 In a similar manner, kunit and kunit tests can also be built as modules,
543 so if you wanted to run tests in this way you might add the following config
544 options to your ``.config``:
549 CONFIG_KUNIT_EXAMPLE_TEST=m
551 Once the kernel is built and installed, a simple
554 modprobe example-test
556 ...will run the tests.
558 Writing new tests for other architectures
559 -----------------------------------------
561 The first thing you must do is ask yourself whether it is necessary to write a
562 KUnit test for a specific architecture, and then whether it is necessary to
563 write that test for a particular piece of hardware. In general, writing a test
564 that depends on having access to a particular piece of hardware or software (not
565 included in the Linux source repo) should be avoided at all costs.
567 Even if you only ever plan on running your KUnit test on your hardware
568 configuration, other people may want to run your tests and may not have access
569 to your hardware. If you write your test to run on UML, then anyone can run your
570 tests without knowing anything about your particular setup, and you can still
571 run your tests on your hardware setup just by compiling for your architecture.
574 Always prefer tests that run on UML to tests that only run under a particular
575 architecture, and always prefer tests that run under QEMU or another easy
576 (and monetarily free) to obtain software environment to a specific piece of
579 Nevertheless, there are still valid reasons to write an architecture or hardware
580 specific test: for example, you might want to test some code that really belongs
581 in ``arch/some-arch/*``. Even so, try your best to write the test so that it
582 does not depend on physical hardware: if some of your test cases don't need the
583 hardware, only require the hardware for tests that actually need it.
585 Now that you have narrowed down exactly what bits are hardware specific, the
586 actual procedure for writing and running the tests is pretty much the same as
587 writing normal KUnit tests. One special caveat is that you have to reset
588 hardware state in between test cases; if this is not possible, you may only be
589 able to run one test case per invocation.
591 .. TODO(brendanhiggins@google.com): Add an actual example of an architecture
592 dependent KUnit test.