1 // SPDX-License-Identifier: GPL-2.0
3 * Base unit test (KUnit) API.
5 * Copyright (C) 2019, Google LLC.
9 #include <kunit/resource.h>
10 #include <kunit/test.h>
11 #include <kunit/test-bug.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/panic.h>
16 #include <linux/sched/debug.h>
17 #include <linux/sched.h>
20 #include "string-stream.h"
21 #include "try-catch-impl.h"
23 DEFINE_STATIC_KEY_FALSE(kunit_running);
25 #if IS_BUILTIN(CONFIG_KUNIT)
27 * Fail the current test and print an error message to the log.
29 void __kunit_fail_current_test(const char *file, int line, const char *fmt, ...)
35 if (!current->kunit_test)
38 kunit_set_failure(current->kunit_test);
40 /* kunit_err() only accepts literals, so evaluate the args first. */
42 len = vsnprintf(NULL, 0, fmt, args) + 1;
45 buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
50 vsnprintf(buffer, len, fmt, args);
53 kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
54 kunit_kfree(current->kunit_test, buffer);
56 EXPORT_SYMBOL_GPL(__kunit_fail_current_test);
60 * Enable KUnit tests to run.
62 #ifdef CONFIG_KUNIT_DEFAULT_ENABLED
63 static bool enable_param = true;
65 static bool enable_param;
67 module_param_named(enable, enable_param, bool, 0);
68 MODULE_PARM_DESC(enable, "Enable KUnit tests");
71 * KUnit statistic mode:
73 * 1 - only when there is more than one subtest
76 static int kunit_stats_enabled = 1;
77 module_param_named(stats_enabled, kunit_stats_enabled, int, 0644);
78 MODULE_PARM_DESC(stats_enabled,
79 "Print test stats: never (0), only for multiple subtests (1), or always (2)");
81 struct kunit_result_stats {
83 unsigned long skipped;
88 static bool kunit_should_print_stats(struct kunit_result_stats stats)
90 if (kunit_stats_enabled == 0)
93 if (kunit_stats_enabled == 2)
96 return (stats.total > 1);
99 static void kunit_print_test_stats(struct kunit *test,
100 struct kunit_result_stats stats)
102 if (!kunit_should_print_stats(stats))
105 kunit_log(KERN_INFO, test,
107 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
116 * Append formatted message to log, size of which is limited to
117 * KUNIT_LOG_SIZE bytes (including null terminating byte).
119 void kunit_log_append(char *log, const char *fmt, ...)
121 char line[KUNIT_LOG_SIZE];
128 len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
133 vsnprintf(line, sizeof(line), fmt, args);
136 strncat(log, line, len_left);
138 EXPORT_SYMBOL_GPL(kunit_log_append);
140 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
142 struct kunit_case *test_case;
145 kunit_suite_for_each_test_case(suite, test_case)
150 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
152 static void kunit_print_suite_start(struct kunit_suite *suite)
154 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "KTAP version 1\n");
155 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
157 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
158 kunit_suite_num_test_cases(suite));
161 static void kunit_print_ok_not_ok(void *test_or_suite,
163 enum kunit_status status,
165 const char *description,
166 const char *directive)
168 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
169 struct kunit *test = is_test ? test_or_suite : NULL;
170 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
173 * We do not log the test suite results as doing so would
174 * mean debugfs display would consist of the test suite
175 * description and status prior to individual test results.
176 * Hence directly printk the suite status, and we will
177 * separately seq_printf() the suite status for the debugfs
181 pr_info("%s %zd %s%s%s\n",
182 kunit_status_to_ok_not_ok(status),
183 test_number, description, directive_header,
184 (status == KUNIT_SKIPPED) ? directive : "");
186 kunit_log(KERN_INFO, test,
187 KUNIT_SUBTEST_INDENT "%s %zd %s%s%s",
188 kunit_status_to_ok_not_ok(status),
189 test_number, description, directive_header,
190 (status == KUNIT_SKIPPED) ? directive : "");
193 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
195 const struct kunit_case *test_case;
196 enum kunit_status status = KUNIT_SKIPPED;
198 if (suite->suite_init_err)
199 return KUNIT_FAILURE;
201 kunit_suite_for_each_test_case(suite, test_case) {
202 if (test_case->status == KUNIT_FAILURE)
203 return KUNIT_FAILURE;
204 else if (test_case->status == KUNIT_SUCCESS)
205 status = KUNIT_SUCCESS;
210 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
212 static size_t kunit_suite_counter = 1;
214 static void kunit_print_suite_end(struct kunit_suite *suite)
216 kunit_print_ok_not_ok((void *)suite, false,
217 kunit_suite_has_succeeded(suite),
218 kunit_suite_counter++,
220 suite->status_comment);
223 unsigned int kunit_test_case_num(struct kunit_suite *suite,
224 struct kunit_case *test_case)
226 struct kunit_case *tc;
229 kunit_suite_for_each_test_case(suite, tc) {
237 EXPORT_SYMBOL_GPL(kunit_test_case_num);
239 static void kunit_print_string_stream(struct kunit *test,
240 struct string_stream *stream)
242 struct string_stream_fragment *fragment;
245 if (string_stream_is_empty(stream))
248 buf = string_stream_get_string(stream);
251 "Could not allocate buffer, dumping stream:\n");
252 list_for_each_entry(fragment, &stream->fragments, node) {
253 kunit_err(test, "%s", fragment->fragment);
255 kunit_err(test, "\n");
257 kunit_err(test, "%s", buf);
258 kunit_kfree(test, buf);
262 static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
263 enum kunit_assert_type type, const struct kunit_assert *assert,
264 assert_format_t assert_format, const struct va_format *message)
266 struct string_stream *stream;
268 kunit_set_failure(test);
270 stream = alloc_string_stream(test, GFP_KERNEL);
271 if (IS_ERR(stream)) {
273 "Could not allocate stream to print failed assertion in %s:%d\n",
279 kunit_assert_prologue(loc, type, stream);
280 assert_format(assert, message, stream);
282 kunit_print_string_stream(test, stream);
284 string_stream_destroy(stream);
287 static void __noreturn kunit_abort(struct kunit *test)
289 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
292 * Throw could not abort from test.
294 * XXX: we should never reach this line! As kunit_try_catch_throw is
297 WARN_ONCE(true, "Throw could not abort from test!\n");
300 void kunit_do_failed_assertion(struct kunit *test,
301 const struct kunit_loc *loc,
302 enum kunit_assert_type type,
303 const struct kunit_assert *assert,
304 assert_format_t assert_format,
305 const char *fmt, ...)
308 struct va_format message;
314 kunit_fail(test, loc, type, assert, assert_format, &message);
318 if (type == KUNIT_ASSERTION)
321 EXPORT_SYMBOL_GPL(kunit_do_failed_assertion);
323 void kunit_init_test(struct kunit *test, const char *name, char *log)
325 spin_lock_init(&test->lock);
326 INIT_LIST_HEAD(&test->resources);
331 test->status = KUNIT_SUCCESS;
332 test->status_comment[0] = '\0';
334 EXPORT_SYMBOL_GPL(kunit_init_test);
337 * Initializes and runs test case. Does not clean up or do post validations.
339 static void kunit_run_case_internal(struct kunit *test,
340 struct kunit_suite *suite,
341 struct kunit_case *test_case)
346 ret = suite->init(test);
348 kunit_err(test, "failed to initialize: %d\n", ret);
349 kunit_set_failure(test);
354 test_case->run_case(test);
357 static void kunit_case_internal_cleanup(struct kunit *test)
363 * Performs post validations and cleanup after a test case was run.
364 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
366 static void kunit_run_case_cleanup(struct kunit *test,
367 struct kunit_suite *suite)
372 kunit_case_internal_cleanup(test);
375 struct kunit_try_catch_context {
377 struct kunit_suite *suite;
378 struct kunit_case *test_case;
381 static void kunit_try_run_case(void *data)
383 struct kunit_try_catch_context *ctx = data;
384 struct kunit *test = ctx->test;
385 struct kunit_suite *suite = ctx->suite;
386 struct kunit_case *test_case = ctx->test_case;
388 current->kunit_test = test;
391 * kunit_run_case_internal may encounter a fatal error; if it does,
392 * abort will be called, this thread will exit, and finally the parent
393 * thread will resume control and handle any necessary clean up.
395 kunit_run_case_internal(test, suite, test_case);
396 /* This line may never be reached. */
397 kunit_run_case_cleanup(test, suite);
400 static void kunit_catch_run_case(void *data)
402 struct kunit_try_catch_context *ctx = data;
403 struct kunit *test = ctx->test;
404 struct kunit_suite *suite = ctx->suite;
405 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
408 kunit_set_failure(test);
410 * Test case could not finish, we have no idea what state it is
411 * in, so don't do clean up.
413 if (try_exit_code == -ETIMEDOUT) {
414 kunit_err(test, "test case timed out\n");
416 * Unknown internal error occurred preventing test case from
417 * running, so there is nothing to clean up.
420 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
427 * Test case was run, but aborted. It is the test case's business as to
428 * whether it failed or not, we just need to clean up.
430 kunit_run_case_cleanup(test, suite);
434 * Performs all logic to run a test case. It also catches most errors that
435 * occur in a test case and reports them as failures.
437 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
438 struct kunit_case *test_case,
441 struct kunit_try_catch_context context;
442 struct kunit_try_catch *try_catch;
444 kunit_init_test(test, test_case->name, test_case->log);
445 try_catch = &test->try_catch;
447 kunit_try_catch_init(try_catch,
450 kunit_catch_run_case);
452 context.suite = suite;
453 context.test_case = test_case;
454 kunit_try_catch_run(try_catch, &context);
456 /* Propagate the parameter result to the test case. */
457 if (test->status == KUNIT_FAILURE)
458 test_case->status = KUNIT_FAILURE;
459 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
460 test_case->status = KUNIT_SUCCESS;
463 static void kunit_print_suite_stats(struct kunit_suite *suite,
464 struct kunit_result_stats suite_stats,
465 struct kunit_result_stats param_stats)
467 if (kunit_should_print_stats(suite_stats)) {
468 kunit_log(KERN_INFO, suite,
469 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
477 if (kunit_should_print_stats(param_stats)) {
478 kunit_log(KERN_INFO, suite,
479 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
487 static void kunit_update_stats(struct kunit_result_stats *stats,
488 enum kunit_status status)
505 static void kunit_accumulate_stats(struct kunit_result_stats *total,
506 struct kunit_result_stats add)
508 total->passed += add.passed;
509 total->skipped += add.skipped;
510 total->failed += add.failed;
511 total->total += add.total;
514 int kunit_run_tests(struct kunit_suite *suite)
516 char param_desc[KUNIT_PARAM_DESC_SIZE];
517 struct kunit_case *test_case;
518 struct kunit_result_stats suite_stats = { 0 };
519 struct kunit_result_stats total_stats = { 0 };
521 /* Taint the kernel so we know we've run tests. */
522 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
524 if (suite->suite_init) {
525 suite->suite_init_err = suite->suite_init(suite);
526 if (suite->suite_init_err) {
527 kunit_err(suite, KUNIT_SUBTEST_INDENT
528 "# failed to initialize (%d)", suite->suite_init_err);
533 kunit_print_suite_start(suite);
535 kunit_suite_for_each_test_case(suite, test_case) {
536 struct kunit test = { .param_value = NULL, .param_index = 0 };
537 struct kunit_result_stats param_stats = { 0 };
538 test_case->status = KUNIT_SKIPPED;
540 if (!test_case->generate_params) {
541 /* Non-parameterised test. */
542 kunit_run_case_catch_errors(suite, test_case, &test);
543 kunit_update_stats(¶m_stats, test.status);
545 /* Get initial param. */
546 param_desc[0] = '\0';
547 test.param_value = test_case->generate_params(NULL, param_desc);
548 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
550 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
551 "# Subtest: %s", test_case->name);
553 while (test.param_value) {
554 kunit_run_case_catch_errors(suite, test_case, &test);
556 if (param_desc[0] == '\0') {
557 snprintf(param_desc, sizeof(param_desc),
558 "param-%d", test.param_index);
561 kunit_log(KERN_INFO, &test,
562 KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
564 kunit_status_to_ok_not_ok(test.status),
565 test.param_index + 1, param_desc);
567 /* Get next param. */
568 param_desc[0] = '\0';
569 test.param_value = test_case->generate_params(test.param_value, param_desc);
572 kunit_update_stats(¶m_stats, test.status);
577 kunit_print_test_stats(&test, param_stats);
579 kunit_print_ok_not_ok(&test, true, test_case->status,
580 kunit_test_case_num(suite, test_case),
582 test.status_comment);
584 kunit_update_stats(&suite_stats, test_case->status);
585 kunit_accumulate_stats(&total_stats, param_stats);
588 if (suite->suite_exit)
589 suite->suite_exit(suite);
591 kunit_print_suite_stats(suite, suite_stats, total_stats);
593 kunit_print_suite_end(suite);
597 EXPORT_SYMBOL_GPL(kunit_run_tests);
599 static void kunit_init_suite(struct kunit_suite *suite)
601 kunit_debugfs_create_suite(suite);
602 suite->status_comment[0] = '\0';
603 suite->suite_init_err = 0;
606 bool kunit_enabled(void)
611 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
615 if (!kunit_enabled() && num_suites > 0) {
616 pr_info("kunit: disabled\n");
620 static_branch_inc(&kunit_running);
622 for (i = 0; i < num_suites; i++) {
623 kunit_init_suite(suites[i]);
624 kunit_run_tests(suites[i]);
627 static_branch_dec(&kunit_running);
630 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
632 static void kunit_exit_suite(struct kunit_suite *suite)
634 kunit_debugfs_destroy_suite(suite);
637 void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites)
641 if (!kunit_enabled())
644 for (i = 0; i < num_suites; i++)
645 kunit_exit_suite(suites[i]);
647 kunit_suite_counter = 1;
649 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
651 #ifdef CONFIG_MODULES
652 static void kunit_module_init(struct module *mod)
654 __kunit_test_suites_init(mod->kunit_suites, mod->num_kunit_suites);
657 static void kunit_module_exit(struct module *mod)
659 __kunit_test_suites_exit(mod->kunit_suites, mod->num_kunit_suites);
662 static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
665 struct module *mod = data;
668 case MODULE_STATE_LIVE:
669 kunit_module_init(mod);
671 case MODULE_STATE_GOING:
672 kunit_module_exit(mod);
674 case MODULE_STATE_COMING:
675 case MODULE_STATE_UNFORMED:
682 static struct notifier_block kunit_mod_nb = {
683 .notifier_call = kunit_module_notify,
688 struct kunit_kmalloc_array_params {
694 static int kunit_kmalloc_array_init(struct kunit_resource *res, void *context)
696 struct kunit_kmalloc_array_params *params = context;
698 res->data = kmalloc_array(params->n, params->size, params->gfp);
705 static void kunit_kmalloc_array_free(struct kunit_resource *res)
710 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
712 struct kunit_kmalloc_array_params params = {
718 return kunit_alloc_resource(test,
719 kunit_kmalloc_array_init,
720 kunit_kmalloc_array_free,
724 EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
726 static inline bool kunit_kfree_match(struct kunit *test,
727 struct kunit_resource *res, void *match_data)
729 /* Only match resources allocated with kunit_kmalloc() and friends. */
730 return res->free == kunit_kmalloc_array_free && res->data == match_data;
733 void kunit_kfree(struct kunit *test, const void *ptr)
738 if (kunit_destroy_resource(test, kunit_kfree_match, (void *)ptr))
739 KUNIT_FAIL(test, "kunit_kfree: %px already freed or not allocated by kunit", ptr);
741 EXPORT_SYMBOL_GPL(kunit_kfree);
743 void kunit_cleanup(struct kunit *test)
745 struct kunit_resource *res;
749 * test->resources is a stack - each allocation must be freed in the
750 * reverse order from which it was added since one resource may depend
751 * on another for its entire lifetime.
752 * Also, we cannot use the normal list_for_each constructs, even the
753 * safe ones because *arbitrary* nodes may be deleted when
754 * kunit_resource_free is called; the list_for_each_safe variants only
755 * protect against the current node being deleted, not the next.
758 spin_lock_irqsave(&test->lock, flags);
759 if (list_empty(&test->resources)) {
760 spin_unlock_irqrestore(&test->lock, flags);
763 res = list_last_entry(&test->resources,
764 struct kunit_resource,
767 * Need to unlock here as a resource may remove another
768 * resource, and this can't happen if the test->lock
771 spin_unlock_irqrestore(&test->lock, flags);
772 kunit_remove_resource(test, res);
774 current->kunit_test = NULL;
776 EXPORT_SYMBOL_GPL(kunit_cleanup);
778 static int __init kunit_init(void)
780 kunit_debugfs_init();
781 #ifdef CONFIG_MODULES
782 return register_module_notifier(&kunit_mod_nb);
787 late_initcall(kunit_init);
789 static void __exit kunit_exit(void)
791 #ifdef CONFIG_MODULES
792 unregister_module_notifier(&kunit_mod_nb);
794 kunit_debugfs_cleanup();
796 module_exit(kunit_exit);
798 MODULE_LICENSE("GPL v2");