1 // SPDX-License-Identifier: GPL-2.0
3 * Base unit test (KUnit) API.
5 * Copyright (C) 2019, Google LLC.
6 * Author: Brendan Higgins <brendanhiggins@google.com>
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 #if IS_BUILTIN(CONFIG_KUNIT)
25 * Fail the current test and print an error message to the log.
27 void __kunit_fail_current_test(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);
54 EXPORT_SYMBOL_GPL(__kunit_fail_current_test);
58 * Enable KUnit tests to run.
60 #ifdef CONFIG_KUNIT_DEFAULT_ENABLED
61 static bool enable_param = true;
63 static bool enable_param;
65 module_param_named(enable, enable_param, bool, 0);
66 MODULE_PARM_DESC(enable, "Enable KUnit tests");
69 * KUnit statistic mode:
71 * 1 - only when there is more than one subtest
74 static int kunit_stats_enabled = 1;
75 module_param_named(stats_enabled, kunit_stats_enabled, int, 0644);
76 MODULE_PARM_DESC(stats_enabled,
77 "Print test stats: never (0), only for multiple subtests (1), or always (2)");
79 struct kunit_result_stats {
81 unsigned long skipped;
86 static bool kunit_should_print_stats(struct kunit_result_stats stats)
88 if (kunit_stats_enabled == 0)
91 if (kunit_stats_enabled == 2)
94 return (stats.total > 1);
97 static void kunit_print_test_stats(struct kunit *test,
98 struct kunit_result_stats stats)
100 if (!kunit_should_print_stats(stats))
103 kunit_log(KERN_INFO, test,
105 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
114 * Append formatted message to log, size of which is limited to
115 * KUNIT_LOG_SIZE bytes (including null terminating byte).
117 void kunit_log_append(char *log, const char *fmt, ...)
119 char line[KUNIT_LOG_SIZE];
126 len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
131 vsnprintf(line, sizeof(line), fmt, args);
134 strncat(log, line, len_left);
136 EXPORT_SYMBOL_GPL(kunit_log_append);
138 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
140 struct kunit_case *test_case;
143 kunit_suite_for_each_test_case(suite, test_case)
148 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
150 static void kunit_print_suite_start(struct kunit_suite *suite)
153 * We do not log the test suite header as doing so would
154 * mean debugfs display would consist of the test suite
155 * header prior to individual test results.
156 * Hence directly printk the suite status, and we will
157 * separately seq_printf() the suite header for the debugfs
160 pr_info(KUNIT_SUBTEST_INDENT "KTAP version 1\n");
161 pr_info(KUNIT_SUBTEST_INDENT "# Subtest: %s\n",
163 pr_info(KUNIT_SUBTEST_INDENT "1..%zd\n",
164 kunit_suite_num_test_cases(suite));
167 static void kunit_print_ok_not_ok(void *test_or_suite,
169 enum kunit_status status,
171 const char *description,
172 const char *directive)
174 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
175 struct kunit *test = is_test ? test_or_suite : NULL;
176 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
179 * We do not log the test suite results as doing so would
180 * mean debugfs display would consist of an incorrect test
181 * number. Hence directly printk the suite result, and we will
182 * separately seq_printf() the suite results for the debugfs
186 pr_info("%s %zd %s%s%s\n",
187 kunit_status_to_ok_not_ok(status),
188 test_number, description, directive_header,
189 (status == KUNIT_SKIPPED) ? directive : "");
191 kunit_log(KERN_INFO, test,
192 KUNIT_SUBTEST_INDENT "%s %zd %s%s%s",
193 kunit_status_to_ok_not_ok(status),
194 test_number, description, directive_header,
195 (status == KUNIT_SKIPPED) ? directive : "");
198 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
200 const struct kunit_case *test_case;
201 enum kunit_status status = KUNIT_SKIPPED;
203 if (suite->suite_init_err)
204 return KUNIT_FAILURE;
206 kunit_suite_for_each_test_case(suite, test_case) {
207 if (test_case->status == KUNIT_FAILURE)
208 return KUNIT_FAILURE;
209 else if (test_case->status == KUNIT_SUCCESS)
210 status = KUNIT_SUCCESS;
215 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
217 static size_t kunit_suite_counter = 1;
219 static void kunit_print_suite_end(struct kunit_suite *suite)
221 kunit_print_ok_not_ok((void *)suite, false,
222 kunit_suite_has_succeeded(suite),
223 kunit_suite_counter++,
225 suite->status_comment);
228 unsigned int kunit_test_case_num(struct kunit_suite *suite,
229 struct kunit_case *test_case)
231 struct kunit_case *tc;
234 kunit_suite_for_each_test_case(suite, tc) {
242 EXPORT_SYMBOL_GPL(kunit_test_case_num);
244 static void kunit_print_string_stream(struct kunit *test,
245 struct string_stream *stream)
247 struct string_stream_fragment *fragment;
250 if (string_stream_is_empty(stream))
253 buf = string_stream_get_string(stream);
256 "Could not allocate buffer, dumping stream:\n");
257 list_for_each_entry(fragment, &stream->fragments, node) {
258 kunit_err(test, "%s", fragment->fragment);
260 kunit_err(test, "\n");
262 kunit_err(test, "%s", buf);
263 kunit_kfree(test, buf);
267 static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
268 enum kunit_assert_type type, const struct kunit_assert *assert,
269 assert_format_t assert_format, const struct va_format *message)
271 struct string_stream *stream;
273 kunit_set_failure(test);
275 stream = alloc_string_stream(test, GFP_KERNEL);
276 if (IS_ERR(stream)) {
278 "Could not allocate stream to print failed assertion in %s:%d\n",
284 kunit_assert_prologue(loc, type, stream);
285 assert_format(assert, message, stream);
287 kunit_print_string_stream(test, stream);
289 string_stream_destroy(stream);
292 static void __noreturn kunit_abort(struct kunit *test)
294 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
297 * Throw could not abort from test.
299 * XXX: we should never reach this line! As kunit_try_catch_throw is
302 WARN_ONCE(true, "Throw could not abort from test!\n");
305 void kunit_do_failed_assertion(struct kunit *test,
306 const struct kunit_loc *loc,
307 enum kunit_assert_type type,
308 const struct kunit_assert *assert,
309 assert_format_t assert_format,
310 const char *fmt, ...)
313 struct va_format message;
319 kunit_fail(test, loc, type, assert, assert_format, &message);
323 if (type == KUNIT_ASSERTION)
326 EXPORT_SYMBOL_GPL(kunit_do_failed_assertion);
328 void kunit_init_test(struct kunit *test, const char *name, char *log)
330 spin_lock_init(&test->lock);
331 INIT_LIST_HEAD(&test->resources);
336 test->status = KUNIT_SUCCESS;
337 test->status_comment[0] = '\0';
339 EXPORT_SYMBOL_GPL(kunit_init_test);
342 * Initializes and runs test case. Does not clean up or do post validations.
344 static void kunit_run_case_internal(struct kunit *test,
345 struct kunit_suite *suite,
346 struct kunit_case *test_case)
351 ret = suite->init(test);
353 kunit_err(test, "failed to initialize: %d\n", ret);
354 kunit_set_failure(test);
359 test_case->run_case(test);
362 static void kunit_case_internal_cleanup(struct kunit *test)
368 * Performs post validations and cleanup after a test case was run.
369 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
371 static void kunit_run_case_cleanup(struct kunit *test,
372 struct kunit_suite *suite)
377 kunit_case_internal_cleanup(test);
380 struct kunit_try_catch_context {
382 struct kunit_suite *suite;
383 struct kunit_case *test_case;
386 static void kunit_try_run_case(void *data)
388 struct kunit_try_catch_context *ctx = data;
389 struct kunit *test = ctx->test;
390 struct kunit_suite *suite = ctx->suite;
391 struct kunit_case *test_case = ctx->test_case;
393 current->kunit_test = test;
396 * kunit_run_case_internal may encounter a fatal error; if it does,
397 * abort will be called, this thread will exit, and finally the parent
398 * thread will resume control and handle any necessary clean up.
400 kunit_run_case_internal(test, suite, test_case);
401 /* This line may never be reached. */
402 kunit_run_case_cleanup(test, suite);
405 static void kunit_catch_run_case(void *data)
407 struct kunit_try_catch_context *ctx = data;
408 struct kunit *test = ctx->test;
409 struct kunit_suite *suite = ctx->suite;
410 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
413 kunit_set_failure(test);
415 * Test case could not finish, we have no idea what state it is
416 * in, so don't do clean up.
418 if (try_exit_code == -ETIMEDOUT) {
419 kunit_err(test, "test case timed out\n");
421 * Unknown internal error occurred preventing test case from
422 * running, so there is nothing to clean up.
425 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
432 * Test case was run, but aborted. It is the test case's business as to
433 * whether it failed or not, we just need to clean up.
435 kunit_run_case_cleanup(test, suite);
439 * Performs all logic to run a test case. It also catches most errors that
440 * occur in a test case and reports them as failures.
442 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
443 struct kunit_case *test_case,
446 struct kunit_try_catch_context context;
447 struct kunit_try_catch *try_catch;
449 kunit_init_test(test, test_case->name, test_case->log);
450 try_catch = &test->try_catch;
452 kunit_try_catch_init(try_catch,
455 kunit_catch_run_case);
457 context.suite = suite;
458 context.test_case = test_case;
459 kunit_try_catch_run(try_catch, &context);
461 /* Propagate the parameter result to the test case. */
462 if (test->status == KUNIT_FAILURE)
463 test_case->status = KUNIT_FAILURE;
464 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
465 test_case->status = KUNIT_SUCCESS;
468 static void kunit_print_suite_stats(struct kunit_suite *suite,
469 struct kunit_result_stats suite_stats,
470 struct kunit_result_stats param_stats)
472 if (kunit_should_print_stats(suite_stats)) {
473 kunit_log(KERN_INFO, suite,
474 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
482 if (kunit_should_print_stats(param_stats)) {
483 kunit_log(KERN_INFO, suite,
484 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
492 static void kunit_update_stats(struct kunit_result_stats *stats,
493 enum kunit_status status)
510 static void kunit_accumulate_stats(struct kunit_result_stats *total,
511 struct kunit_result_stats add)
513 total->passed += add.passed;
514 total->skipped += add.skipped;
515 total->failed += add.failed;
516 total->total += add.total;
519 int kunit_run_tests(struct kunit_suite *suite)
521 char param_desc[KUNIT_PARAM_DESC_SIZE];
522 struct kunit_case *test_case;
523 struct kunit_result_stats suite_stats = { 0 };
524 struct kunit_result_stats total_stats = { 0 };
526 /* Taint the kernel so we know we've run tests. */
527 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
529 if (suite->suite_init) {
530 suite->suite_init_err = suite->suite_init(suite);
531 if (suite->suite_init_err) {
532 kunit_err(suite, KUNIT_SUBTEST_INDENT
533 "# failed to initialize (%d)", suite->suite_init_err);
538 kunit_print_suite_start(suite);
540 kunit_suite_for_each_test_case(suite, test_case) {
541 struct kunit test = { .param_value = NULL, .param_index = 0 };
542 struct kunit_result_stats param_stats = { 0 };
543 test_case->status = KUNIT_SKIPPED;
545 if (!test_case->generate_params) {
546 /* Non-parameterised test. */
547 kunit_run_case_catch_errors(suite, test_case, &test);
548 kunit_update_stats(¶m_stats, test.status);
550 /* Get initial param. */
551 param_desc[0] = '\0';
552 test.param_value = test_case->generate_params(NULL, param_desc);
553 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
555 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
556 "# Subtest: %s", test_case->name);
558 while (test.param_value) {
559 kunit_run_case_catch_errors(suite, test_case, &test);
561 if (param_desc[0] == '\0') {
562 snprintf(param_desc, sizeof(param_desc),
563 "param-%d", test.param_index);
566 kunit_log(KERN_INFO, &test,
567 KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
569 kunit_status_to_ok_not_ok(test.status),
570 test.param_index + 1, param_desc);
572 /* Get next param. */
573 param_desc[0] = '\0';
574 test.param_value = test_case->generate_params(test.param_value, param_desc);
577 kunit_update_stats(¶m_stats, test.status);
582 kunit_print_test_stats(&test, param_stats);
584 kunit_print_ok_not_ok(&test, true, test_case->status,
585 kunit_test_case_num(suite, test_case),
587 test.status_comment);
589 kunit_update_stats(&suite_stats, test_case->status);
590 kunit_accumulate_stats(&total_stats, param_stats);
593 if (suite->suite_exit)
594 suite->suite_exit(suite);
596 kunit_print_suite_stats(suite, suite_stats, total_stats);
598 kunit_print_suite_end(suite);
602 EXPORT_SYMBOL_GPL(kunit_run_tests);
604 static void kunit_init_suite(struct kunit_suite *suite)
606 kunit_debugfs_create_suite(suite);
607 suite->status_comment[0] = '\0';
608 suite->suite_init_err = 0;
611 bool kunit_enabled(void)
616 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
620 if (!kunit_enabled() && num_suites > 0) {
621 pr_info("kunit: disabled\n");
625 for (i = 0; i < num_suites; i++) {
626 kunit_init_suite(suites[i]);
627 kunit_run_tests(suites[i]);
631 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
633 static void kunit_exit_suite(struct kunit_suite *suite)
635 kunit_debugfs_destroy_suite(suite);
638 void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites)
642 if (!kunit_enabled())
645 for (i = 0; i < num_suites; i++)
646 kunit_exit_suite(suites[i]);
648 kunit_suite_counter = 1;
650 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
652 #ifdef CONFIG_MODULES
653 static void kunit_module_init(struct module *mod)
655 __kunit_test_suites_init(mod->kunit_suites, mod->num_kunit_suites);
658 static void kunit_module_exit(struct module *mod)
660 __kunit_test_suites_exit(mod->kunit_suites, mod->num_kunit_suites);
663 static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
666 struct module *mod = data;
669 case MODULE_STATE_LIVE:
670 kunit_module_init(mod);
672 case MODULE_STATE_GOING:
673 kunit_module_exit(mod);
675 case MODULE_STATE_COMING:
676 case MODULE_STATE_UNFORMED:
683 static struct notifier_block kunit_mod_nb = {
684 .notifier_call = kunit_module_notify,
689 struct kunit_kmalloc_array_params {
695 static int kunit_kmalloc_array_init(struct kunit_resource *res, void *context)
697 struct kunit_kmalloc_array_params *params = context;
699 res->data = kmalloc_array(params->n, params->size, params->gfp);
706 static void kunit_kmalloc_array_free(struct kunit_resource *res)
711 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
713 struct kunit_kmalloc_array_params params = {
719 return kunit_alloc_resource(test,
720 kunit_kmalloc_array_init,
721 kunit_kmalloc_array_free,
725 EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
727 static inline bool kunit_kfree_match(struct kunit *test,
728 struct kunit_resource *res, void *match_data)
730 /* Only match resources allocated with kunit_kmalloc() and friends. */
731 return res->free == kunit_kmalloc_array_free && res->data == match_data;
734 void kunit_kfree(struct kunit *test, const void *ptr)
739 if (kunit_destroy_resource(test, kunit_kfree_match, (void *)ptr))
740 KUNIT_FAIL(test, "kunit_kfree: %px already freed or not allocated by kunit", ptr);
742 EXPORT_SYMBOL_GPL(kunit_kfree);
744 void kunit_cleanup(struct kunit *test)
746 struct kunit_resource *res;
750 * test->resources is a stack - each allocation must be freed in the
751 * reverse order from which it was added since one resource may depend
752 * on another for its entire lifetime.
753 * Also, we cannot use the normal list_for_each constructs, even the
754 * safe ones because *arbitrary* nodes may be deleted when
755 * kunit_resource_free is called; the list_for_each_safe variants only
756 * protect against the current node being deleted, not the next.
759 spin_lock_irqsave(&test->lock, flags);
760 if (list_empty(&test->resources)) {
761 spin_unlock_irqrestore(&test->lock, flags);
764 res = list_last_entry(&test->resources,
765 struct kunit_resource,
768 * Need to unlock here as a resource may remove another
769 * resource, and this can't happen if the test->lock
772 spin_unlock_irqrestore(&test->lock, flags);
773 kunit_remove_resource(test, res);
775 current->kunit_test = NULL;
777 EXPORT_SYMBOL_GPL(kunit_cleanup);
779 static int __init kunit_init(void)
781 kunit_debugfs_init();
782 #ifdef CONFIG_MODULES
783 return register_module_notifier(&kunit_mod_nb);
788 late_initcall(kunit_init);
790 static void __exit kunit_exit(void)
792 #ifdef CONFIG_MODULES
793 unregister_module_notifier(&kunit_mod_nb);
795 kunit_debugfs_cleanup();
797 module_exit(kunit_exit);
799 MODULE_LICENSE("GPL v2");