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 "hooks-impl.h"
21 #include "string-stream.h"
22 #include "try-catch-impl.h"
25 * Hook to fail the current test and print an error message to the log.
27 void __printf(3, 4) __kunit_fail_current_test_impl(const char *file, int line, const char *fmt, ...)
33 if (!current->kunit_test)
36 kunit_set_failure(current->kunit_test);
38 /* kunit_err() only accepts literals, so evaluate the args first. */
40 len = vsnprintf(NULL, 0, fmt, args) + 1;
43 buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
48 vsnprintf(buffer, len, fmt, args);
51 kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
52 kunit_kfree(current->kunit_test, buffer);
56 * Enable KUnit tests to run.
58 #ifdef CONFIG_KUNIT_DEFAULT_ENABLED
59 static bool enable_param = true;
61 static bool enable_param;
63 module_param_named(enable, enable_param, bool, 0);
64 MODULE_PARM_DESC(enable, "Enable KUnit tests");
67 * KUnit statistic mode:
69 * 1 - only when there is more than one subtest
72 static int kunit_stats_enabled = 1;
73 module_param_named(stats_enabled, kunit_stats_enabled, int, 0644);
74 MODULE_PARM_DESC(stats_enabled,
75 "Print test stats: never (0), only for multiple subtests (1), or always (2)");
77 struct kunit_result_stats {
79 unsigned long skipped;
84 static bool kunit_should_print_stats(struct kunit_result_stats stats)
86 if (kunit_stats_enabled == 0)
89 if (kunit_stats_enabled == 2)
92 return (stats.total > 1);
95 static void kunit_print_test_stats(struct kunit *test,
96 struct kunit_result_stats stats)
98 if (!kunit_should_print_stats(stats))
101 kunit_log(KERN_INFO, test,
103 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
112 * kunit_log_newline() - Add newline to the end of log if one is not
114 * @log: The log to add the newline to.
116 static void kunit_log_newline(char *log)
118 int log_len, len_left;
120 log_len = strlen(log);
121 len_left = KUNIT_LOG_SIZE - log_len - 1;
123 if (log_len > 0 && log[log_len - 1] != '\n')
124 strncat(log, "\n", len_left);
128 * Append formatted message to log, size of which is limited to
129 * KUNIT_LOG_SIZE bytes (including null terminating byte).
131 void kunit_log_append(char *log, const char *fmt, ...)
134 int len, log_len, len_left;
139 log_len = strlen(log);
140 len_left = KUNIT_LOG_SIZE - log_len - 1;
144 /* Evaluate length of line to add to log */
146 len = vsnprintf(NULL, 0, fmt, args) + 1;
149 /* Print formatted line to the log */
151 vsnprintf(log + log_len, min(len, len_left), fmt, args);
154 /* Add newline to end of log if not already present. */
155 kunit_log_newline(log);
157 EXPORT_SYMBOL_GPL(kunit_log_append);
159 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
161 struct kunit_case *test_case;
164 kunit_suite_for_each_test_case(suite, test_case)
169 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
171 static void kunit_print_suite_start(struct kunit_suite *suite)
174 * We do not log the test suite header as doing so would
175 * mean debugfs display would consist of the test suite
176 * header prior to individual test results.
177 * Hence directly printk the suite status, and we will
178 * separately seq_printf() the suite header for the debugfs
181 pr_info(KUNIT_SUBTEST_INDENT "KTAP version 1\n");
182 pr_info(KUNIT_SUBTEST_INDENT "# Subtest: %s\n",
184 pr_info(KUNIT_SUBTEST_INDENT "1..%zd\n",
185 kunit_suite_num_test_cases(suite));
188 /* Currently supported test levels */
190 KUNIT_LEVEL_SUITE = 0,
192 KUNIT_LEVEL_CASE_PARAM,
195 static void kunit_print_ok_not_ok(struct kunit *test,
196 unsigned int test_level,
197 enum kunit_status status,
199 const char *description,
200 const char *directive)
202 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
203 const char *directive_body = (status == KUNIT_SKIPPED) ? directive : "";
206 * When test is NULL assume that results are from the suite
207 * and today suite results are expected at level 0 only.
209 WARN(!test && test_level, "suite test level can't be %u!\n", test_level);
212 * We do not log the test suite results as doing so would
213 * mean debugfs display would consist of an incorrect test
214 * number. Hence directly printk the suite result, and we will
215 * separately seq_printf() the suite results for the debugfs
219 pr_info("%s %zd %s%s%s\n",
220 kunit_status_to_ok_not_ok(status),
221 test_number, description, directive_header,
224 kunit_log(KERN_INFO, test,
226 KUNIT_INDENT_LEN * test_level, "",
227 kunit_status_to_ok_not_ok(status),
228 test_number, description, directive_header,
232 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
234 const struct kunit_case *test_case;
235 enum kunit_status status = KUNIT_SKIPPED;
237 if (suite->suite_init_err)
238 return KUNIT_FAILURE;
240 kunit_suite_for_each_test_case(suite, test_case) {
241 if (test_case->status == KUNIT_FAILURE)
242 return KUNIT_FAILURE;
243 else if (test_case->status == KUNIT_SUCCESS)
244 status = KUNIT_SUCCESS;
249 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
251 static size_t kunit_suite_counter = 1;
253 static void kunit_print_suite_end(struct kunit_suite *suite)
255 kunit_print_ok_not_ok(NULL, KUNIT_LEVEL_SUITE,
256 kunit_suite_has_succeeded(suite),
257 kunit_suite_counter++,
259 suite->status_comment);
262 unsigned int kunit_test_case_num(struct kunit_suite *suite,
263 struct kunit_case *test_case)
265 struct kunit_case *tc;
268 kunit_suite_for_each_test_case(suite, tc) {
276 EXPORT_SYMBOL_GPL(kunit_test_case_num);
278 static void kunit_print_string_stream(struct kunit *test,
279 struct string_stream *stream)
281 struct string_stream_fragment *fragment;
284 if (string_stream_is_empty(stream))
287 buf = string_stream_get_string(stream);
290 "Could not allocate buffer, dumping stream:\n");
291 list_for_each_entry(fragment, &stream->fragments, node) {
292 kunit_err(test, "%s", fragment->fragment);
294 kunit_err(test, "\n");
296 kunit_err(test, "%s", buf);
297 kunit_kfree(test, buf);
301 static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
302 enum kunit_assert_type type, const struct kunit_assert *assert,
303 assert_format_t assert_format, const struct va_format *message)
305 struct string_stream *stream;
307 kunit_set_failure(test);
309 stream = alloc_string_stream(test, GFP_KERNEL);
310 if (IS_ERR(stream)) {
312 "Could not allocate stream to print failed assertion in %s:%d\n",
318 kunit_assert_prologue(loc, type, stream);
319 assert_format(assert, message, stream);
321 kunit_print_string_stream(test, stream);
323 string_stream_destroy(stream);
326 void __noreturn __kunit_abort(struct kunit *test)
328 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
331 * Throw could not abort from test.
333 * XXX: we should never reach this line! As kunit_try_catch_throw is
336 WARN_ONCE(true, "Throw could not abort from test!\n");
338 EXPORT_SYMBOL_GPL(__kunit_abort);
340 void __kunit_do_failed_assertion(struct kunit *test,
341 const struct kunit_loc *loc,
342 enum kunit_assert_type type,
343 const struct kunit_assert *assert,
344 assert_format_t assert_format,
345 const char *fmt, ...)
348 struct va_format message;
354 kunit_fail(test, loc, type, assert, assert_format, &message);
358 EXPORT_SYMBOL_GPL(__kunit_do_failed_assertion);
360 void kunit_init_test(struct kunit *test, const char *name, char *log)
362 spin_lock_init(&test->lock);
363 INIT_LIST_HEAD(&test->resources);
368 test->status = KUNIT_SUCCESS;
369 test->status_comment[0] = '\0';
371 EXPORT_SYMBOL_GPL(kunit_init_test);
374 * Initializes and runs test case. Does not clean up or do post validations.
376 static void kunit_run_case_internal(struct kunit *test,
377 struct kunit_suite *suite,
378 struct kunit_case *test_case)
383 ret = suite->init(test);
385 kunit_err(test, "failed to initialize: %d\n", ret);
386 kunit_set_failure(test);
391 test_case->run_case(test);
394 static void kunit_case_internal_cleanup(struct kunit *test)
400 * Performs post validations and cleanup after a test case was run.
401 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
403 static void kunit_run_case_cleanup(struct kunit *test,
404 struct kunit_suite *suite)
409 kunit_case_internal_cleanup(test);
412 struct kunit_try_catch_context {
414 struct kunit_suite *suite;
415 struct kunit_case *test_case;
418 static void kunit_try_run_case(void *data)
420 struct kunit_try_catch_context *ctx = data;
421 struct kunit *test = ctx->test;
422 struct kunit_suite *suite = ctx->suite;
423 struct kunit_case *test_case = ctx->test_case;
425 current->kunit_test = test;
428 * kunit_run_case_internal may encounter a fatal error; if it does,
429 * abort will be called, this thread will exit, and finally the parent
430 * thread will resume control and handle any necessary clean up.
432 kunit_run_case_internal(test, suite, test_case);
435 static void kunit_try_run_case_cleanup(void *data)
437 struct kunit_try_catch_context *ctx = data;
438 struct kunit *test = ctx->test;
439 struct kunit_suite *suite = ctx->suite;
441 current->kunit_test = test;
443 kunit_run_case_cleanup(test, suite);
446 static void kunit_catch_run_case_cleanup(void *data)
448 struct kunit_try_catch_context *ctx = data;
449 struct kunit *test = ctx->test;
450 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
452 /* It is always a failure if cleanup aborts. */
453 kunit_set_failure(test);
457 * Test case could not finish, we have no idea what state it is
458 * in, so don't do clean up.
460 if (try_exit_code == -ETIMEDOUT) {
461 kunit_err(test, "test case cleanup timed out\n");
463 * Unknown internal error occurred preventing test case from
464 * running, so there is nothing to clean up.
467 kunit_err(test, "internal error occurred during test case cleanup: %d\n",
473 kunit_err(test, "test aborted during cleanup. continuing without cleaning up\n");
477 static void kunit_catch_run_case(void *data)
479 struct kunit_try_catch_context *ctx = data;
480 struct kunit *test = ctx->test;
481 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
484 kunit_set_failure(test);
486 * Test case could not finish, we have no idea what state it is
487 * in, so don't do clean up.
489 if (try_exit_code == -ETIMEDOUT) {
490 kunit_err(test, "test case timed out\n");
492 * Unknown internal error occurred preventing test case from
493 * running, so there is nothing to clean up.
496 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
504 * Performs all logic to run a test case. It also catches most errors that
505 * occur in a test case and reports them as failures.
507 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
508 struct kunit_case *test_case,
511 struct kunit_try_catch_context context;
512 struct kunit_try_catch *try_catch;
514 try_catch = &test->try_catch;
516 kunit_try_catch_init(try_catch,
519 kunit_catch_run_case);
521 context.suite = suite;
522 context.test_case = test_case;
523 kunit_try_catch_run(try_catch, &context);
525 /* Now run the cleanup */
526 kunit_try_catch_init(try_catch,
528 kunit_try_run_case_cleanup,
529 kunit_catch_run_case_cleanup);
530 kunit_try_catch_run(try_catch, &context);
532 /* Propagate the parameter result to the test case. */
533 if (test->status == KUNIT_FAILURE)
534 test_case->status = KUNIT_FAILURE;
535 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
536 test_case->status = KUNIT_SUCCESS;
539 static void kunit_print_suite_stats(struct kunit_suite *suite,
540 struct kunit_result_stats suite_stats,
541 struct kunit_result_stats param_stats)
543 if (kunit_should_print_stats(suite_stats)) {
544 kunit_log(KERN_INFO, suite,
545 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
553 if (kunit_should_print_stats(param_stats)) {
554 kunit_log(KERN_INFO, suite,
555 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
563 static void kunit_update_stats(struct kunit_result_stats *stats,
564 enum kunit_status status)
581 static void kunit_accumulate_stats(struct kunit_result_stats *total,
582 struct kunit_result_stats add)
584 total->passed += add.passed;
585 total->skipped += add.skipped;
586 total->failed += add.failed;
587 total->total += add.total;
590 int kunit_run_tests(struct kunit_suite *suite)
592 char param_desc[KUNIT_PARAM_DESC_SIZE];
593 struct kunit_case *test_case;
594 struct kunit_result_stats suite_stats = { 0 };
595 struct kunit_result_stats total_stats = { 0 };
597 /* Taint the kernel so we know we've run tests. */
598 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
600 if (suite->suite_init) {
601 suite->suite_init_err = suite->suite_init(suite);
602 if (suite->suite_init_err) {
603 kunit_err(suite, KUNIT_SUBTEST_INDENT
604 "# failed to initialize (%d)", suite->suite_init_err);
609 kunit_print_suite_start(suite);
611 kunit_suite_for_each_test_case(suite, test_case) {
612 struct kunit test = { .param_value = NULL, .param_index = 0 };
613 struct kunit_result_stats param_stats = { 0 };
614 test_case->status = KUNIT_SKIPPED;
616 kunit_init_test(&test, test_case->name, test_case->log);
618 if (!test_case->generate_params) {
619 /* Non-parameterised test. */
620 kunit_run_case_catch_errors(suite, test_case, &test);
621 kunit_update_stats(¶m_stats, test.status);
623 /* Get initial param. */
624 param_desc[0] = '\0';
625 test.param_value = test_case->generate_params(NULL, param_desc);
626 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
628 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
629 "# Subtest: %s", test_case->name);
631 while (test.param_value) {
632 kunit_run_case_catch_errors(suite, test_case, &test);
634 if (param_desc[0] == '\0') {
635 snprintf(param_desc, sizeof(param_desc),
636 "param-%d", test.param_index);
639 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE_PARAM,
641 test.param_index + 1,
643 test.status_comment);
645 /* Get next param. */
646 param_desc[0] = '\0';
647 test.param_value = test_case->generate_params(test.param_value, param_desc);
650 kunit_update_stats(¶m_stats, test.status);
655 kunit_print_test_stats(&test, param_stats);
657 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE, test_case->status,
658 kunit_test_case_num(suite, test_case),
660 test.status_comment);
662 kunit_update_stats(&suite_stats, test_case->status);
663 kunit_accumulate_stats(&total_stats, param_stats);
666 if (suite->suite_exit)
667 suite->suite_exit(suite);
669 kunit_print_suite_stats(suite, suite_stats, total_stats);
671 kunit_print_suite_end(suite);
675 EXPORT_SYMBOL_GPL(kunit_run_tests);
677 static void kunit_init_suite(struct kunit_suite *suite)
679 kunit_debugfs_create_suite(suite);
680 suite->status_comment[0] = '\0';
681 suite->suite_init_err = 0;
684 bool kunit_enabled(void)
689 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
693 if (!kunit_enabled() && num_suites > 0) {
694 pr_info("kunit: disabled\n");
698 static_branch_inc(&kunit_running);
700 for (i = 0; i < num_suites; i++) {
701 kunit_init_suite(suites[i]);
702 kunit_run_tests(suites[i]);
705 static_branch_dec(&kunit_running);
708 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
710 static void kunit_exit_suite(struct kunit_suite *suite)
712 kunit_debugfs_destroy_suite(suite);
715 void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites)
719 if (!kunit_enabled())
722 for (i = 0; i < num_suites; i++)
723 kunit_exit_suite(suites[i]);
725 kunit_suite_counter = 1;
727 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
729 #ifdef CONFIG_MODULES
730 static void kunit_module_init(struct module *mod)
732 __kunit_test_suites_init(mod->kunit_suites, mod->num_kunit_suites);
735 static void kunit_module_exit(struct module *mod)
737 __kunit_test_suites_exit(mod->kunit_suites, mod->num_kunit_suites);
740 static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
743 struct module *mod = data;
746 case MODULE_STATE_LIVE:
747 kunit_module_init(mod);
749 case MODULE_STATE_GOING:
750 kunit_module_exit(mod);
752 case MODULE_STATE_COMING:
753 case MODULE_STATE_UNFORMED:
760 static struct notifier_block kunit_mod_nb = {
761 .notifier_call = kunit_module_notify,
766 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
770 data = kmalloc_array(n, size, gfp);
775 if (kunit_add_action_or_reset(test, (kunit_action_t *)kfree, data) != 0)
780 EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
782 void kunit_kfree(struct kunit *test, const void *ptr)
787 kunit_release_action(test, (kunit_action_t *)kfree, (void *)ptr);
789 EXPORT_SYMBOL_GPL(kunit_kfree);
791 void kunit_cleanup(struct kunit *test)
793 struct kunit_resource *res;
797 * test->resources is a stack - each allocation must be freed in the
798 * reverse order from which it was added since one resource may depend
799 * on another for its entire lifetime.
800 * Also, we cannot use the normal list_for_each constructs, even the
801 * safe ones because *arbitrary* nodes may be deleted when
802 * kunit_resource_free is called; the list_for_each_safe variants only
803 * protect against the current node being deleted, not the next.
806 spin_lock_irqsave(&test->lock, flags);
807 if (list_empty(&test->resources)) {
808 spin_unlock_irqrestore(&test->lock, flags);
811 res = list_last_entry(&test->resources,
812 struct kunit_resource,
815 * Need to unlock here as a resource may remove another
816 * resource, and this can't happen if the test->lock
819 spin_unlock_irqrestore(&test->lock, flags);
820 kunit_remove_resource(test, res);
822 current->kunit_test = NULL;
824 EXPORT_SYMBOL_GPL(kunit_cleanup);
826 static int __init kunit_init(void)
828 /* Install the KUnit hook functions. */
829 kunit_install_hooks();
831 kunit_debugfs_init();
832 #ifdef CONFIG_MODULES
833 return register_module_notifier(&kunit_mod_nb);
838 late_initcall(kunit_init);
840 static void __exit kunit_exit(void)
842 memset(&kunit_hooks, 0, sizeof(kunit_hooks));
843 #ifdef CONFIG_MODULES
844 unregister_module_notifier(&kunit_mod_nb);
846 kunit_debugfs_cleanup();
848 module_exit(kunit_exit);
850 MODULE_LICENSE("GPL v2");