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)
152 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
154 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
155 kunit_suite_num_test_cases(suite));
158 static void kunit_print_ok_not_ok(void *test_or_suite,
160 enum kunit_status status,
162 const char *description,
163 const char *directive)
165 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
166 struct kunit *test = is_test ? test_or_suite : NULL;
167 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
170 * We do not log the test suite results as doing so would
171 * mean debugfs display would consist of the test suite
172 * description and status prior to individual test results.
173 * Hence directly printk the suite status, and we will
174 * separately seq_printf() the suite status for the debugfs
178 pr_info("%s %zd - %s%s%s\n",
179 kunit_status_to_ok_not_ok(status),
180 test_number, description, directive_header,
181 (status == KUNIT_SKIPPED) ? directive : "");
183 kunit_log(KERN_INFO, test,
184 KUNIT_SUBTEST_INDENT "%s %zd - %s%s%s",
185 kunit_status_to_ok_not_ok(status),
186 test_number, description, directive_header,
187 (status == KUNIT_SKIPPED) ? directive : "");
190 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
192 const struct kunit_case *test_case;
193 enum kunit_status status = KUNIT_SKIPPED;
195 if (suite->suite_init_err)
196 return KUNIT_FAILURE;
198 kunit_suite_for_each_test_case(suite, test_case) {
199 if (test_case->status == KUNIT_FAILURE)
200 return KUNIT_FAILURE;
201 else if (test_case->status == KUNIT_SUCCESS)
202 status = KUNIT_SUCCESS;
207 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
209 static size_t kunit_suite_counter = 1;
211 static void kunit_print_suite_end(struct kunit_suite *suite)
213 kunit_print_ok_not_ok((void *)suite, false,
214 kunit_suite_has_succeeded(suite),
215 kunit_suite_counter++,
217 suite->status_comment);
220 unsigned int kunit_test_case_num(struct kunit_suite *suite,
221 struct kunit_case *test_case)
223 struct kunit_case *tc;
226 kunit_suite_for_each_test_case(suite, tc) {
234 EXPORT_SYMBOL_GPL(kunit_test_case_num);
236 static void kunit_print_string_stream(struct kunit *test,
237 struct string_stream *stream)
239 struct string_stream_fragment *fragment;
242 if (string_stream_is_empty(stream))
245 buf = string_stream_get_string(stream);
248 "Could not allocate buffer, dumping stream:\n");
249 list_for_each_entry(fragment, &stream->fragments, node) {
250 kunit_err(test, "%s", fragment->fragment);
252 kunit_err(test, "\n");
254 kunit_err(test, "%s", buf);
255 kunit_kfree(test, buf);
259 static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
260 enum kunit_assert_type type, const struct kunit_assert *assert,
261 assert_format_t assert_format, const struct va_format *message)
263 struct string_stream *stream;
265 kunit_set_failure(test);
267 stream = alloc_string_stream(test, GFP_KERNEL);
268 if (IS_ERR(stream)) {
270 "Could not allocate stream to print failed assertion in %s:%d\n",
276 kunit_assert_prologue(loc, type, stream);
277 assert_format(assert, message, stream);
279 kunit_print_string_stream(test, stream);
281 string_stream_destroy(stream);
284 static void __noreturn kunit_abort(struct kunit *test)
286 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
289 * Throw could not abort from test.
291 * XXX: we should never reach this line! As kunit_try_catch_throw is
294 WARN_ONCE(true, "Throw could not abort from test!\n");
297 void kunit_do_failed_assertion(struct kunit *test,
298 const struct kunit_loc *loc,
299 enum kunit_assert_type type,
300 const struct kunit_assert *assert,
301 assert_format_t assert_format,
302 const char *fmt, ...)
305 struct va_format message;
311 kunit_fail(test, loc, type, assert, assert_format, &message);
315 if (type == KUNIT_ASSERTION)
318 EXPORT_SYMBOL_GPL(kunit_do_failed_assertion);
320 void kunit_init_test(struct kunit *test, const char *name, char *log)
322 spin_lock_init(&test->lock);
323 INIT_LIST_HEAD(&test->resources);
328 test->status = KUNIT_SUCCESS;
329 test->status_comment[0] = '\0';
331 EXPORT_SYMBOL_GPL(kunit_init_test);
334 * Initializes and runs test case. Does not clean up or do post validations.
336 static void kunit_run_case_internal(struct kunit *test,
337 struct kunit_suite *suite,
338 struct kunit_case *test_case)
343 ret = suite->init(test);
345 kunit_err(test, "failed to initialize: %d\n", ret);
346 kunit_set_failure(test);
351 test_case->run_case(test);
354 static void kunit_case_internal_cleanup(struct kunit *test)
360 * Performs post validations and cleanup after a test case was run.
361 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
363 static void kunit_run_case_cleanup(struct kunit *test,
364 struct kunit_suite *suite)
369 kunit_case_internal_cleanup(test);
372 struct kunit_try_catch_context {
374 struct kunit_suite *suite;
375 struct kunit_case *test_case;
378 static void kunit_try_run_case(void *data)
380 struct kunit_try_catch_context *ctx = data;
381 struct kunit *test = ctx->test;
382 struct kunit_suite *suite = ctx->suite;
383 struct kunit_case *test_case = ctx->test_case;
385 current->kunit_test = test;
388 * kunit_run_case_internal may encounter a fatal error; if it does,
389 * abort will be called, this thread will exit, and finally the parent
390 * thread will resume control and handle any necessary clean up.
392 kunit_run_case_internal(test, suite, test_case);
393 /* This line may never be reached. */
394 kunit_run_case_cleanup(test, suite);
397 static void kunit_catch_run_case(void *data)
399 struct kunit_try_catch_context *ctx = data;
400 struct kunit *test = ctx->test;
401 struct kunit_suite *suite = ctx->suite;
402 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
405 kunit_set_failure(test);
407 * Test case could not finish, we have no idea what state it is
408 * in, so don't do clean up.
410 if (try_exit_code == -ETIMEDOUT) {
411 kunit_err(test, "test case timed out\n");
413 * Unknown internal error occurred preventing test case from
414 * running, so there is nothing to clean up.
417 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
424 * Test case was run, but aborted. It is the test case's business as to
425 * whether it failed or not, we just need to clean up.
427 kunit_run_case_cleanup(test, suite);
431 * Performs all logic to run a test case. It also catches most errors that
432 * occur in a test case and reports them as failures.
434 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
435 struct kunit_case *test_case,
438 struct kunit_try_catch_context context;
439 struct kunit_try_catch *try_catch;
441 kunit_init_test(test, test_case->name, test_case->log);
442 try_catch = &test->try_catch;
444 kunit_try_catch_init(try_catch,
447 kunit_catch_run_case);
449 context.suite = suite;
450 context.test_case = test_case;
451 kunit_try_catch_run(try_catch, &context);
453 /* Propagate the parameter result to the test case. */
454 if (test->status == KUNIT_FAILURE)
455 test_case->status = KUNIT_FAILURE;
456 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
457 test_case->status = KUNIT_SUCCESS;
460 static void kunit_print_suite_stats(struct kunit_suite *suite,
461 struct kunit_result_stats suite_stats,
462 struct kunit_result_stats param_stats)
464 if (kunit_should_print_stats(suite_stats)) {
465 kunit_log(KERN_INFO, suite,
466 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
474 if (kunit_should_print_stats(param_stats)) {
475 kunit_log(KERN_INFO, suite,
476 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
484 static void kunit_update_stats(struct kunit_result_stats *stats,
485 enum kunit_status status)
502 static void kunit_accumulate_stats(struct kunit_result_stats *total,
503 struct kunit_result_stats add)
505 total->passed += add.passed;
506 total->skipped += add.skipped;
507 total->failed += add.failed;
508 total->total += add.total;
511 int kunit_run_tests(struct kunit_suite *suite)
513 char param_desc[KUNIT_PARAM_DESC_SIZE];
514 struct kunit_case *test_case;
515 struct kunit_result_stats suite_stats = { 0 };
516 struct kunit_result_stats total_stats = { 0 };
518 /* Taint the kernel so we know we've run tests. */
519 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
521 if (suite->suite_init) {
522 suite->suite_init_err = suite->suite_init(suite);
523 if (suite->suite_init_err) {
524 kunit_err(suite, KUNIT_SUBTEST_INDENT
525 "# failed to initialize (%d)", suite->suite_init_err);
530 kunit_print_suite_start(suite);
532 kunit_suite_for_each_test_case(suite, test_case) {
533 struct kunit test = { .param_value = NULL, .param_index = 0 };
534 struct kunit_result_stats param_stats = { 0 };
535 test_case->status = KUNIT_SKIPPED;
537 if (!test_case->generate_params) {
538 /* Non-parameterised test. */
539 kunit_run_case_catch_errors(suite, test_case, &test);
540 kunit_update_stats(¶m_stats, test.status);
542 /* Get initial param. */
543 param_desc[0] = '\0';
544 test.param_value = test_case->generate_params(NULL, param_desc);
545 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
546 "# Subtest: %s", test_case->name);
548 while (test.param_value) {
549 kunit_run_case_catch_errors(suite, test_case, &test);
551 if (param_desc[0] == '\0') {
552 snprintf(param_desc, sizeof(param_desc),
553 "param-%d", test.param_index);
556 kunit_log(KERN_INFO, &test,
557 KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
559 kunit_status_to_ok_not_ok(test.status),
560 test.param_index + 1, param_desc);
562 /* Get next param. */
563 param_desc[0] = '\0';
564 test.param_value = test_case->generate_params(test.param_value, param_desc);
567 kunit_update_stats(¶m_stats, test.status);
572 kunit_print_test_stats(&test, param_stats);
574 kunit_print_ok_not_ok(&test, true, test_case->status,
575 kunit_test_case_num(suite, test_case),
577 test.status_comment);
579 kunit_update_stats(&suite_stats, test_case->status);
580 kunit_accumulate_stats(&total_stats, param_stats);
583 if (suite->suite_exit)
584 suite->suite_exit(suite);
586 kunit_print_suite_stats(suite, suite_stats, total_stats);
588 kunit_print_suite_end(suite);
592 EXPORT_SYMBOL_GPL(kunit_run_tests);
594 static void kunit_init_suite(struct kunit_suite *suite)
596 kunit_debugfs_create_suite(suite);
597 suite->status_comment[0] = '\0';
598 suite->suite_init_err = 0;
601 bool kunit_enabled(void)
606 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
610 if (!kunit_enabled() && num_suites > 0) {
611 pr_info("kunit: disabled\n");
615 for (i = 0; i < num_suites; i++) {
616 kunit_init_suite(suites[i]);
617 kunit_run_tests(suites[i]);
621 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
623 static void kunit_exit_suite(struct kunit_suite *suite)
625 kunit_debugfs_destroy_suite(suite);
628 void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites)
632 if (!kunit_enabled())
635 for (i = 0; i < num_suites; i++)
636 kunit_exit_suite(suites[i]);
638 kunit_suite_counter = 1;
640 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
642 #ifdef CONFIG_MODULES
643 static void kunit_module_init(struct module *mod)
645 __kunit_test_suites_init(mod->kunit_suites, mod->num_kunit_suites);
648 static void kunit_module_exit(struct module *mod)
650 __kunit_test_suites_exit(mod->kunit_suites, mod->num_kunit_suites);
653 static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
656 struct module *mod = data;
659 case MODULE_STATE_LIVE:
660 kunit_module_init(mod);
662 case MODULE_STATE_GOING:
663 kunit_module_exit(mod);
665 case MODULE_STATE_COMING:
666 case MODULE_STATE_UNFORMED:
673 static struct notifier_block kunit_mod_nb = {
674 .notifier_call = kunit_module_notify,
679 struct kunit_kmalloc_array_params {
685 static int kunit_kmalloc_array_init(struct kunit_resource *res, void *context)
687 struct kunit_kmalloc_array_params *params = context;
689 res->data = kmalloc_array(params->n, params->size, params->gfp);
696 static void kunit_kmalloc_array_free(struct kunit_resource *res)
701 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
703 struct kunit_kmalloc_array_params params = {
709 return kunit_alloc_resource(test,
710 kunit_kmalloc_array_init,
711 kunit_kmalloc_array_free,
715 EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
717 static inline bool kunit_kfree_match(struct kunit *test,
718 struct kunit_resource *res, void *match_data)
720 /* Only match resources allocated with kunit_kmalloc() and friends. */
721 return res->free == kunit_kmalloc_array_free && res->data == match_data;
724 void kunit_kfree(struct kunit *test, const void *ptr)
729 if (kunit_destroy_resource(test, kunit_kfree_match, (void *)ptr))
730 KUNIT_FAIL(test, "kunit_kfree: %px already freed or not allocated by kunit", ptr);
732 EXPORT_SYMBOL_GPL(kunit_kfree);
734 void kunit_cleanup(struct kunit *test)
736 struct kunit_resource *res;
740 * test->resources is a stack - each allocation must be freed in the
741 * reverse order from which it was added since one resource may depend
742 * on another for its entire lifetime.
743 * Also, we cannot use the normal list_for_each constructs, even the
744 * safe ones because *arbitrary* nodes may be deleted when
745 * kunit_resource_free is called; the list_for_each_safe variants only
746 * protect against the current node being deleted, not the next.
749 spin_lock_irqsave(&test->lock, flags);
750 if (list_empty(&test->resources)) {
751 spin_unlock_irqrestore(&test->lock, flags);
754 res = list_last_entry(&test->resources,
755 struct kunit_resource,
758 * Need to unlock here as a resource may remove another
759 * resource, and this can't happen if the test->lock
762 spin_unlock_irqrestore(&test->lock, flags);
763 kunit_remove_resource(test, res);
765 current->kunit_test = NULL;
767 EXPORT_SYMBOL_GPL(kunit_cleanup);
769 static int __init kunit_init(void)
771 kunit_debugfs_init();
772 #ifdef CONFIG_MODULES
773 return register_module_notifier(&kunit_mod_nb);
778 late_initcall(kunit_init);
780 static void __exit kunit_exit(void)
782 #ifdef CONFIG_MODULES
783 unregister_module_notifier(&kunit_mod_nb);
785 kunit_debugfs_cleanup();
787 module_exit(kunit_exit);
789 MODULE_LICENSE("GPL v2");