Writing Tests

Test Cases

The fundamental unit in KUnit is the test case. A test case is a function withthe signaturevoid(*)(structkunit*test). It calls the function under testand then setsexpectations for what should happen. For example:

voidexample_test_success(structkunit*test){}voidexample_test_failure(structkunit*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 handexample_test_failure always fails because it callsKUNIT_FAIL,which is a special expectation that logs a message and causes the test case tofail.

Expectations

Anexpectation 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:

voidadd_test_basic(structkunit*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 calledadd. The first parameter is always of typestructkunit*, 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. Ifadd 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 casefails 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 toassertions which are discussedlater.

To learn about more KUnit expectations, seeTest API.

Note

A single test case should be short, easy to understand, and focused on asingle behavior.

For example, if we want to rigorously test theadd function above, createadditional tests cases which would test each property that anadd functionshould have as shown below:

voidadd_test_basic(structkunit*test){KUNIT_EXPECT_EQ(test,1,add(1,0));KUNIT_EXPECT_EQ(test,2,add(1,1));}voidadd_test_negative(structkunit*test){KUNIT_EXPECT_EQ(test,0,add(-1,1));}voidadd_test_max(structkunit*test){KUNIT_EXPECT_EQ(test,INT_MAX,add(0,INT_MAX));KUNIT_EXPECT_EQ(test,-1,add(INT_MAX,INT_MIN));}voidadd_test_overflow(structkunit*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:

staticvoidtest_sort(structkunit*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 thesort()function. So we useKUNIT_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 callingreturn so they only work from the test function. In KUnit, we stop thecurrent kthread on failure, so you can call them from anywhere.

Note

Warning: There is an exception to the above rule. You shouldn’t use assertionsin the suite’sexit() function, or in the free function for a resource. Theserun when a test is shutting down, and an assertion here prevents furthercleanup code from running, potentially leading to a memory leak.

Customizing error messages

Each of theKUNIT_EXPECT andKUNIT_ASSERT macros have a_MSGvariant. These take a format string and arguments to provide additionalcontext to the automatically generated error messages.

charsome_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 usingKUNIT_FAIL(), e.g.

/* 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");

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 atest 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:

staticstructkunit_caseexample_test_cases[]={KUNIT_CASE(example_test_foo),KUNIT_CASE(example_test_bar),KUNIT_CASE(example_test_baz),{}};staticstructkunit_suiteexample_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 suiteexample_test_suite would first runexample_suite_init, then run the test casesexample_test_foo,example_test_bar, andexample_test_baz. Each would haveexample_test_init called immediately before it andexample_test_exitcalled 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

Theexit andsuite_exit functions will run even ifinit orsuite_init fail. Make sure that they can handle any inconsistentstate which may result frominit orsuite_init encountering errorsor 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 afterlate_init, or when the test module is loaded (if the test wasbuilt as a module).

For more information, seeTest API.

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 inarch/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 onlybe able to run one test case per invocation.

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, aclass is astructthat contains function pointers. This creates acontract betweenimplementers andusers 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 asaclass handle, be one of the parameters. Thus the member functions (alsoknown asmethods) have access to member variables (also known asfields)allowing the same implementation to have multipleinstances.

A class can beoverridden bychild classes by embedding theparent classin the child class. Then when the child classmethod 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:

structshape{int(*area)(structshape*this);};structrectangle{structshapeparent;intlength;intwidth;};intrectangle_area(structshape*this){structrectangle*self=container_of(this,structrectangle,parent);returnself->length*self->width;};voidrectangle_new(structrectangle*self,intlength,intwidth){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 bycontainer_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:

structeeprom{ssize_t(*read)(structeeprom*this,size_toffset,char*buffer,size_tcount);ssize_t(*write)(structeeprom*this,size_toffset,constchar*buffer,size_tcount);};

And we want to test code that buffers writes to the EEPROM:

structeeprom_buffer{ssize_t(*write)(structeeprom_buffer*this,constchar*buffer,size_tcount);intflush(structeeprom_buffer*this);size_tflush_count;/* Flushes when buffer exceeds flush_count. */};structeeprom_buffer*new_eeprom_buffer(structeeprom*eeprom);voiddestroy_eeprom_buffer(structeeprom*eeprom);

We can test this code byfaking out the underlying EEPROM:

structfake_eeprom{structeepromparent;charcontents[FAKE_EEPROM_CONTENTS_SIZE];};ssize_tfake_eeprom_read(structeeprom*parent,size_toffset,char*buffer,size_tcount){structfake_eeprom*this=container_of(parent,structfake_eeprom,parent);count=min(count,FAKE_EEPROM_CONTENTS_SIZE-offset);memcpy(buffer,this->contents+offset,count);returncount;}ssize_tfake_eeprom_write(structeeprom*parent,size_toffset,constchar*buffer,size_tcount){structfake_eeprom*this=container_of(parent,structfake_eeprom,parent);count=min(count,FAKE_EEPROM_CONTENTS_SIZE-offset);memcpy(this->contents+offset,buffer,count);returncount;}voidfake_eeprom_init(structfake_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 teststructeeprom_buffer:

structeeprom_buffer_test{structfake_eeprom*fake_eeprom;structeeprom_buffer*eeprom_buffer;};staticvoideeprom_buffer_test_does_not_write_until_flush(structkunit*test){structeeprom_buffer_test*ctx=test->priv;structeeprom_buffer*eeprom_buffer=ctx->eeprom_buffer;structfake_eeprom*fake_eeprom=ctx->fake_eeprom;charbuffer[]={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);}staticvoideeprom_buffer_test_flushes_after_flush_count_met(structkunit*test){structeeprom_buffer_test*ctx=test->priv;structeeprom_buffer*eeprom_buffer=ctx->eeprom_buffer;structfake_eeprom*fake_eeprom=ctx->fake_eeprom;charbuffer[]={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);}staticvoideeprom_buffer_test_flushes_increments_of_flush_count(structkunit*test){structeeprom_buffer_test*ctx=test->priv;structeeprom_buffer*eeprom_buffer=ctx->eeprom_buffer;structfake_eeprom*fake_eeprom=ctx->fake_eeprom;charbuffer[]={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);}staticinteeprom_buffer_test_init(structkunit*test){structeeprom_buffer_test*ctx;ctx=kunit_kzalloc(test,sizeof(*ctx),GFP_KERNEL);KUNIT_ASSERT_NOT_ERR_OR_NULL(test,ctx);ctx->fake_eeprom=kunit_kzalloc(test,sizeof(*ctx->fake_eeprom),GFP_KERNEL);KUNIT_ASSERT_NOT_ERR_OR_NULL(test,ctx->fake_eeprom);fake_eeprom_init(ctx->fake_eeprom);ctx->eeprom_buffer=new_eeprom_buffer(&ctx->fake_eeprom->parent);KUNIT_ASSERT_NOT_ERR_OR_NULL(test,ctx->eeprom_buffer);test->priv=ctx;return0;}staticvoideeprom_buffer_test_exit(structkunit*test){structeeprom_buffer_test*ctx=test->priv;destroy_eeprom_buffer(ctx->eeprom_buffer);}

Testing Against Multiple Inputs

Testing just a few inputs is not enough to ensure that the code works correctly,for example: testing a hash function.

We can write a helper macro or function. The function is called for each input.For example, to testsha1sum(1), we can write:

#define TEST_SHA1(in, want) \        sha1sum(in, out); \        KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in);charout[40];TEST_SHA1("hello world","2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");TEST_SHA1("hello world!","430ce34d020724ed75a196dfc2ad67c77772d169");

Note the use of the_MSG version ofKUNIT_EXPECT_STREQ to print a moredetailed error and make the assertions clearer within the helper macros.

The_MSG variants are useful when the same expectation is called multipletimes (in a loop or helper function) and thus the line number is not enough toidentify what failed, as shown below.

In complicated cases, we recommend using atable-driven test compared to thehelper macro variation, for example:

inti;charout[40];structsha1_test_case{constchar*str;constchar*sha1;};structsha1_test_casecases[]={{.str="hello world",.sha1="2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",},{.str="hello world!",.sha1="430ce34d020724ed75a196dfc2ad67c77772d169",},};for(i=0;i<ARRAY_SIZE(cases);++i){sha1sum(cases[i].str,out);KUNIT_EXPECT_STREQ_MSG(test,out,cases[i].sha1,"sha1sum(%s)",cases[i].str);}

There is more boilerplate code involved, but it can:

  • be more readable when there are multiple inputs/outputs (due to field names).

    • For example, seefs/ext4/inode-test.c.

  • reduce duplication if test cases are shared across multiple tests.

    • For example: if we want to testsha256sum, we could add asha256field and reusecases.

  • be converted to a “parameterized test”.

Parameterized Testing

To run a test case against multiple inputs, KUnit provides a parameterizedtesting framework. This feature formalizes and extends the concept oftable-driven tests discussed previously.

A KUnit test is determined to be parameterized if a parameter generator functionis provided when registering the test case. A test user can either write theirown generator function or use one that is provided by KUnit. The generatorfunction is stored inkunit_case->generate_params and can be set using themacros described in the section below.

To establish the terminology, a “parameterized test” is a test which is runmultiple times (once per “parameter” or “parameter run”). Each parameter run hasboth its own independentstructkunit (the “parameter run context”) andaccess to a shared parentstructkunit (the “parameterized test context”).

Passing Parameters to a Test

There are three ways to provide the parameters to a test:

Array Parameter Macros:

KUnit provides special support for the common table-driven testing pattern.By applying eitherKUNIT_ARRAY_PARAM orKUNIT_ARRAY_PARAM_DESC to thecases array from the previous section, we can create a parameterized testas shown below:

// This is copy-pasted from above.structsha1_test_case{constchar*str;constchar*sha1;};staticconststructsha1_test_casecases[]={{.str="hello world",.sha1="2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",},{.str="hello world!",.sha1="430ce34d020724ed75a196dfc2ad67c77772d169",},};// Creates `sha1_gen_params()` to iterate over `cases` while using// the struct member `str` for the case description.KUNIT_ARRAY_PARAM_DESC(sha1,cases,str);// Looks no different from a normal test.staticvoidsha1_test(structkunit*test){// This function can just contain the body of the for-loop.// The former `cases[i]` is accessible under test->param_value.charout[40];structsha1_test_case*test_param=(structsha1_test_case*)(test->param_value);sha1sum(test_param->str,out);KUNIT_EXPECT_STREQ_MSG(test,out,test_param->sha1,"sha1sum(%s)",test_param->str);}// Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the// function declared by KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC.staticstructkunit_casesha1_test_cases[]={KUNIT_CASE_PARAM(sha1_test,sha1_gen_params),{}};

Custom Parameter Generator Function:

The generator function is responsible for generating parameters one-by-oneand has the following signature:constvoid*(*)(structkunit*test,constvoid*prev,char*desc).You can pass the generator function to theKUNIT_CASE_PARAMorKUNIT_CASE_PARAM_WITH_INIT macros.

The function receives the previously generated parameter as theprev argument(which isNULL on the first call) and can also access the parameterizedtest context passed as thetest argument. KUnit calls this functionrepeatedly until it returnsNULL, which signifies that a parameterizedtest ended.

Below is an example of how it works:

#define MAX_TEST_BUFFER_SIZE 8// Example generator function. It produces a sequence of buffer sizes that// are powers of two, starting at 1 (e.g., 1, 2, 4, 8).staticconstvoid*buffer_size_gen_params(structkunit*test,constvoid*prev,char*desc){longprev_buffer_size=(long)prev;longnext_buffer_size=1;// Start with an initial size of 1.// Stop generating parameters if the limit is reached or exceeded.if(prev_buffer_size>=MAX_TEST_BUFFER_SIZE)returnNULL;// For subsequent calls, calculate the next size by doubling the previous one.if(prev)next_buffer_size=prev_buffer_size<<1;return(void*)next_buffer_size;}// Simple test to validate that kunit_kzalloc provides zeroed memory.staticvoidbuffer_zero_test(structkunit*test){longbuffer_size=(long)test->param_value;// Use kunit_kzalloc to allocate a zero-initialized buffer. This makes the// memory "parameter run managed," meaning it's automatically cleaned up at// the end of each parameter run.int*buf=kunit_kzalloc(test,buffer_size*sizeof(int),GFP_KERNEL);// Ensure the allocation was successful.KUNIT_ASSERT_NOT_NULL(test,buf);// Loop through the buffer and confirm every element is zero.for(inti=0;i<buffer_size;i++)KUNIT_EXPECT_EQ(test,buf[i],0);}staticstructkunit_casebuffer_test_cases[]={KUNIT_CASE_PARAM(buffer_zero_test,buffer_size_gen_params),{}};

Runtime Parameter Array Registration in the Init Function:

For scenarios where you might need to initialize a parameterized test, youcan directly register a parameter array to the parameterized test context.

To do this, you must pass the parameterized test context, the array itself,the array size, and aget_description() function to thekunit_register_params_array() macro. This macro populatesstructkunit_params within the parameterized test context, effectivelystoring a parameter array object. Theget_description() function willbe used for populating parameter descriptions and has the following signature:void(*)(structkunit*test,constvoid*param,char*desc). Note that italso has access to the parameterized test context.

Important

When using this way to register a parameter array, you will need tomanually passkunit_array_gen_params() as the generator function toKUNIT_CASE_PARAM_WITH_INIT.kunit_array_gen_params() is a KUnithelper that will use the registered array to generate the parameters.

If needed, instead of passing the KUnit helper, you can also pass yourown custom generator function that utilizes the parameter array. Toaccess the parameter array from within the parameter generatorfunction usetest->params_array.params.

Thekunit_register_params_array() macro should be called within aparam_init() function that initializes the parameterized test and hasthe following signatureint(*)(structkunit*test). For a detailedexplanation of this mechanism please refer to the “Adding Shared Resources”section that is after this one. This method supports registering bothdynamically built and static parameter arrays.

The code snippet below shows theexample_param_init_dynamic_arr test thatutilizesmake_fibonacci_params() to create a dynamic array, which is thenregistered usingkunit_register_params_array(). To see the full codeplease refer to lib/kunit/kunit-example-test.c.

/** Example of a parameterized test param_init() function that registers a dynamic* array of parameters.*/staticintexample_param_init_dynamic_arr(structkunit*test){size_tseq_size;int*fibonacci_params;kunit_info(test,"initializing parameterized test\n");seq_size=6;fibonacci_params=make_fibonacci_params(test,seq_size);if(!fibonacci_params)return-ENOMEM;/*        * Passes the dynamic parameter array information to the parameterized test        * context struct kunit. The array and its metadata will be stored in        * test->parent->params_array. The array itself will be located in        * params_data.params.        */kunit_register_params_array(test,fibonacci_params,seq_size,example_param_dynamic_arr_get_desc);return0;}staticstructkunit_caseexample_test_cases[]={/*         * Note how we pass kunit_array_gen_params() to use the array we         * registered in example_param_init_dynamic_arr() to generate         * parameters.         */KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr,kunit_array_gen_params,example_param_init_dynamic_arr,example_param_exit_dynamic_arr),{}};

Adding Shared Resources

All parameter runs in this framework hold a reference to the parameterized testcontext, which can be accessed using the parentstructkunit pointer. Theparameterized test context is not used to execute any test logic itself; instead,it serves as a container for shared resources.

It’s possible to add resources to share between parameter runs within aparameterized test by usingKUNIT_CASE_PARAM_WITH_INIT, to which you passcustomparam_init() andparam_exit() functions. These functions run oncebefore and once after the parameterized test, respectively.

Theparam_init() function, with the signatureint(*)(structkunit*test),can be used for adding resources to theresources orpriv fields ofthe parameterized test context, registering the parameter array, and any otherinitialization logic.

Theparam_exit() function, with the signaturevoid(*)(structkunit*test),can be used to release any resources that were not parameterized test managed (i.e.not automatically cleaned up after the parameterized test ends) and for any otherexit logic.

Bothparam_init() andparam_exit() are passed the parameterized testcontext behind the scenes. However, the test case function receives the parameterrun context. Therefore, to manage and access shared resources from within a testcase function, you must usetest->parent.

For instance, finding a shared resource allocated by the Resource API requirespassingtest->parent tokunit_find_resource(). This principle extends toall other APIs that might be used in the test case function, includingkunit_kzalloc(),kunit_kmalloc_array(), and others (seeTest API and theResource API).

Note

Thesuite->init() function, which executes before each parameter run,receives the parameter run context. Therefore, any resources set up insuite->init() are cleaned up after each parameter run.

The code below shows how you can add the shared resources. Note that this codeutilizes the Resource API, which you can read more about here:Resource API. To see the full version of thiscode please refer to lib/kunit/kunit-example-test.c.

staticintexample_resource_init(structkunit_resource*res,void*context){.../* Code that allocates memory and stores context in res->data. */}/* This function deallocates memory for the kunit_resource->data field. */staticvoidexample_resource_free(structkunit_resource*res){kfree(res->data);}/* This match function locates a test resource based on defined criteria. */staticboolexample_resource_alloc_match(structkunit*test,structkunit_resource*res,void*match_data){returnres->data&&res->free==example_resource_free;}/* Function to initialize the parameterized test. */staticintexample_param_init(structkunit*test){intctx=3;/* Data to be stored. */void*data=kunit_alloc_resource(test,example_resource_init,example_resource_free,GFP_KERNEL,&ctx);if(!data)return-ENOMEM;kunit_register_params_array(test,example_params_array,ARRAY_SIZE(example_params_array));return0;}/* Example test that uses shared resources in test->resources. */staticvoidexample_params_test_with_init(structkunit*test){intthreshold;conststructexample_param*param=test->param_value;/*  Here we pass test->parent to access the parameterized test context. */structkunit_resource*res=kunit_find_resource(test->parent,example_resource_alloc_match,NULL);threshold=*((int*)res->data);KUNIT_ASSERT_LE(test,param->value,threshold);kunit_put_resource(res);}staticstructkunit_caseexample_test_cases[]={KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init,kunit_array_gen_params,example_param_init,NULL),{}};

As an alternative to using the KUnit Resource API for sharing resources, you canplace them intest->parent->priv. This serves as a more lightweight methodfor resource storage, best for scenarios where complex resource management isnot required.

As stated previouslyparam_init() andparam_exit() get the parameterizedtest context. So, you can directly usetest->priv withinparam_init/exitto manage shared resources. However, from within the test case function, you mustnavigate up to the parentstructkunit i.e. the parameterized test context.Therefore, you need to usetest->parent->priv to access those sameresources.

The resources placed intest->parent->priv will need to be allocated inmemory to persist across the parameter runs. If memory is allocated using theKUnit memory allocation APIs (described more in the “Allocating Memory” sectionbelow), you won’t need to worry about deallocation. The APIs will make the memoryparameterized test ‘managed’, ensuring that it will automatically get cleaned upafter the parameterized test concludes.

The code below demonstrates example usage of thepriv field for sharedresources:

staticconststructexample_param{intvalue;}example_params_array[]={{.value=3,},{.value=2,},{.value=1,},{.value=0,},};/* Initialize the parameterized test context. */staticintexample_param_init_priv(structkunit*test){intctx=3;/* Data to be stored. */intarr_size=ARRAY_SIZE(example_params_array);/*         * Allocate memory using kunit_kzalloc(). Since the `param_init`         * function receives the parameterized test context, this memory         * allocation will be scoped to the lifetime of the parameterized test.         */test->priv=kunit_kzalloc(test,sizeof(int),GFP_KERNEL);/* Assign the context value to test->priv.*/*((int*)test->priv)=ctx;/* Register the parameter array. */kunit_register_params_array(test,example_params_array,arr_size,NULL);return0;}staticvoidexample_params_test_with_init_priv(structkunit*test){intthreshold;conststructexample_param*param=test->param_value;/* By design, test->parent will not be NULL. */KUNIT_ASSERT_NOT_NULL(test,test->parent);/* Here we use test->parent->priv to access the shared resource. */threshold=*(int*)test->parent->priv;KUNIT_ASSERT_LE(test,param->value,threshold);}staticstructkunit_caseexample_tests[]={KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_priv,kunit_array_gen_params,example_param_init_priv,NULL),{}};

Allocating Memory

Where you might usekzalloc, you can instead usekunit_kzalloc as KUnitwill then ensure that the memory is freed once the test completes.

This is useful because it lets us use theKUNIT_ASSERT_EQ macros to exitearly from a test without having to worry about remembering to callkfree.For example:

voidexample_test_allocation(structkunit*test){char*buffer=kunit_kzalloc(test,16,GFP_KERNEL);/* Ensure allocation succeeded. */KUNIT_ASSERT_NOT_ERR_OR_NULL(test,buffer);KUNIT_ASSERT_STREQ(test,buffer,"");}

Registering Cleanup Actions

If you need to perform some cleanup beyond simple use ofkunit_kzalloc,you can register a custom “deferred action”, which is a cleanup functionrun when the test exits (whether cleanly, or via a failed assertion).

Actions are simple functions with no return value, and a singlevoid*context argument, and fulfill the same role as “cleanup” functions in Pythonand Go tests, “defer” statements in languages which support them, and(in some cases) destructors in RAII languages.

These are very useful for unregistering things from global lists, closingfiles or other resources, or freeing resources.

For example:

staticvoidcleanup_device(void*ctx){structdevice*dev=(structdevice*)ctx;device_unregister(dev);}voidexample_device_test(structkunit*test){structmy_devicedev;device_register(&dev);kunit_add_action(test,&cleanup_device,&dev);}

Note that, for functions like device_unregister which only accept a singlepointer-sized argument, it’s possible to automatically generate a wrapperwith theKUNIT_DEFINE_ACTION_WRAPPER() macro, for example:

KUNIT_DEFINE_ACTION_WRAPPER(device_unregister,device_unregister_wrapper,structdevice*);kunit_add_action(test,&device_unregister_wrapper,&dev);

You should do this in preference to manually casting to thekunit_action_t type,as casting function pointers will break Control Flow Integrity (CFI).

kunit_add_action can fail if, for example, the system is out of memory.You can usekunit_add_action_or_reset instead which runs the actionimmediately if it cannot be deferred.

If you need more control over when the cleanup function is called, youcan trigger it early usingkunit_release_action, or cancel it entirelywithkunit_remove_action.

Testing Static Functions

If you want to test static functions without exposing those functions outside oftesting, one option is conditionally export the symbol. When KUnit is enabled,the symbol is exposed but remains static otherwise. To use this method, followthe template below.

/* In the file containing functions to test "my_file.c" */#include<kunit/visibility.h>#include<my_file.h>...VISIBLE_IF_KUNITintdo_interesting_thing(){...}EXPORT_SYMBOL_IF_KUNIT(do_interesting_thing);/* In the header file "my_file.h" */#if IS_ENABLED(CONFIG_KUNIT)intdo_interesting_thing(void);#endif/* In the KUnit test file "my_file_test.c" */#include<kunit/visibility.h>#include<my_file.h>...MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING");...// Use do_interesting_thing() in tests

For a full example, see thispatchwhere a test is modified to conditionally expose static functions for testingusing the macros above.

As analternative to the method above, you could conditionally#includethe test file at the end of your .c file. This is not recommended but worksif needed. For example:

/* In "my_file.c" */staticintdo_interesting_thing();#ifdef CONFIG_MY_KUNIT_TEST#include"my_kunit_test.c"#endif

Injecting Test-Only Code

Similar to as shown above, we can add test-specific logic. For example:

/* In my_file.h */#ifdef CONFIG_MY_KUNIT_TEST/* Defined in my_kunit_test.c */voidtest_only_hook(void);#elsevoidtest_only_hook(void){}#endif

This test-only code can be made more useful by accessing the currentkunit_testas shown in next section:Accessing The Current Test.

Accessing The Current Test

In some cases, we need to call test-only code from outside the test file. Thisis helpful, for example, when providing a fake implementation of a function, orto fail any current test from within an error handler.We can do this via thekunit_test field intask_struct, which we canaccess using thekunit_get_current_test() function inkunit/test-bug.h.

kunit_get_current_test() is safe to call even if KUnit is not enabled. IfKUnit is not enabled, or if no test is running in the current task, it willreturnNULL. This compiles down to either a no-op or a static key check,so will have a negligible performance impact when no test is running.

The example below uses this to implement a “mock” implementation of a function,foo:

#include<kunit/test-bug.h> /* for kunit_get_current_test */structtest_data{intfoo_result;intwant_foo_called_with;};staticintfake_foo(intarg){structkunit*test=kunit_get_current_test();structtest_data*test_data=test->priv;KUNIT_EXPECT_EQ(test,test_data->want_foo_called_with,arg);returntest_data->foo_result;}staticvoidexample_simple_test(structkunit*test){/* Assume priv (private, a member used to pass test data from         * the init function) is allocated in the suite's .init */structtest_data*test_data=test->priv;test_data->foo_result=42;test_data->want_foo_called_with=1;/* In a real test, we'd probably pass a pointer to fake_foo somewhere         * like an ops struct, etc. instead of calling it directly. */KUNIT_EXPECT_EQ(test,fake_foo(1),42);}

In this example, we are using thepriv member ofstructkunit as a wayof passing data to the test from the init function. In generalpriv ispointer that can be used for any user data. This is preferred over staticvariables, as it avoids concurrency issues.

Had we wanted something more flexible, we could have used a namedkunit_resource.Each test can have multiple resources which have string names providing the sameflexibility as apriv member, but also, for example, allowing helperfunctions to create resources without conflicting with each other. It is alsopossible to define a clean up function for each resource, making it easy toavoid resource leaks. For more information, seeResource API.

Failing The Current Test

If we want to fail the current test, we can usekunit_fail_current_test(fmt,args...)which is defined in<kunit/test-bug.h> and does not require pulling in<kunit/test.h>.For example, we have an option to enable some extra debug checks on some datastructures as shown below:

#include<kunit/test-bug.h>#ifdef CONFIG_EXTRA_DEBUG_CHECKSstaticvoidvalidate_my_data(structdata*data){if(is_valid(data))return;kunit_fail_current_test("data %p is invalid",data);/* Normal, non-KUnit, error reporting code here. */}#elsestaticvoidmy_debug_function(void){}#endif

kunit_fail_current_test() is safe to call even if KUnit is not enabled. IfKUnit is not enabled, or if no test is running in the current task, it will donothing. This compiles down to either a no-op or a static key check, so willhave a negligible performance impact when no test is running.

Managing Fake Devices and Drivers

When testing drivers or code which interacts with drivers, many functions willrequire astructdevice orstructdevice_driver. In many cases, settingup a real device is not required to test any given function, so a fake devicecan be used instead.

KUnit provides helper functions to create and manage these fake devices, whichare internally of typestructkunit_device, and are attached to a specialkunit_bus. These devices support managed device resources (devres), asdescribed inDevres - Managed Device Resource

To create a KUnit-managedstructdevice_driver, usekunit_driver_create(),which will create a driver with the given name, on thekunit_bus. This driverwill automatically be destroyed when the corresponding test finishes, but can alsobe manually destroyed withdriver_unregister().

To create a fake device, use thekunit_device_register(), which will createand register a device, using a new KUnit-managed driver created withkunit_driver_create().To provide a specific, non-KUnit-managed driver, usekunit_device_register_with_driver()instead. Like with managed drivers, KUnit-managed fake devices are automaticallycleaned up when the test finishes, but can be manually cleaned up early withkunit_device_unregister().

The KUnit devices should be used in preference toroot_device_register(), andinstead ofplatform_device_register() in cases where the device is not otherwisea platform device.

For example:

#include<kunit/device.h>staticvoidtest_my_device(structkunit*test){structdevice*fake_device;constchar*dev_managed_string;// Create a fake device.fake_device=kunit_device_register(test,"my_device");KUNIT_ASSERT_NOT_ERR_OR_NULL(test,fake_device)// Pass it to functions which need a device.dev_managed_string=devm_kstrdup(fake_device,"Hello, World!");// Everything is cleaned up automatically when the test ends.}