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/test.h>
10 #include <kunit/test-bug.h>
11 #include <linux/kernel.h>
12 #include <linux/kref.h>
13 #include <linux/sched/debug.h>
14 #include <linux/sched.h>
17 #include "string-stream.h"
18 #include "try-catch-impl.h"
20 #if IS_BUILTIN(CONFIG_KUNIT)
22 * Fail the current test and print an error message to the log.
24 void __kunit_fail_current_test(const char *file, int line, const char *fmt, ...)
30 if (!current->kunit_test)
33 kunit_set_failure(current->kunit_test);
35 /* kunit_err() only accepts literals, so evaluate the args first. */
37 len = vsnprintf(NULL, 0, fmt, args) + 1;
40 buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
45 vsnprintf(buffer, len, fmt, args);
48 kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
49 kunit_kfree(current->kunit_test, buffer);
51 EXPORT_SYMBOL_GPL(__kunit_fail_current_test);
55 * Append formatted message to log, size of which is limited to
56 * KUNIT_LOG_SIZE bytes (including null terminating byte).
58 void kunit_log_append(char *log, const char *fmt, ...)
60 char line[KUNIT_LOG_SIZE];
67 len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
72 vsnprintf(line, sizeof(line), fmt, args);
75 strncat(log, line, len_left);
77 EXPORT_SYMBOL_GPL(kunit_log_append);
79 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
81 struct kunit_case *test_case;
84 kunit_suite_for_each_test_case(suite, test_case)
89 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
91 static void kunit_print_subtest_start(struct kunit_suite *suite)
93 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
95 kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
96 kunit_suite_num_test_cases(suite));
99 static void kunit_print_ok_not_ok(void *test_or_suite,
101 enum kunit_status status,
103 const char *description,
104 const char *directive)
106 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
107 struct kunit *test = is_test ? test_or_suite : NULL;
108 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
111 * We do not log the test suite results as doing so would
112 * mean debugfs display would consist of the test suite
113 * description and status prior to individual test results.
114 * Hence directly printk the suite status, and we will
115 * separately seq_printf() the suite status for the debugfs
119 pr_info("%s %zd - %s%s%s\n",
120 kunit_status_to_ok_not_ok(status),
121 test_number, description, directive_header,
122 (status == KUNIT_SKIPPED) ? directive : "");
124 kunit_log(KERN_INFO, test,
125 KUNIT_SUBTEST_INDENT "%s %zd - %s%s%s",
126 kunit_status_to_ok_not_ok(status),
127 test_number, description, directive_header,
128 (status == KUNIT_SKIPPED) ? directive : "");
131 enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
133 const struct kunit_case *test_case;
134 enum kunit_status status = KUNIT_SKIPPED;
136 kunit_suite_for_each_test_case(suite, test_case) {
137 if (test_case->status == KUNIT_FAILURE)
138 return KUNIT_FAILURE;
139 else if (test_case->status == KUNIT_SUCCESS)
140 status = KUNIT_SUCCESS;
145 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
147 static void kunit_print_subtest_end(struct kunit_suite *suite)
149 static size_t kunit_suite_counter = 1;
151 kunit_print_ok_not_ok((void *)suite, false,
152 kunit_suite_has_succeeded(suite),
153 kunit_suite_counter++,
155 suite->status_comment);
158 unsigned int kunit_test_case_num(struct kunit_suite *suite,
159 struct kunit_case *test_case)
161 struct kunit_case *tc;
164 kunit_suite_for_each_test_case(suite, tc) {
172 EXPORT_SYMBOL_GPL(kunit_test_case_num);
174 static void kunit_print_string_stream(struct kunit *test,
175 struct string_stream *stream)
177 struct string_stream_fragment *fragment;
180 if (string_stream_is_empty(stream))
183 buf = string_stream_get_string(stream);
186 "Could not allocate buffer, dumping stream:\n");
187 list_for_each_entry(fragment, &stream->fragments, node) {
188 kunit_err(test, "%s", fragment->fragment);
190 kunit_err(test, "\n");
192 kunit_err(test, "%s", buf);
193 kunit_kfree(test, buf);
197 static void kunit_fail(struct kunit *test, struct kunit_assert *assert)
199 struct string_stream *stream;
201 kunit_set_failure(test);
203 stream = alloc_string_stream(test, GFP_KERNEL);
206 "Could not allocate stream to print failed assertion in %s:%d\n",
212 assert->format(assert, stream);
214 kunit_print_string_stream(test, stream);
216 WARN_ON(string_stream_destroy(stream));
219 static void __noreturn kunit_abort(struct kunit *test)
221 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
224 * Throw could not abort from test.
226 * XXX: we should never reach this line! As kunit_try_catch_throw is
229 WARN_ONCE(true, "Throw could not abort from test!\n");
232 void kunit_do_assertion(struct kunit *test,
233 struct kunit_assert *assert,
235 const char *fmt, ...)
244 assert->message.fmt = fmt;
245 assert->message.va = &args;
247 kunit_fail(test, assert);
251 if (assert->type == KUNIT_ASSERTION)
254 EXPORT_SYMBOL_GPL(kunit_do_assertion);
256 void kunit_init_test(struct kunit *test, const char *name, char *log)
258 spin_lock_init(&test->lock);
259 INIT_LIST_HEAD(&test->resources);
264 test->status = KUNIT_SUCCESS;
265 test->status_comment[0] = '\0';
267 EXPORT_SYMBOL_GPL(kunit_init_test);
270 * Initializes and runs test case. Does not clean up or do post validations.
272 static void kunit_run_case_internal(struct kunit *test,
273 struct kunit_suite *suite,
274 struct kunit_case *test_case)
279 ret = suite->init(test);
281 kunit_err(test, "failed to initialize: %d\n", ret);
282 kunit_set_failure(test);
287 test_case->run_case(test);
290 static void kunit_case_internal_cleanup(struct kunit *test)
296 * Performs post validations and cleanup after a test case was run.
297 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
299 static void kunit_run_case_cleanup(struct kunit *test,
300 struct kunit_suite *suite)
305 kunit_case_internal_cleanup(test);
308 struct kunit_try_catch_context {
310 struct kunit_suite *suite;
311 struct kunit_case *test_case;
314 static void kunit_try_run_case(void *data)
316 struct kunit_try_catch_context *ctx = data;
317 struct kunit *test = ctx->test;
318 struct kunit_suite *suite = ctx->suite;
319 struct kunit_case *test_case = ctx->test_case;
321 current->kunit_test = test;
324 * kunit_run_case_internal may encounter a fatal error; if it does,
325 * abort will be called, this thread will exit, and finally the parent
326 * thread will resume control and handle any necessary clean up.
328 kunit_run_case_internal(test, suite, test_case);
329 /* This line may never be reached. */
330 kunit_run_case_cleanup(test, suite);
333 static void kunit_catch_run_case(void *data)
335 struct kunit_try_catch_context *ctx = data;
336 struct kunit *test = ctx->test;
337 struct kunit_suite *suite = ctx->suite;
338 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
341 kunit_set_failure(test);
343 * Test case could not finish, we have no idea what state it is
344 * in, so don't do clean up.
346 if (try_exit_code == -ETIMEDOUT) {
347 kunit_err(test, "test case timed out\n");
349 * Unknown internal error occurred preventing test case from
350 * running, so there is nothing to clean up.
353 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
360 * Test case was run, but aborted. It is the test case's business as to
361 * whether it failed or not, we just need to clean up.
363 kunit_run_case_cleanup(test, suite);
367 * Performs all logic to run a test case. It also catches most errors that
368 * occur in a test case and reports them as failures.
370 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
371 struct kunit_case *test_case,
374 struct kunit_try_catch_context context;
375 struct kunit_try_catch *try_catch;
377 kunit_init_test(test, test_case->name, test_case->log);
378 try_catch = &test->try_catch;
380 kunit_try_catch_init(try_catch,
383 kunit_catch_run_case);
385 context.suite = suite;
386 context.test_case = test_case;
387 kunit_try_catch_run(try_catch, &context);
389 /* Propagate the parameter result to the test case. */
390 if (test->status == KUNIT_FAILURE)
391 test_case->status = KUNIT_FAILURE;
392 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
393 test_case->status = KUNIT_SUCCESS;
396 int kunit_run_tests(struct kunit_suite *suite)
398 char param_desc[KUNIT_PARAM_DESC_SIZE];
399 struct kunit_case *test_case;
401 kunit_print_subtest_start(suite);
403 kunit_suite_for_each_test_case(suite, test_case) {
404 struct kunit test = { .param_value = NULL, .param_index = 0 };
405 test_case->status = KUNIT_SKIPPED;
407 if (test_case->generate_params) {
408 /* Get initial param. */
409 param_desc[0] = '\0';
410 test.param_value = test_case->generate_params(NULL, param_desc);
414 kunit_run_case_catch_errors(suite, test_case, &test);
416 if (test_case->generate_params) {
417 if (param_desc[0] == '\0') {
418 snprintf(param_desc, sizeof(param_desc),
419 "param-%d", test.param_index);
422 kunit_log(KERN_INFO, &test,
426 kunit_status_to_ok_not_ok(test.status),
427 test.param_index + 1, param_desc);
429 /* Get next param. */
430 param_desc[0] = '\0';
431 test.param_value = test_case->generate_params(test.param_value, param_desc);
434 } while (test.param_value);
436 kunit_print_ok_not_ok(&test, true, test_case->status,
437 kunit_test_case_num(suite, test_case),
439 test.status_comment);
442 kunit_print_subtest_end(suite);
446 EXPORT_SYMBOL_GPL(kunit_run_tests);
448 static void kunit_init_suite(struct kunit_suite *suite)
450 kunit_debugfs_create_suite(suite);
451 suite->status_comment[0] = '\0';
454 int __kunit_test_suites_init(struct kunit_suite * const * const suites)
458 for (i = 0; suites[i] != NULL; i++) {
459 kunit_init_suite(suites[i]);
460 kunit_run_tests(suites[i]);
464 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
466 static void kunit_exit_suite(struct kunit_suite *suite)
468 kunit_debugfs_destroy_suite(suite);
471 void __kunit_test_suites_exit(struct kunit_suite **suites)
475 for (i = 0; suites[i] != NULL; i++)
476 kunit_exit_suite(suites[i]);
478 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
481 * Used for static resources and when a kunit_resource * has been created by
482 * kunit_alloc_resource(). When an init function is supplied, @data is passed
483 * into the init function; otherwise, we simply set the resource data field to
484 * the data value passed in.
486 int kunit_add_resource(struct kunit *test,
487 kunit_resource_init_t init,
488 kunit_resource_free_t free,
489 struct kunit_resource *res,
496 kref_init(&res->refcount);
499 ret = init(res, data);
506 spin_lock_irqsave(&test->lock, flags);
507 list_add_tail(&res->node, &test->resources);
508 /* refcount for list is established by kref_init() */
509 spin_unlock_irqrestore(&test->lock, flags);
513 EXPORT_SYMBOL_GPL(kunit_add_resource);
515 int kunit_add_named_resource(struct kunit *test,
516 kunit_resource_init_t init,
517 kunit_resource_free_t free,
518 struct kunit_resource *res,
522 struct kunit_resource *existing;
527 existing = kunit_find_named_resource(test, name);
529 kunit_put_resource(existing);
535 return kunit_add_resource(test, init, free, res, data);
537 EXPORT_SYMBOL_GPL(kunit_add_named_resource);
539 struct kunit_resource *kunit_alloc_and_get_resource(struct kunit *test,
540 kunit_resource_init_t init,
541 kunit_resource_free_t free,
545 struct kunit_resource *res;
548 res = kzalloc(sizeof(*res), internal_gfp);
552 ret = kunit_add_resource(test, init, free, res, data);
555 * bump refcount for get; kunit_resource_put() should be called
558 kunit_get_resource(res);
563 EXPORT_SYMBOL_GPL(kunit_alloc_and_get_resource);
565 void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
569 spin_lock_irqsave(&test->lock, flags);
570 list_del(&res->node);
571 spin_unlock_irqrestore(&test->lock, flags);
572 kunit_put_resource(res);
574 EXPORT_SYMBOL_GPL(kunit_remove_resource);
576 int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
579 struct kunit_resource *res = kunit_find_resource(test, match,
585 kunit_remove_resource(test, res);
587 /* We have a reference also via _find(); drop it. */
588 kunit_put_resource(res);
592 EXPORT_SYMBOL_GPL(kunit_destroy_resource);
594 struct kunit_kmalloc_array_params {
600 static int kunit_kmalloc_array_init(struct kunit_resource *res, void *context)
602 struct kunit_kmalloc_array_params *params = context;
604 res->data = kmalloc_array(params->n, params->size, params->gfp);
611 static void kunit_kmalloc_array_free(struct kunit_resource *res)
616 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
618 struct kunit_kmalloc_array_params params = {
624 return kunit_alloc_resource(test,
625 kunit_kmalloc_array_init,
626 kunit_kmalloc_array_free,
630 EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
632 void kunit_kfree(struct kunit *test, const void *ptr)
634 struct kunit_resource *res;
636 res = kunit_find_resource(test, kunit_resource_instance_match,
640 * Removing the resource from the list of resources drops the
641 * reference count to 1; the final put will trigger the free.
643 kunit_remove_resource(test, res);
645 kunit_put_resource(res);
648 EXPORT_SYMBOL_GPL(kunit_kfree);
650 void kunit_cleanup(struct kunit *test)
652 struct kunit_resource *res;
656 * test->resources is a stack - each allocation must be freed in the
657 * reverse order from which it was added since one resource may depend
658 * on another for its entire lifetime.
659 * Also, we cannot use the normal list_for_each constructs, even the
660 * safe ones because *arbitrary* nodes may be deleted when
661 * kunit_resource_free is called; the list_for_each_safe variants only
662 * protect against the current node being deleted, not the next.
665 spin_lock_irqsave(&test->lock, flags);
666 if (list_empty(&test->resources)) {
667 spin_unlock_irqrestore(&test->lock, flags);
670 res = list_last_entry(&test->resources,
671 struct kunit_resource,
674 * Need to unlock here as a resource may remove another
675 * resource, and this can't happen if the test->lock
678 spin_unlock_irqrestore(&test->lock, flags);
679 kunit_remove_resource(test, res);
681 current->kunit_test = NULL;
683 EXPORT_SYMBOL_GPL(kunit_cleanup);
685 static int __init kunit_init(void)
687 kunit_debugfs_init();
691 late_initcall(kunit_init);
693 static void __exit kunit_exit(void)
695 kunit_debugfs_cleanup();
697 module_exit(kunit_exit);
699 MODULE_LICENSE("GPL v2");