usage.rst 28 KB

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