Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Documentation: kunit: include example of a parameterized test

Commit fadb08e7c750 ("kunit: Support for Parameterized Testing")
introduced support but lacks documentation for how to use it.

This patch builds on commit 1f0e943df68a ("Documentation: kunit: provide
guidance for testing many inputs") to show a minimal example of the new
feature.

Signed-off-by: Daniel Latypov <dlatypov@google.com>
Reviewed-by: David Gow <davidgow@google.com>
Tested-by: Brendan Higgins <brendanhiggins@google.com>
Acked-by: Brendan Higgins <brendanhiggins@google.com>
Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

authored by

Daniel Latypov and committed by
Shuah Khan
8db50be2 ebfd4488

+57
+57
Documentation/dev-tools/kunit/usage.rst
··· 522 522 * E.g. if we wanted to also test ``sha256sum``, we could add a ``sha256`` 523 523 field and reuse ``cases``. 524 524 525 + * be converted to a "parameterized test", see below. 526 + 527 + Parameterized Testing 528 + ~~~~~~~~~~~~~~~~~~~~~ 529 + 530 + The table-driven testing pattern is common enough that KUnit has special 531 + support for it. 532 + 533 + Reusing the same ``cases`` array from above, we can write the test as a 534 + "parameterized test" with the following. 535 + 536 + .. code-block:: c 537 + 538 + // This is copy-pasted from above. 539 + struct sha1_test_case { 540 + const char *str; 541 + const char *sha1; 542 + }; 543 + struct sha1_test_case cases[] = { 544 + { 545 + .str = "hello world", 546 + .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", 547 + }, 548 + { 549 + .str = "hello world!", 550 + .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169", 551 + }, 552 + }; 553 + 554 + // Need a helper function to generate a name for each test case. 555 + static void case_to_desc(const struct sha1_test_case *t, char *desc) 556 + { 557 + strcpy(desc, t->str); 558 + } 559 + // Creates `sha1_gen_params()` to iterate over `cases`. 560 + KUNIT_ARRAY_PARAM(sha1, cases, case_to_desc); 561 + 562 + // Looks no different from a normal test. 563 + static void sha1_test(struct kunit *test) 564 + { 565 + // This function can just contain the body of the for-loop. 566 + // The former `cases[i]` is accessible under test->param_value. 567 + char out[40]; 568 + struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value); 569 + 570 + sha1sum(test_param->str, out); 571 + KUNIT_EXPECT_STREQ_MSG(test, (char *)out, test_param->sha1, 572 + "sha1sum(%s)", test_param->str); 573 + } 574 + 575 + // Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the 576 + // function declared by KUNIT_ARRAY_PARAM. 577 + static struct kunit_case sha1_test_cases[] = { 578 + KUNIT_CASE_PARAM(sha1_test, sha1_gen_params), 579 + {} 580 + }; 581 + 525 582 .. _kunit-on-non-uml: 526 583 527 584 KUnit on non-UML architectures