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 DEFINE_STATIC_KEY_FALSE(kunit_running);
24 EXPORT_SYMBOL_GPL(kunit_running);
26 #if IS_BUILTIN(CONFIG_KUNIT)
28 * Fail the current test and print an error message to the log.
30 void __kunit_fail_current_test(const char *file, int line, const char *fmt, ...)
36 if (!current->kunit_test)
39 kunit_set_failure(current->kunit_test);
41 /* kunit_err() only accepts literals, so evaluate the args first. */
43 len = vsnprintf(NULL, 0, fmt, args) + 1;
46 buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
51 vsnprintf(buffer, len, fmt, args);
54 kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
55 kunit_kfree(current->kunit_test, buffer);
57 EXPORT_SYMBOL_GPL(__kunit_fail_current_test);
61 * Enable KUnit tests to run.
63 #ifdef CONFIG_KUNIT_DEFAULT_ENABLED
64 static bool enable_param = true;
66 static bool enable_param;
68 module_param_named(enable, enable_param, bool, 0);
69 MODULE_PARM_DESC(enable, "Enable KUnit tests");
72 * KUnit statistic mode:
74 * 1 - only when there is more than one subtest
77 static int kunit_stats_enabled = 1;
78 module_param_named(stats_enabled, kunit_stats_enabled, int, 0644);
79 MODULE_PARM_DESC(stats_enabled,
80 "Print test stats: never (0), only for multiple subtests (1), or always (2)");
82 struct kunit_result_stats {
84 unsigned long skipped;
89 static bool kunit_should_print_stats(struct kunit_result_stats stats)
91 if (kunit_stats_enabled == 0)
94 if (kunit_stats_enabled == 2)
97 return (stats.total > 1);
100 static void kunit_print_test_stats(struct kunit *test,
101 struct kunit_result_stats stats)
103 if (!kunit_should_print_stats(stats))
106 kunit_log(KERN_INFO, test,
108 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
117 * Append formatted message to log, size of which is limited to
118 * KUNIT_LOG_SIZE bytes (including null terminating byte).
120 void kunit_log_append(char *log, const char *fmt, ...)
122 char line[KUNIT_LOG_SIZE];
129 len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
134 vsnprintf(line, sizeof(line), fmt, args);
137 strncat(log, line, len_left);
139 EXPORT_SYMBOL_GPL(kunit_log_append);
141 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
143 struct kunit_case *test_case;
146 kunit_suite_for_each_test_case(suite, test_case)
151 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
153 static void kunit_print_suite_start(struct kunit_suite *suite)
155 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "KTAP version 1\n");
156 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
158 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
159 kunit_suite_num_test_cases(suite));
162 static void kunit_print_ok_not_ok(void *test_or_suite,
164 enum kunit_status status,
166 const char *description,
167 const char *directive)
169 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
170 struct kunit *test = is_test ? test_or_suite : NULL;
171 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
174 * We do not log the test suite results as doing so would
175 * mean debugfs display would consist of the test suite
176 * description and status prior to individual test results.
177 * Hence directly printk the suite status, and we will
178 * separately seq_printf() the suite status for the debugfs
182 pr_info("%s %zd %s%s%s\n",
183 kunit_status_to_ok_not_ok(status),
184 test_number, description, directive_header,
185 (status == KUNIT_SKIPPED) ? directive : "");
187 kunit_log(KERN_INFO, test,
188 KUNIT_SUBTEST_INDENT "%s %zd %s%s%s",
189 kunit_status_to_ok_not_ok(status),
190 test_number, description, directive_header,
191 (status == KUNIT_SKIPPED) ? directive : "");
194 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
196 const struct kunit_case *test_case;
197 enum kunit_status status = KUNIT_SKIPPED;
199 if (suite->suite_init_err)
200 return KUNIT_FAILURE;
202 kunit_suite_for_each_test_case(suite, test_case) {
203 if (test_case->status == KUNIT_FAILURE)
204 return KUNIT_FAILURE;
205 else if (test_case->status == KUNIT_SUCCESS)
206 status = KUNIT_SUCCESS;
211 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
213 static size_t kunit_suite_counter = 1;
215 static void kunit_print_suite_end(struct kunit_suite *suite)
217 kunit_print_ok_not_ok((void *)suite, false,
218 kunit_suite_has_succeeded(suite),
219 kunit_suite_counter++,
221 suite->status_comment);
224 unsigned int kunit_test_case_num(struct kunit_suite *suite,
225 struct kunit_case *test_case)
227 struct kunit_case *tc;
230 kunit_suite_for_each_test_case(suite, tc) {
238 EXPORT_SYMBOL_GPL(kunit_test_case_num);
240 static void kunit_print_string_stream(struct kunit *test,
241 struct string_stream *stream)
243 struct string_stream_fragment *fragment;
246 if (string_stream_is_empty(stream))
249 buf = string_stream_get_string(stream);
252 "Could not allocate buffer, dumping stream:\n");
253 list_for_each_entry(fragment, &stream->fragments, node) {
254 kunit_err(test, "%s", fragment->fragment);
256 kunit_err(test, "\n");
258 kunit_err(test, "%s", buf);
259 kunit_kfree(test, buf);
263 static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
264 enum kunit_assert_type type, const struct kunit_assert *assert,
265 assert_format_t assert_format, const struct va_format *message)
267 struct string_stream *stream;
269 kunit_set_failure(test);
271 stream = alloc_string_stream(test, GFP_KERNEL);
272 if (IS_ERR(stream)) {
274 "Could not allocate stream to print failed assertion in %s:%d\n",
280 kunit_assert_prologue(loc, type, stream);
281 assert_format(assert, message, stream);
283 kunit_print_string_stream(test, stream);
285 string_stream_destroy(stream);
288 static void __noreturn kunit_abort(struct kunit *test)
290 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
293 * Throw could not abort from test.
295 * XXX: we should never reach this line! As kunit_try_catch_throw is
298 WARN_ONCE(true, "Throw could not abort from test!\n");
301 void kunit_do_failed_assertion(struct kunit *test,
302 const struct kunit_loc *loc,
303 enum kunit_assert_type type,
304 const struct kunit_assert *assert,
305 assert_format_t assert_format,
306 const char *fmt, ...)
309 struct va_format message;
315 kunit_fail(test, loc, type, assert, assert_format, &message);
319 if (type == KUNIT_ASSERTION)
322 EXPORT_SYMBOL_GPL(kunit_do_failed_assertion);
324 void kunit_init_test(struct kunit *test, const char *name, char *log)
326 spin_lock_init(&test->lock);
327 INIT_LIST_HEAD(&test->resources);
332 test->status = KUNIT_SUCCESS;
333 test->status_comment[0] = '\0';
335 EXPORT_SYMBOL_GPL(kunit_init_test);
338 * Initializes and runs test case. Does not clean up or do post validations.
340 static void kunit_run_case_internal(struct kunit *test,
341 struct kunit_suite *suite,
342 struct kunit_case *test_case)
347 ret = suite->init(test);
349 kunit_err(test, "failed to initialize: %d\n", ret);
350 kunit_set_failure(test);
355 test_case->run_case(test);
358 static void kunit_case_internal_cleanup(struct kunit *test)
364 * Performs post validations and cleanup after a test case was run.
365 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
367 static void kunit_run_case_cleanup(struct kunit *test,
368 struct kunit_suite *suite)
373 kunit_case_internal_cleanup(test);
376 struct kunit_try_catch_context {
378 struct kunit_suite *suite;
379 struct kunit_case *test_case;
382 static void kunit_try_run_case(void *data)
384 struct kunit_try_catch_context *ctx = data;
385 struct kunit *test = ctx->test;
386 struct kunit_suite *suite = ctx->suite;
387 struct kunit_case *test_case = ctx->test_case;
389 current->kunit_test = test;
392 * kunit_run_case_internal may encounter a fatal error; if it does,
393 * abort will be called, this thread will exit, and finally the parent
394 * thread will resume control and handle any necessary clean up.
396 kunit_run_case_internal(test, suite, test_case);
397 /* This line may never be reached. */
398 kunit_run_case_cleanup(test, suite);
401 static void kunit_catch_run_case(void *data)
403 struct kunit_try_catch_context *ctx = data;
404 struct kunit *test = ctx->test;
405 struct kunit_suite *suite = ctx->suite;
406 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
409 kunit_set_failure(test);
411 * Test case could not finish, we have no idea what state it is
412 * in, so don't do clean up.
414 if (try_exit_code == -ETIMEDOUT) {
415 kunit_err(test, "test case timed out\n");
417 * Unknown internal error occurred preventing test case from
418 * running, so there is nothing to clean up.
421 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
428 * Test case was run, but aborted. It is the test case's business as to
429 * whether it failed or not, we just need to clean up.
431 kunit_run_case_cleanup(test, suite);
435 * Performs all logic to run a test case. It also catches most errors that
436 * occur in a test case and reports them as failures.
438 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
439 struct kunit_case *test_case,
442 struct kunit_try_catch_context context;
443 struct kunit_try_catch *try_catch;
445 kunit_init_test(test, test_case->name, test_case->log);
446 try_catch = &test->try_catch;
448 kunit_try_catch_init(try_catch,
451 kunit_catch_run_case);
453 context.suite = suite;
454 context.test_case = test_case;
455 kunit_try_catch_run(try_catch, &context);
457 /* Propagate the parameter result to the test case. */
458 if (test->status == KUNIT_FAILURE)
459 test_case->status = KUNIT_FAILURE;
460 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
461 test_case->status = KUNIT_SUCCESS;
464 static void kunit_print_suite_stats(struct kunit_suite *suite,
465 struct kunit_result_stats suite_stats,
466 struct kunit_result_stats param_stats)
468 if (kunit_should_print_stats(suite_stats)) {
469 kunit_log(KERN_INFO, suite,
470 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
478 if (kunit_should_print_stats(param_stats)) {
479 kunit_log(KERN_INFO, suite,
480 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
488 static void kunit_update_stats(struct kunit_result_stats *stats,
489 enum kunit_status status)
506 static void kunit_accumulate_stats(struct kunit_result_stats *total,
507 struct kunit_result_stats add)
509 total->passed += add.passed;
510 total->skipped += add.skipped;
511 total->failed += add.failed;
512 total->total += add.total;
515 int kunit_run_tests(struct kunit_suite *suite)
517 char param_desc[KUNIT_PARAM_DESC_SIZE];
518 struct kunit_case *test_case;
519 struct kunit_result_stats suite_stats = { 0 };
520 struct kunit_result_stats total_stats = { 0 };
522 /* Taint the kernel so we know we've run tests. */
523 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
525 if (suite->suite_init) {
526 suite->suite_init_err = suite->suite_init(suite);
527 if (suite->suite_init_err) {
528 kunit_err(suite, KUNIT_SUBTEST_INDENT
529 "# failed to initialize (%d)", suite->suite_init_err);
534 kunit_print_suite_start(suite);
536 kunit_suite_for_each_test_case(suite, test_case) {
537 struct kunit test = { .param_value = NULL, .param_index = 0 };
538 struct kunit_result_stats param_stats = { 0 };
539 test_case->status = KUNIT_SKIPPED;
541 if (!test_case->generate_params) {
542 /* Non-parameterised test. */
543 kunit_run_case_catch_errors(suite, test_case, &test);
544 kunit_update_stats(¶m_stats, test.status);
546 /* Get initial param. */
547 param_desc[0] = '\0';
548 test.param_value = test_case->generate_params(NULL, param_desc);
549 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
551 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
552 "# Subtest: %s", test_case->name);
554 while (test.param_value) {
555 kunit_run_case_catch_errors(suite, test_case, &test);
557 if (param_desc[0] == '\0') {
558 snprintf(param_desc, sizeof(param_desc),
559 "param-%d", test.param_index);
562 kunit_log(KERN_INFO, &test,
563 KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
565 kunit_status_to_ok_not_ok(test.status),
566 test.param_index + 1, param_desc);
568 /* Get next param. */
569 param_desc[0] = '\0';
570 test.param_value = test_case->generate_params(test.param_value, param_desc);
573 kunit_update_stats(¶m_stats, test.status);
578 kunit_print_test_stats(&test, param_stats);
580 kunit_print_ok_not_ok(&test, true, test_case->status,
581 kunit_test_case_num(suite, test_case),
583 test.status_comment);
585 kunit_update_stats(&suite_stats, test_case->status);
586 kunit_accumulate_stats(&total_stats, param_stats);
589 if (suite->suite_exit)
590 suite->suite_exit(suite);
592 kunit_print_suite_stats(suite, suite_stats, total_stats);
594 kunit_print_suite_end(suite);
598 EXPORT_SYMBOL_GPL(kunit_run_tests);
600 static void kunit_init_suite(struct kunit_suite *suite)
602 kunit_debugfs_create_suite(suite);
603 suite->status_comment[0] = '\0';
604 suite->suite_init_err = 0;
607 bool kunit_enabled(void)
612 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
616 if (!kunit_enabled() && num_suites > 0) {
617 pr_info("kunit: disabled\n");
621 static_branch_inc(&kunit_running);
623 for (i = 0; i < num_suites; i++) {
624 kunit_init_suite(suites[i]);
625 kunit_run_tests(suites[i]);
628 static_branch_dec(&kunit_running);
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");