.. SPDX-License-Identifier: GPL-2.0 Writing Tests============= Test Cases---------- The fundamental unit in KUnit is the test case. A test case is a function withthe signature ``void (*)(struct kunit *test)``. It calls the function under testand then sets *expectations* for what should happen. For example: .. code-block:: c void example_test_success(struct kunit *test) { } void example_test_failure(struct kunit *test) { KUNIT_FAIL(test, "This test never passes."); } In the above example, ``example_test_success`` always passes because it doesnothing; no expectations are set, and therefore all expectations pass. On theother hand ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``,which is a special expectation that logs a message and causes the test case tofail. Expectations~~~~~~~~~~~~An *expectation* specifies that we expect a piece of code to do something in atest. An expectation is called like a function. A test is made by settingexpectations about the behavior of a piece of code under test. When one or moreexpectations fail, the test case fails and information about the failure islogged. For example: .. code-block:: c void add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } In the above example, ``add_test_basic`` makes a number of assertions about thebehavior of a function called ``add``. The first parameter is always of type``struct kunit *``, which contains information about the current test context.The second parameter, in this case, is what the value is expected to be. Thelast value is what the value actually is. If ``add`` passes all of theseexpectations, the test case, ``add_test_basic`` will pass; if any one of theseexpectations fails, the test case will fail. A test case *fails* when any expectation is violated; however, the test willcontinue to run, and try other expectations until the test case ends or isotherwise terminated. This is as opposed to *assertions* which are discussedlater. To learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst. .. note:: A single test case should be short, easy to understand, and focused on a single behavior. For example, if we want to rigorously test the ``add`` function above, createadditional tests cases which would test each property that an ``add`` functionshould have as shown below: .. code-block:: c void add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } void add_test_negative(struct kunit *test) { KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); } void add_test_max(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); } void add_test_overflow(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1)); } Assertions~~~~~~~~~~ An assertion is like an expectation, except that the assertion immediatelyterminates the test case if the condition is not satisfied. For example: .. code-block:: c static void test_sort(struct kunit *test) { int *a, i, r = 1; a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a); for (i = 0; i < TEST_LEN; i++) { r = (r * 725861) % 6599; a[i] = r; } sort(a, TEST_LEN, sizeof(*a), cmpint, NULL); for (i = 0; i < TEST_LEN-1; i++) KUNIT_EXPECT_LE(test, a[i], a[i + 1]); } In this example, we need to be able to allocate an array to test the ``sort()``function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_NULL()`` to abort the test ifthere's an allocation error. .. note:: In other test frameworks, ``ASSERT`` macros are often implemented by calling ``return`` so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere. .. note:: Warning: There is an exception to the above rule. You shouldn't use assertions in the suite's exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak. Customizing error messages-------------------------- Each of the ``KUNIT_EXPECT`` and ``KUNIT_ASSERT`` macros have a ``_MSG``variant. These take a format string and arguments to provide additionalcontext to the automatically generated error messages. .. code-block:: c char some_str[41]; generate_sha1_hex_string(some_str); /* Before. Not easy to tell why the test failed. */ KUNIT_EXPECT_EQ(test, strlen(some_str), 40); /* After. Now we see the offending string. */ KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str); Alternatively, one can take full control over the error message by using``KUNIT_FAIL()``, e.g. .. code-block:: c /* Before */ KUNIT_EXPECT_EQ(test, some_setup_function(), 0); /* After: full control over the failure message. */ if (some_setup_function()) KUNIT_FAIL(test, "Failed to setup thing for testing"); Suppressing warning backtraces------------------------------ Some unit tests trigger warning backtraces either intentionally or as a sideeffect. Such backtraces are normally undesirable since they distract fromthe actual test and may result in the impression that there is a problem. Backtraces can be suppressed with **task-scoped suppression**: whilesuppression is active on the current task, the backtrace and stack dump from``WARN*()``, ``WARN_ON*()``, and related macros on that task are suppressed.Two API forms are available. - Scoped suppression is the simplest form. Wrap the code that triggers warnings in a ``kunit_warning_suppress()`` block: .. code-block:: c static void some_test(struct kunit *test) { kunit_warning_suppress(test) { trigger_backtrace(); KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 1); } } .. note:: The warning count must be checked inside the block; the suppression handle is not accessible after the block exits. - Direct functions return an explicit handle pointer. Use them when the handle needs to be retained or passed across helper functions: .. code-block:: c static void some_test(struct kunit *test) { struct kunit_suppressed_warning *w; w = kunit_start_suppress_warning(test); trigger_backtrace(); kunit_end_suppress_warning(test, w); KUNIT_EXPECT_EQ(test, kunit_suppressed_warning_count(w), 1); } Test Suites~~~~~~~~~~~ We need many test cases covering all the unit's behaviors. It is common to havemany similar tests. In order to reduce duplication in these closely relatedtests, most unit testing frameworks (including KUnit) provide the concept of a*test suite*. A test suite is a collection of test cases for a unit of codewith optional setup and teardown functions that run before/after the wholesuite and/or every test case. .. note:: A test case will only run if it is associated with a test suite. For example: .. code-block:: c static struct kunit_case example_test_cases[] = { KUNIT_CASE(example_test_foo), KUNIT_CASE(example_test_bar), KUNIT_CASE(example_test_baz), {} }; static struct kunit_suite example_test_suite = { .name = "example", .init = example_test_init, .exit = example_test_exit, .suite_init = example_suite_init, .suite_exit = example_suite_exit, .test_cases = example_test_cases, }; kunit_test_suite(example_test_suite); In the above example, the test suite ``example_test_suite`` would first run``example_suite_init``, then run the test cases ``example_test_foo``,``example_test_bar``, and ``example_test_baz``. Each would have``example_test_init`` called immediately before it and ``example_test_exit``called immediately after it. Finally, ``example_suite_exit`` would be calledafter everything else. ``kunit_test_suite(example_test_suite)`` registers thetest suite with the KUnit test framework. .. note:: The ``exit`` and ``suite_exit`` functions will run even if ``init`` or ``suite_init`` fail. Make sure that they can handle any inconsistent state which may result from ``init`` or ``suite_init`` encountering errors or exiting early. ``kunit_test_suite(...)`` is a macro which tells the linker to put thespecified test suite in a special linker section so that it can be run by KUniteither after ``late_init``, or when the test module is loaded (if the test wasbuilt as a module). For more information, see Documentation/dev-tools/kunit/api/test.rst. .. _kunit-on-non-uml: Writing Tests For Other Architectures------------------------------------- It is better to write tests that run on UML to tests that only run under aparticular architecture. It is better to write tests that run under QEMU oranother easy to obtain (and monetarily free) software environment to a specificpiece of hardware. Nevertheless, there are still valid reasons to write a test that is architectureor hardware specific. For example, we might want to test code that reallybelongs in ``arch/some-arch/*``. Even so, try to write the test so that it doesnot depend on physical hardware. Some of our test cases may not need hardware,only few tests actually require the hardware to test it. When hardware is notavailable, instead of disabling tests, we can skip them. Now that we have narrowed down exactly what bits are hardware specific, theactual procedure for writing and running the tests is same as writing normalKUnit tests. .. important:: We may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation. .. TODO(brendanhiggins@google.com): Add an actual example of an architecture- dependent KUnit test. Common Patterns=============== Isolating Behavior------------------ Unit testing limits the amount of code under test to a single unit. It controlswhat code gets run when the unit under test calls a function. Where a functionis exposed as part of an API such that the definition of that function can bechanged without affecting the rest of the code base. In the kernel, this comesfrom two constructs: classes, which are structs that contain function pointersprovided by the implementer, and architecture-specific functions, which havedefinitions selected at compile time. Classes~~~~~~~ Classes are not a construct that is built into the C programming language;however, it is an easily derived concept. Accordingly, in most cases, everyproject that does not use a standardized object oriented library (like GNOME'sGObject) has their own slightly different way of doing object orientedprogramming; the Linux kernel is no exception. The central concept in kernel object oriented programming is the class. In thekernel, a *class* is a struct that contains function pointers. This creates acontract between *implementers* and *users* since it forces them to use thesame function signature without having to call the function directly. To be aclass, the function pointers must specify that a pointer to the class, known asa *class handle*, be one of the parameters. Thus the member functions (alsoknown as *methods*) have access to member variables (also known as *fields*)allowing the same implementation to have multiple *instances*. A class can be *overridden* by *child classes* by embedding the *parent class*in the child class. Then when the child class *method* is called, the childimplementation knows that the pointer passed to it is of a parent containedwithin the child. Thus, the child can compute the pointer to itself because thepointer to the parent is always a fixed offset from the pointer to the child.This offset is the offset of the parent contained in the child struct. Forexample: .. code-block:: c struct shape { int (*area)(struct shape *this); }; struct rectangle { struct shape parent; int length; int width; }; int rectangle_area(struct shape *this) { struct rectangle *self = container_of(this, struct rectangle, parent); return self->length * self->width; }; void rectangle_new(struct rectangle *self, int length, int width) { self->parent.area = rectangle_area; self->length = length; self->width = width; } In this example, computing the pointer to the child from the pointer to theparent is done by ``container_of``. Faking Classes~~~~~~~~~~~~~~ In order to unit test a piece of code that calls a method in a class, thebehavior of the method must be controllable, otherwise the test ceases to be aunit test and becomes an integration test. A fake class implements a piece of code that is different than what runs in aproduction instance, but behaves identical from the standpoint of the callers.This is done to replace a dependency that is hard to deal with, or is slow. Forexample, implementing a fake EEPROM that stores the "contents" in aninternal buffer. Assume we have a class that represents an EEPROM: .. code-block:: c struct eeprom { ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count); ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count); }; And we want to test code that buffers writes to the EEPROM: .. code-block:: c struct eeprom_buffer { ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count); int flush(struct eeprom_buffer *this); size_t flush_count; /* Flushes when buffer exceeds flush_count. */ }; struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom); void destroy_eeprom_buffer(struct eeprom *eeprom); We can test this code by *faking out* the underlying EEPROM: .. code-block:: c struct fake_eeprom { struct eeprom parent; char contents[FAKE_EEPROM_CONTENTS_SIZE]; }; ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(buffer, this->contents + offset, count); return count; } ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(this->contents + offset, buffer, count); return count; } void fake_eeprom_init(struct fake_eeprom *this) { this->parent.read = fake_eeprom_read; this->parent.write = fake_eeprom_write; memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE); } We can now use it to test ``struct eeprom_buffer``: .. code-block:: c struct eeprom_buffer_test { struct fake_eeprom *fake_eeprom; struct eeprom_buffer *eeprom_buffer; }; static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = SIZE_MAX; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0); eeprom_buffer->flush(eeprom_buffer); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff, 0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 2); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); /* Should have only flushed the first two bytes. */ KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0); } static int eeprom_buffer_test_init(struct kunit *test) { struct eeprom_buffer_test *ctx; ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom); fake_eeprom_init(ctx->fake_eeprom);Lines 1–500 of 1258. Load more
.. SPDX-License-Identifier: GPL-2.0 Writing Tests ============= Test Cases ---------- The fundamental unit in KUnit is the test case. A test case is a function with the signature ``void (*)(struct kunit *test)``. It calls the function under test and then sets *expectations* for what should happen. For example: .. code-block:: c void example_test_success(struct kunit *test) { } void example_test_failure(struct kunit *test) { KUNIT_FAIL(test, "This test never passes."); } In the above example, ``example_test_success`` always passes because it does nothing; no expectations are set, and therefore all expectations pass. On the other hand ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``, which is a special expectation that logs a message and causes the test case to fail. Expectations ~~~~~~~~~~~~ An *expectation* specifies that we expect a piece of code to do something in a test. An expectation is called like a function. A test is made by setting expectations about the behavior of a piece of code under test. When one or more expectations fail, the test case fails and information about the failure is logged. For example: .. code-block:: c void add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } In the above example, ``add_test_basic`` makes a number of assertions about the behavior of a function called ``add``. The first parameter is always of type ``struct kunit *``, which contains information about the current test context. The second parameter, in this case, is what the value is expected to be. The last value is what the value actually is. If ``add`` passes all of these expectations, the test case, ``add_test_basic`` will pass; if any one of these expectations fails, the test case will fail. A test case *fails* when any expectation is violated; however, the test will continue to run, and try other expectations until the test case ends or is otherwise terminated. This is as opposed to *assertions* which are discussed later. To learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst. .. note:: A single test case should be short, easy to understand, and focused on a single behavior. For example, if we want to rigorously test the ``add`` function above, create additional tests cases which would test each property that an ``add`` function should have as shown below: .. code-block:: c void add_test_basic(struct kunit *test) { KUNIT_EXPECT_EQ(test, 1, add(1, 0)); KUNIT_EXPECT_EQ(test, 2, add(1, 1)); } void add_test_negative(struct kunit *test) { KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); } void add_test_max(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); } void add_test_overflow(struct kunit *test) { KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1)); } Assertions ~~~~~~~~~~ An assertion is like an expectation, except that the assertion immediately terminates the test case if the condition is not satisfied. For example: .. code-block:: c static void test_sort(struct kunit *test) { int *a, i, r = 1; a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a); for (i = 0; i < TEST_LEN; i++) { r = (r * 725861) % 6599; a[i] = r; } sort(a, TEST_LEN, sizeof(*a), cmpint, NULL); for (i = 0; i < TEST_LEN-1; i++) KUNIT_EXPECT_LE(test, a[i], a[i + 1]); } In this example, we need to be able to allocate an array to test the ``sort()`` function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_NULL()`` to abort the test if there's an allocation error. .. note:: In other test frameworks, ``ASSERT`` macros are often implemented by calling ``return`` so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere. .. note:: Warning: There is an exception to the above rule. You shouldn't use assertions in the suite's exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak. Customizing error messages -------------------------- Each of the ``KUNIT_EXPECT`` and ``KUNIT_ASSERT`` macros have a ``_MSG`` variant. These take a format string and arguments to provide additional context to the automatically generated error messages. .. code-block:: c char some_str[41]; generate_sha1_hex_string(some_str); /* Before. Not easy to tell why the test failed. */ KUNIT_EXPECT_EQ(test, strlen(some_str), 40); /* After. Now we see the offending string. */ KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str); Alternatively, one can take full control over the error message by using ``KUNIT_FAIL()``, e.g. .. code-block:: c /* Before */ KUNIT_EXPECT_EQ(test, some_setup_function(), 0); /* After: full control over the failure message. */ if (some_setup_function()) KUNIT_FAIL(test, "Failed to setup thing for testing"); Suppressing warning backtraces ------------------------------ Some unit tests trigger warning backtraces either intentionally or as a side effect. Such backtraces are normally undesirable since they distract from the actual test and may result in the impression that there is a problem. Backtraces can be suppressed with **task-scoped suppression**: while suppression is active on the current task, the backtrace and stack dump from ``WARN*()``, ``WARN_ON*()``, and related macros on that task are suppressed. Two API forms are available. - Scoped suppression is the simplest form. Wrap the code that triggers warnings in a ``kunit_warning_suppress()`` block: .. code-block:: c static void some_test(struct kunit *test) { kunit_warning_suppress(test) { trigger_backtrace(); KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 1); } } .. note:: The warning count must be checked inside the block; the suppression handle is not accessible after the block exits. - Direct functions return an explicit handle pointer. Use them when the handle needs to be retained or passed across helper functions: .. code-block:: c static void some_test(struct kunit *test) { struct kunit_suppressed_warning *w; w = kunit_start_suppress_warning(test); trigger_backtrace(); kunit_end_suppress_warning(test, w); KUNIT_EXPECT_EQ(test, kunit_suppressed_warning_count(w), 1); } Test Suites ~~~~~~~~~~~ We need many test cases covering all the unit's behaviors. It is common to have many similar tests. In order to reduce duplication in these closely related tests, most unit testing frameworks (including KUnit) provide the concept of a *test suite*. A test suite is a collection of test cases for a unit of code with optional setup and teardown functions that run before/after the whole suite and/or every test case. .. note:: A test case will only run if it is associated with a test suite. For example: .. code-block:: c static struct kunit_case example_test_cases[] = { KUNIT_CASE(example_test_foo), KUNIT_CASE(example_test_bar), KUNIT_CASE(example_test_baz), {} }; static struct kunit_suite example_test_suite = { .name = "example", .init = example_test_init, .exit = example_test_exit, .suite_init = example_suite_init, .suite_exit = example_suite_exit, .test_cases = example_test_cases, }; kunit_test_suite(example_test_suite); In the above example, the test suite ``example_test_suite`` would first run ``example_suite_init``, then run the test cases ``example_test_foo``, ``example_test_bar``, and ``example_test_baz``. Each would have ``example_test_init`` called immediately before it and ``example_test_exit`` called immediately after it. Finally, ``example_suite_exit`` would be called after everything else. ``kunit_test_suite(example_test_suite)`` registers the test suite with the KUnit test framework. .. note:: The ``exit`` and ``suite_exit`` functions will run even if ``init`` or ``suite_init`` fail. Make sure that they can handle any inconsistent state which may result from ``init`` or ``suite_init`` encountering errors or exiting early. ``kunit_test_suite(...)`` is a macro which tells the linker to put the specified test suite in a special linker section so that it can be run by KUnit either after ``late_init``, or when the test module is loaded (if the test was built as a module). For more information, see Documentation/dev-tools/kunit/api/test.rst. .. _kunit-on-non-uml: Writing Tests For Other Architectures ------------------------------------- It is better to write tests that run on UML to tests that only run under a particular architecture. It is better to write tests that run under QEMU or another easy to obtain (and monetarily free) software environment to a specific piece of hardware. Nevertheless, there are still valid reasons to write a test that is architecture or hardware specific. For example, we might want to test code that really belongs in ``arch/some-arch/*``. Even so, try to write the test so that it does not depend on physical hardware. Some of our test cases may not need hardware, only few tests actually require the hardware to test it. When hardware is not available, instead of disabling tests, we can skip them. Now that we have narrowed down exactly what bits are hardware specific, the actual procedure for writing and running the tests is same as writing normal KUnit tests. .. important:: We may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation. .. TODO(brendanhiggins@google.com): Add an actual example of an architecture- dependent KUnit test. Common Patterns =============== Isolating Behavior ------------------ Unit testing limits the amount of code under test to a single unit. It controls what code gets run when the unit under test calls a function. Where a function is exposed as part of an API such that the definition of that function can be changed without affecting the rest of the code base. In the kernel, this comes from two constructs: classes, which are structs that contain function pointers provided by the implementer, and architecture-specific functions, which have definitions selected at compile time. Classes ~~~~~~~ Classes are not a construct that is built into the C programming language; however, it is an easily derived concept. Accordingly, in most cases, every project that does not use a standardized object oriented library (like GNOME's GObject) has their own slightly different way of doing object oriented programming; the Linux kernel is no exception. The central concept in kernel object oriented programming is the class. In the kernel, a *class* is a struct that contains function pointers. This creates a contract between *implementers* and *users* since it forces them to use the same function signature without having to call the function directly. To be a class, the function pointers must specify that a pointer to the class, known as a *class handle*, be one of the parameters. Thus the member functions (also known as *methods*) have access to member variables (also known as *fields*) allowing the same implementation to have multiple *instances*. A class can be *overridden* by *child classes* by embedding the *parent class* in the child class. Then when the child class *method* is called, the child implementation knows that the pointer passed to it is of a parent contained within the child. Thus, the child can compute the pointer to itself because the pointer to the parent is always a fixed offset from the pointer to the child. This offset is the offset of the parent contained in the child struct. For example: .. code-block:: c struct shape { int (*area)(struct shape *this); }; struct rectangle { struct shape parent; int length; int width; }; int rectangle_area(struct shape *this) { struct rectangle *self = container_of(this, struct rectangle, parent); return self->length * self->width; }; void rectangle_new(struct rectangle *self, int length, int width) { self->parent.area = rectangle_area; self->length = length; self->width = width; } In this example, computing the pointer to the child from the pointer to the parent is done by ``container_of``. Faking Classes ~~~~~~~~~~~~~~ In order to unit test a piece of code that calls a method in a class, the behavior of the method must be controllable, otherwise the test ceases to be a unit test and becomes an integration test. A fake class implements a piece of code that is different than what runs in a production instance, but behaves identical from the standpoint of the callers. This is done to replace a dependency that is hard to deal with, or is slow. For example, implementing a fake EEPROM that stores the "contents" in an internal buffer. Assume we have a class that represents an EEPROM: .. code-block:: c struct eeprom { ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count); ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count); }; And we want to test code that buffers writes to the EEPROM: .. code-block:: c struct eeprom_buffer { ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count); int flush(struct eeprom_buffer *this); size_t flush_count; /* Flushes when buffer exceeds flush_count. */ }; struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom); void destroy_eeprom_buffer(struct eeprom *eeprom); We can test this code by *faking out* the underlying EEPROM: .. code-block:: c struct fake_eeprom { struct eeprom parent; char contents[FAKE_EEPROM_CONTENTS_SIZE]; }; ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(buffer, this->contents + offset, count); return count; } ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count) { struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); memcpy(this->contents + offset, buffer, count); return count; } void fake_eeprom_init(struct fake_eeprom *this) { this->parent.read = fake_eeprom_read; this->parent.write = fake_eeprom_write; memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE); } We can now use it to test ``struct eeprom_buffer``: .. code-block:: c struct eeprom_buffer_test { struct fake_eeprom *fake_eeprom; struct eeprom_buffer *eeprom_buffer; }; static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = SIZE_MAX; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0); eeprom_buffer->flush(eeprom_buffer); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); } static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test) { struct eeprom_buffer_test *ctx = test->priv; struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; char buffer[] = {0xff, 0xff}; eeprom_buffer->flush_count = 2; eeprom_buffer->write(eeprom_buffer, buffer, 1); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); eeprom_buffer->write(eeprom_buffer, buffer, 2); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); /* Should have only flushed the first two bytes. */ KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0); } static int eeprom_buffer_test_init(struct kunit *test) { struct eeprom_buffer_test *ctx; ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom); fake_eeprom_init(ctx->fake_eeprom);