1.. SPDX-License-Identifier: GPL-2.0
2
3Writing Tests
4=============
5
6Test Cases
7----------
8
9The fundamental unit in KUnit is the test case. A test case is a function with
10the signature ``void (*)(struct kunit *test)``. It calls the function under test
11and then sets *expectations* for what should happen. For example:
12
13.. code-block:: c
14
15	void example_test_success(struct kunit *test)
16	{
17	}
18
19	void example_test_failure(struct kunit *test)
20	{
21		KUNIT_FAIL(test, "This test never passes.");
22	}
23
24In the above example, ``example_test_success`` always passes because it does
25nothing; no expectations are set, and therefore all expectations pass. On the
26other hand ``example_test_failure`` always fails because it calls ``KUNIT_FAIL``,
27which is a special expectation that logs a message and causes the test case to
28fail.
29
30Expectations
31~~~~~~~~~~~~
32An *expectation* specifies that we expect a piece of code to do something in a
33test. An expectation is called like a function. A test is made by setting
34expectations about the behavior of a piece of code under test. When one or more
35expectations fail, the test case fails and information about the failure is
36logged. For example:
37
38.. code-block:: c
39
40	void add_test_basic(struct kunit *test)
41	{
42		KUNIT_EXPECT_EQ(test, 1, add(1, 0));
43		KUNIT_EXPECT_EQ(test, 2, add(1, 1));
44	}
45
46In the above example, ``add_test_basic`` makes a number of assertions about the
47behavior of a function called ``add``. The first parameter is always of type
48``struct kunit *``, which contains information about the current test context.
49The second parameter, in this case, is what the value is expected to be. The
50last value is what the value actually is. If ``add`` passes all of these
51expectations, the test case, ``add_test_basic`` will pass; if any one of these
52expectations fails, the test case will fail.
53
54A test case *fails* when any expectation is violated; however, the test will
55continue to run, and try other expectations until the test case ends or is
56otherwise terminated. This is as opposed to *assertions* which are discussed
57later.
58
59To learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst.
60
61.. note::
62   A single test case should be short, easy to understand, and focused on a
63   single behavior.
64
65For example, if we want to rigorously test the ``add`` function above, create
66additional tests cases which would test each property that an ``add`` function
67should have as shown below:
68
69.. code-block:: c
70
71	void add_test_basic(struct kunit *test)
72	{
73		KUNIT_EXPECT_EQ(test, 1, add(1, 0));
74		KUNIT_EXPECT_EQ(test, 2, add(1, 1));
75	}
76
77	void add_test_negative(struct kunit *test)
78	{
79		KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
80	}
81
82	void add_test_max(struct kunit *test)
83	{
84		KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
85		KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
86	}
87
88	void add_test_overflow(struct kunit *test)
89	{
90		KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1));
91	}
92
93Assertions
94~~~~~~~~~~
95
96An assertion is like an expectation, except that the assertion immediately
97terminates the test case if the condition is not satisfied. For example:
98
99.. code-block:: c
100
101	static void test_sort(struct kunit *test)
102	{
103		int *a, i, r = 1;
104		a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL);
105		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a);
106		for (i = 0; i < TEST_LEN; i++) {
107			r = (r * 725861) % 6599;
108			a[i] = r;
109		}
110		sort(a, TEST_LEN, sizeof(*a), cmpint, NULL);
111		for (i = 0; i < TEST_LEN-1; i++)
112			KUNIT_EXPECT_LE(test, a[i], a[i + 1]);
113	}
114
115In this example, we need to be able to allocate an array to test the ``sort()``
116function. So we use ``KUNIT_ASSERT_NOT_ERR_OR_NULL()`` to abort the test if
117there's an allocation error.
118
119.. note::
120   In other test frameworks, ``ASSERT`` macros are often implemented by calling
121   ``return`` so they only work from the test function. In KUnit, we stop the
122   current kthread on failure, so you can call them from anywhere.
123
124Customizing error messages
125--------------------------
126
127Each of the ``KUNIT_EXPECT`` and ``KUNIT_ASSERT`` macros have a ``_MSG``
128variant.  These take a format string and arguments to provide additional
129context to the automatically generated error messages.
130
131.. code-block:: c
132
133	char some_str[41];
134	generate_sha1_hex_string(some_str);
135
136	/* Before. Not easy to tell why the test failed. */
137	KUNIT_EXPECT_EQ(test, strlen(some_str), 40);
138
139	/* After. Now we see the offending string. */
140	KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str);
141
142Alternatively, one can take full control over the error message by using
143``KUNIT_FAIL()``, e.g.
144
145.. code-block:: c
146
147	/* Before */
148	KUNIT_EXPECT_EQ(test, some_setup_function(), 0);
149
150	/* After: full control over the failure message. */
151	if (some_setup_function())
152		KUNIT_FAIL(test, "Failed to setup thing for testing");
153
154
155Test Suites
156~~~~~~~~~~~
157
158We need many test cases covering all the unit's behaviors. It is common to have
159many similar tests. In order to reduce duplication in these closely related
160tests, most unit testing frameworks (including KUnit) provide the concept of a
161*test suite*. A test suite is a collection of test cases for a unit of code
162with optional setup and teardown functions that run before/after the whole
163suite and/or every test case. For example:
164
165.. code-block:: c
166
167	static struct kunit_case example_test_cases[] = {
168		KUNIT_CASE(example_test_foo),
169		KUNIT_CASE(example_test_bar),
170		KUNIT_CASE(example_test_baz),
171		{}
172	};
173
174	static struct kunit_suite example_test_suite = {
175		.name = "example",
176		.init = example_test_init,
177		.exit = example_test_exit,
178		.suite_init = example_suite_init,
179		.suite_exit = example_suite_exit,
180		.test_cases = example_test_cases,
181	};
182	kunit_test_suite(example_test_suite);
183
184In the above example, the test suite ``example_test_suite`` would first run
185``example_suite_init``, then run the test cases ``example_test_foo``,
186``example_test_bar``, and ``example_test_baz``. Each would have
187``example_test_init`` called immediately before it and ``example_test_exit``
188called immediately after it. Finally, ``example_suite_exit`` would be called
189after everything else. ``kunit_test_suite(example_test_suite)`` registers the
190test suite with the KUnit test framework.
191
192.. note::
193   A test case will only run if it is associated with a test suite.
194
195``kunit_test_suite(...)`` is a macro which tells the linker to put the
196specified test suite in a special linker section so that it can be run by KUnit
197either after ``late_init``, or when the test module is loaded (if the test was
198built as a module).
199
200For more information, see Documentation/dev-tools/kunit/api/test.rst.
201
202.. _kunit-on-non-uml:
203
204Writing Tests For Other Architectures
205-------------------------------------
206
207It is better to write tests that run on UML to tests that only run under a
208particular architecture. It is better to write tests that run under QEMU or
209another easy to obtain (and monetarily free) software environment to a specific
210piece of hardware.
211
212Nevertheless, there are still valid reasons to write a test that is architecture
213or hardware specific. For example, we might want to test code that really
214belongs in ``arch/some-arch/*``. Even so, try to write the test so that it does
215not depend on physical hardware. Some of our test cases may not need hardware,
216only few tests actually require the hardware to test it. When hardware is not
217available, instead of disabling tests, we can skip them.
218
219Now that we have narrowed down exactly what bits are hardware specific, the
220actual procedure for writing and running the tests is same as writing normal
221KUnit tests.
222
223.. important::
224   We may have to reset hardware state. If this is not possible, we may only
225   be able to run one test case per invocation.
226
227.. TODO(brendanhiggins@google.com): Add an actual example of an architecture-
228   dependent KUnit test.
229
230Common Patterns
231===============
232
233Isolating Behavior
234------------------
235
236Unit testing limits the amount of code under test to a single unit. It controls
237what code gets run when the unit under test calls a function. Where a function
238is exposed as part of an API such that the definition of that function can be
239changed without affecting the rest of the code base. In the kernel, this comes
240from two constructs: classes, which are structs that contain function pointers
241provided by the implementer, and architecture-specific functions, which have
242definitions selected at compile time.
243
244Classes
245~~~~~~~
246
247Classes are not a construct that is built into the C programming language;
248however, it is an easily derived concept. Accordingly, in most cases, every
249project that does not use a standardized object oriented library (like GNOME's
250GObject) has their own slightly different way of doing object oriented
251programming; the Linux kernel is no exception.
252
253The central concept in kernel object oriented programming is the class. In the
254kernel, a *class* is a struct that contains function pointers. This creates a
255contract between *implementers* and *users* since it forces them to use the
256same function signature without having to call the function directly. To be a
257class, the function pointers must specify that a pointer to the class, known as
258a *class handle*, be one of the parameters. Thus the member functions (also
259known as *methods*) have access to member variables (also known as *fields*)
260allowing the same implementation to have multiple *instances*.
261
262A class can be *overridden* by *child classes* by embedding the *parent class*
263in the child class. Then when the child class *method* is called, the child
264implementation knows that the pointer passed to it is of a parent contained
265within the child. Thus, the child can compute the pointer to itself because the
266pointer to the parent is always a fixed offset from the pointer to the child.
267This offset is the offset of the parent contained in the child struct. For
268example:
269
270.. code-block:: c
271
272	struct shape {
273		int (*area)(struct shape *this);
274	};
275
276	struct rectangle {
277		struct shape parent;
278		int length;
279		int width;
280	};
281
282	int rectangle_area(struct shape *this)
283	{
284		struct rectangle *self = container_of(this, struct rectangle, parent);
285
286		return self->length * self->width;
287	};
288
289	void rectangle_new(struct rectangle *self, int length, int width)
290	{
291		self->parent.area = rectangle_area;
292		self->length = length;
293		self->width = width;
294	}
295
296In this example, computing the pointer to the child from the pointer to the
297parent is done by ``container_of``.
298
299Faking Classes
300~~~~~~~~~~~~~~
301
302In order to unit test a piece of code that calls a method in a class, the
303behavior of the method must be controllable, otherwise the test ceases to be a
304unit test and becomes an integration test.
305
306A fake class implements a piece of code that is different than what runs in a
307production instance, but behaves identical from the standpoint of the callers.
308This is done to replace a dependency that is hard to deal with, or is slow. For
309example, implementing a fake EEPROM that stores the "contents" in an
310internal buffer. Assume we have a class that represents an EEPROM:
311
312.. code-block:: c
313
314	struct eeprom {
315		ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count);
316		ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count);
317	};
318
319And we want to test code that buffers writes to the EEPROM:
320
321.. code-block:: c
322
323	struct eeprom_buffer {
324		ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count);
325		int flush(struct eeprom_buffer *this);
326		size_t flush_count; /* Flushes when buffer exceeds flush_count. */
327	};
328
329	struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom);
330	void destroy_eeprom_buffer(struct eeprom *eeprom);
331
332We can test this code by *faking out* the underlying EEPROM:
333
334.. code-block:: c
335
336	struct fake_eeprom {
337		struct eeprom parent;
338		char contents[FAKE_EEPROM_CONTENTS_SIZE];
339	};
340
341	ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count)
342	{
343		struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
344
345		count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
346		memcpy(buffer, this->contents + offset, count);
347
348		return count;
349	}
350
351	ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count)
352	{
353		struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);
354
355		count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
356		memcpy(this->contents + offset, buffer, count);
357
358		return count;
359	}
360
361	void fake_eeprom_init(struct fake_eeprom *this)
362	{
363		this->parent.read = fake_eeprom_read;
364		this->parent.write = fake_eeprom_write;
365		memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE);
366	}
367
368We can now use it to test ``struct eeprom_buffer``:
369
370.. code-block:: c
371
372	struct eeprom_buffer_test {
373		struct fake_eeprom *fake_eeprom;
374		struct eeprom_buffer *eeprom_buffer;
375	};
376
377	static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test)
378	{
379		struct eeprom_buffer_test *ctx = test->priv;
380		struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
381		struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
382		char buffer[] = {0xff};
383
384		eeprom_buffer->flush_count = SIZE_MAX;
385
386		eeprom_buffer->write(eeprom_buffer, buffer, 1);
387		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
388
389		eeprom_buffer->write(eeprom_buffer, buffer, 1);
390		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0);
391
392		eeprom_buffer->flush(eeprom_buffer);
393		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
394		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
395	}
396
397	static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test)
398	{
399		struct eeprom_buffer_test *ctx = test->priv;
400		struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
401		struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
402		char buffer[] = {0xff};
403
404		eeprom_buffer->flush_count = 2;
405
406		eeprom_buffer->write(eeprom_buffer, buffer, 1);
407		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
408
409		eeprom_buffer->write(eeprom_buffer, buffer, 1);
410		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
411		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
412	}
413
414	static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test)
415	{
416		struct eeprom_buffer_test *ctx = test->priv;
417		struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
418		struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
419		char buffer[] = {0xff, 0xff};
420
421		eeprom_buffer->flush_count = 2;
422
423		eeprom_buffer->write(eeprom_buffer, buffer, 1);
424		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);
425
426		eeprom_buffer->write(eeprom_buffer, buffer, 2);
427		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
428		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
429		/* Should have only flushed the first two bytes. */
430		KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0);
431	}
432
433	static int eeprom_buffer_test_init(struct kunit *test)
434	{
435		struct eeprom_buffer_test *ctx;
436
437		ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
438		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);
439
440		ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL);
441		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom);
442		fake_eeprom_init(ctx->fake_eeprom);
443
444		ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent);
445		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer);
446
447		test->priv = ctx;
448
449		return 0;
450	}
451
452	static void eeprom_buffer_test_exit(struct kunit *test)
453	{
454		struct eeprom_buffer_test *ctx = test->priv;
455
456		destroy_eeprom_buffer(ctx->eeprom_buffer);
457	}
458
459Testing Against Multiple Inputs
460-------------------------------
461
462Testing just a few inputs is not enough to ensure that the code works correctly,
463for example: testing a hash function.
464
465We can write a helper macro or function. The function is called for each input.
466For example, to test ``sha1sum(1)``, we can write:
467
468.. code-block:: c
469
470	#define TEST_SHA1(in, want) \
471		sha1sum(in, out); \
472		KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in);
473
474	char out[40];
475	TEST_SHA1("hello world",  "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
476	TEST_SHA1("hello world!", "430ce34d020724ed75a196dfc2ad67c77772d169");
477
478Note the use of the ``_MSG`` version of ``KUNIT_EXPECT_STREQ`` to print a more
479detailed error and make the assertions clearer within the helper macros.
480
481The ``_MSG`` variants are useful when the same expectation is called multiple
482times (in a loop or helper function) and thus the line number is not enough to
483identify what failed, as shown below.
484
485In complicated cases, we recommend using a *table-driven test* compared to the
486helper macro variation, for example:
487
488.. code-block:: c
489
490	int i;
491	char out[40];
492
493	struct sha1_test_case {
494		const char *str;
495		const char *sha1;
496	};
497
498	struct sha1_test_case cases[] = {
499		{
500			.str = "hello world",
501			.sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
502		},
503		{
504			.str = "hello world!",
505			.sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
506		},
507	};
508	for (i = 0; i < ARRAY_SIZE(cases); ++i) {
509		sha1sum(cases[i].str, out);
510		KUNIT_EXPECT_STREQ_MSG(test, out, cases[i].sha1,
511		                      "sha1sum(%s)", cases[i].str);
512	}
513
514
515There is more boilerplate code involved, but it can:
516
517* be more readable when there are multiple inputs/outputs (due to field names).
518
519  * For example, see ``fs/ext4/inode-test.c``.
520
521* reduce duplication if test cases are shared across multiple tests.
522
523  * For example: if we want to test ``sha256sum``, we could add a ``sha256``
524    field and reuse ``cases``.
525
526* be converted to a "parameterized test".
527
528Parameterized Testing
529~~~~~~~~~~~~~~~~~~~~~
530
531The table-driven testing pattern is common enough that KUnit has special
532support for it.
533
534By reusing the same ``cases`` array from above, we can write the test as a
535"parameterized test" with the following.
536
537.. code-block:: c
538
539	// This is copy-pasted from above.
540	struct sha1_test_case {
541		const char *str;
542		const char *sha1;
543	};
544	const struct sha1_test_case cases[] = {
545		{
546			.str = "hello world",
547			.sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
548		},
549		{
550			.str = "hello world!",
551			.sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
552		},
553	};
554
555	// Need a helper function to generate a name for each test case.
556	static void case_to_desc(const struct sha1_test_case *t, char *desc)
557	{
558		strcpy(desc, t->str);
559	}
560	// Creates `sha1_gen_params()` to iterate over `cases`.
561	KUNIT_ARRAY_PARAM(sha1, cases, case_to_desc);
562
563	// Looks no different from a normal test.
564	static void sha1_test(struct kunit *test)
565	{
566		// This function can just contain the body of the for-loop.
567		// The former `cases[i]` is accessible under test->param_value.
568		char out[40];
569		struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value);
570
571		sha1sum(test_param->str, out);
572		KUNIT_EXPECT_STREQ_MSG(test, out, test_param->sha1,
573				      "sha1sum(%s)", test_param->str);
574	}
575
576	// Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the
577	// function declared by KUNIT_ARRAY_PARAM.
578	static struct kunit_case sha1_test_cases[] = {
579		KUNIT_CASE_PARAM(sha1_test, sha1_gen_params),
580		{}
581	};
582
583Allocating Memory
584-----------------
585
586Where you might use ``kzalloc``, you can instead use ``kunit_kzalloc`` as KUnit
587will then ensure that the memory is freed once the test completes.
588
589This is useful because it lets us use the ``KUNIT_ASSERT_EQ`` macros to exit
590early from a test without having to worry about remembering to call ``kfree``.
591For example:
592
593.. code-block:: c
594
595	void example_test_allocation(struct kunit *test)
596	{
597		char *buffer = kunit_kzalloc(test, 16, GFP_KERNEL);
598		/* Ensure allocation succeeded. */
599		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buffer);
600
601		KUNIT_ASSERT_STREQ(test, buffer, "");
602	}
603
604
605Testing Static Functions
606------------------------
607
608If we do not want to expose functions or variables for testing, one option is to
609conditionally ``#include`` the test file at the end of your .c file. For
610example:
611
612.. code-block:: c
613
614	/* In my_file.c */
615
616	static int do_interesting_thing();
617
618	#ifdef CONFIG_MY_KUNIT_TEST
619	#include "my_kunit_test.c"
620	#endif
621
622Injecting Test-Only Code
623------------------------
624
625Similar to as shown above, we can add test-specific logic. For example:
626
627.. code-block:: c
628
629	/* In my_file.h */
630
631	#ifdef CONFIG_MY_KUNIT_TEST
632	/* Defined in my_kunit_test.c */
633	void test_only_hook(void);
634	#else
635	void test_only_hook(void) { }
636	#endif
637
638This test-only code can be made more useful by accessing the current ``kunit_test``
639as shown in next section: *Accessing The Current Test*.
640
641Accessing The Current Test
642--------------------------
643
644In some cases, we need to call test-only code from outside the test file.  This
645is helpful, for example, when providing a fake implementation of a function, or
646to fail any current test from within an error handler.
647We can do this via the ``kunit_test`` field in ``task_struct``, which we can
648access using the ``kunit_get_current_test()`` function in ``kunit/test-bug.h``.
649
650``kunit_get_current_test()`` is safe to call even if KUnit is not enabled. If
651KUnit is not enabled, or if no test is running in the current task, it will
652return ``NULL``. This compiles down to either a no-op or a static key check,
653so will have a negligible performance impact when no test is running.
654
655The example below uses this to implement a "mock" implementation of a function, ``foo``:
656
657.. code-block:: c
658
659	#include <kunit/test-bug.h> /* for kunit_get_current_test */
660
661	struct test_data {
662		int foo_result;
663		int want_foo_called_with;
664	};
665
666	static int fake_foo(int arg)
667	{
668		struct kunit *test = kunit_get_current_test();
669		struct test_data *test_data = test->priv;
670
671		KUNIT_EXPECT_EQ(test, test_data->want_foo_called_with, arg);
672		return test_data->foo_result;
673	}
674
675	static void example_simple_test(struct kunit *test)
676	{
677		/* Assume priv (private, a member used to pass test data from
678		 * the init function) is allocated in the suite's .init */
679		struct test_data *test_data = test->priv;
680
681		test_data->foo_result = 42;
682		test_data->want_foo_called_with = 1;
683
684		/* In a real test, we'd probably pass a pointer to fake_foo somewhere
685		 * like an ops struct, etc. instead of calling it directly. */
686		KUNIT_EXPECT_EQ(test, fake_foo(1), 42);
687	}
688
689In this example, we are using the ``priv`` member of ``struct kunit`` as a way
690of passing data to the test from the init function. In general ``priv`` is
691pointer that can be used for any user data. This is preferred over static
692variables, as it avoids concurrency issues.
693
694Had we wanted something more flexible, we could have used a named ``kunit_resource``.
695Each test can have multiple resources which have string names providing the same
696flexibility as a ``priv`` member, but also, for example, allowing helper
697functions to create resources without conflicting with each other. It is also
698possible to define a clean up function for each resource, making it easy to
699avoid resource leaks. For more information, see Documentation/dev-tools/kunit/api/resource.rst.
700
701Failing The Current Test
702------------------------
703
704If we want to fail the current test, we can use ``kunit_fail_current_test(fmt, args...)``
705which is defined in ``<kunit/test-bug.h>`` and does not require pulling in ``<kunit/test.h>``.
706For example, we have an option to enable some extra debug checks on some data
707structures as shown below:
708
709.. code-block:: c
710
711	#include <kunit/test-bug.h>
712
713	#ifdef CONFIG_EXTRA_DEBUG_CHECKS
714	static void validate_my_data(struct data *data)
715	{
716		if (is_valid(data))
717			return;
718
719		kunit_fail_current_test("data %p is invalid", data);
720
721		/* Normal, non-KUnit, error reporting code here. */
722	}
723	#else
724	static void my_debug_function(void) { }
725	#endif
726
727``kunit_fail_current_test()`` is safe to call even if KUnit is not enabled. If
728KUnit is not enabled, or if no test is running in the current task, it will do
729nothing. This compiles down to either a no-op or a static key check, so will
730have a negligible performance impact when no test is running.
731