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,
103 const char *description)
105 struct kunit_suite *suite = is_test ? NULL : test_or_suite;
106 struct kunit *test = is_test ? test_or_suite : NULL;
109 * We do not log the test suite results as doing so would
110 * mean debugfs display would consist of the test suite
111 * description and status prior to individual test results.
112 * Hence directly printk the suite status, and we will
113 * separately seq_printf() the suite status for the debugfs
117 pr_info("%s %zd - %s\n",
118 kunit_status_to_string(is_ok),
119 test_number, description);
121 kunit_log(KERN_INFO, test, KUNIT_SUBTEST_INDENT "%s %zd - %s",
122 kunit_status_to_string(is_ok),
123 test_number, description);
126 bool kunit_suite_has_succeeded(struct kunit_suite *suite)
128 const struct kunit_case *test_case;
130 kunit_suite_for_each_test_case(suite, test_case) {
131 if (!test_case->success)
137 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
139 static void kunit_print_subtest_end(struct kunit_suite *suite)
141 static size_t kunit_suite_counter = 1;
143 kunit_print_ok_not_ok((void *)suite, false,
144 kunit_suite_has_succeeded(suite),
145 kunit_suite_counter++,
149 unsigned int kunit_test_case_num(struct kunit_suite *suite,
150 struct kunit_case *test_case)
152 struct kunit_case *tc;
155 kunit_suite_for_each_test_case(suite, tc) {
163 EXPORT_SYMBOL_GPL(kunit_test_case_num);
165 static void kunit_print_string_stream(struct kunit *test,
166 struct string_stream *stream)
168 struct string_stream_fragment *fragment;
171 if (string_stream_is_empty(stream))
174 buf = string_stream_get_string(stream);
177 "Could not allocate buffer, dumping stream:\n");
178 list_for_each_entry(fragment, &stream->fragments, node) {
179 kunit_err(test, "%s", fragment->fragment);
181 kunit_err(test, "\n");
183 kunit_err(test, "%s", buf);
184 kunit_kfree(test, buf);
188 static void kunit_fail(struct kunit *test, struct kunit_assert *assert)
190 struct string_stream *stream;
192 kunit_set_failure(test);
194 stream = alloc_string_stream(test, GFP_KERNEL);
197 "Could not allocate stream to print failed assertion in %s:%d\n",
203 assert->format(assert, stream);
205 kunit_print_string_stream(test, stream);
207 WARN_ON(string_stream_destroy(stream));
210 static void __noreturn kunit_abort(struct kunit *test)
212 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
215 * Throw could not abort from test.
217 * XXX: we should never reach this line! As kunit_try_catch_throw is
220 WARN_ONCE(true, "Throw could not abort from test!\n");
223 void kunit_do_assertion(struct kunit *test,
224 struct kunit_assert *assert,
226 const char *fmt, ...)
235 assert->message.fmt = fmt;
236 assert->message.va = &args;
238 kunit_fail(test, assert);
242 if (assert->type == KUNIT_ASSERTION)
245 EXPORT_SYMBOL_GPL(kunit_do_assertion);
247 void kunit_init_test(struct kunit *test, const char *name, char *log)
249 spin_lock_init(&test->lock);
250 INIT_LIST_HEAD(&test->resources);
255 test->success = true;
257 EXPORT_SYMBOL_GPL(kunit_init_test);
260 * Initializes and runs test case. Does not clean up or do post validations.
262 static void kunit_run_case_internal(struct kunit *test,
263 struct kunit_suite *suite,
264 struct kunit_case *test_case)
269 ret = suite->init(test);
271 kunit_err(test, "failed to initialize: %d\n", ret);
272 kunit_set_failure(test);
277 test_case->run_case(test);
280 static void kunit_case_internal_cleanup(struct kunit *test)
286 * Performs post validations and cleanup after a test case was run.
287 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
289 static void kunit_run_case_cleanup(struct kunit *test,
290 struct kunit_suite *suite)
295 kunit_case_internal_cleanup(test);
298 struct kunit_try_catch_context {
300 struct kunit_suite *suite;
301 struct kunit_case *test_case;
304 static void kunit_try_run_case(void *data)
306 struct kunit_try_catch_context *ctx = data;
307 struct kunit *test = ctx->test;
308 struct kunit_suite *suite = ctx->suite;
309 struct kunit_case *test_case = ctx->test_case;
311 current->kunit_test = test;
314 * kunit_run_case_internal may encounter a fatal error; if it does,
315 * abort will be called, this thread will exit, and finally the parent
316 * thread will resume control and handle any necessary clean up.
318 kunit_run_case_internal(test, suite, test_case);
319 /* This line may never be reached. */
320 kunit_run_case_cleanup(test, suite);
323 static void kunit_catch_run_case(void *data)
325 struct kunit_try_catch_context *ctx = data;
326 struct kunit *test = ctx->test;
327 struct kunit_suite *suite = ctx->suite;
328 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
331 kunit_set_failure(test);
333 * Test case could not finish, we have no idea what state it is
334 * in, so don't do clean up.
336 if (try_exit_code == -ETIMEDOUT) {
337 kunit_err(test, "test case timed out\n");
339 * Unknown internal error occurred preventing test case from
340 * running, so there is nothing to clean up.
343 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
350 * Test case was run, but aborted. It is the test case's business as to
351 * whether it failed or not, we just need to clean up.
353 kunit_run_case_cleanup(test, suite);
357 * Performs all logic to run a test case. It also catches most errors that
358 * occur in a test case and reports them as failures.
360 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
361 struct kunit_case *test_case,
364 struct kunit_try_catch_context context;
365 struct kunit_try_catch *try_catch;
367 kunit_init_test(test, test_case->name, test_case->log);
368 try_catch = &test->try_catch;
370 kunit_try_catch_init(try_catch,
373 kunit_catch_run_case);
375 context.suite = suite;
376 context.test_case = test_case;
377 kunit_try_catch_run(try_catch, &context);
379 test_case->success = test->success;
382 int kunit_run_tests(struct kunit_suite *suite)
384 char param_desc[KUNIT_PARAM_DESC_SIZE];
385 struct kunit_case *test_case;
387 kunit_print_subtest_start(suite);
389 kunit_suite_for_each_test_case(suite, test_case) {
390 struct kunit test = { .param_value = NULL, .param_index = 0 };
391 bool test_success = true;
393 if (test_case->generate_params) {
394 /* Get initial param. */
395 param_desc[0] = '\0';
396 test.param_value = test_case->generate_params(NULL, param_desc);
400 kunit_run_case_catch_errors(suite, test_case, &test);
401 test_success &= test_case->success;
403 if (test_case->generate_params) {
404 if (param_desc[0] == '\0') {
405 snprintf(param_desc, sizeof(param_desc),
406 "param-%d", test.param_index);
409 kunit_log(KERN_INFO, &test,
413 kunit_status_to_string(test.success),
414 test.param_index + 1, param_desc);
416 /* Get next param. */
417 param_desc[0] = '\0';
418 test.param_value = test_case->generate_params(test.param_value, param_desc);
421 } while (test.param_value);
423 kunit_print_ok_not_ok(&test, true, test_success,
424 kunit_test_case_num(suite, test_case),
428 kunit_print_subtest_end(suite);
432 EXPORT_SYMBOL_GPL(kunit_run_tests);
434 static void kunit_init_suite(struct kunit_suite *suite)
436 kunit_debugfs_create_suite(suite);
439 int __kunit_test_suites_init(struct kunit_suite * const * const suites)
443 for (i = 0; suites[i] != NULL; i++) {
444 kunit_init_suite(suites[i]);
445 kunit_run_tests(suites[i]);
449 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
451 static void kunit_exit_suite(struct kunit_suite *suite)
453 kunit_debugfs_destroy_suite(suite);
456 void __kunit_test_suites_exit(struct kunit_suite **suites)
460 for (i = 0; suites[i] != NULL; i++)
461 kunit_exit_suite(suites[i]);
463 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
466 * Used for static resources and when a kunit_resource * has been created by
467 * kunit_alloc_resource(). When an init function is supplied, @data is passed
468 * into the init function; otherwise, we simply set the resource data field to
469 * the data value passed in.
471 int kunit_add_resource(struct kunit *test,
472 kunit_resource_init_t init,
473 kunit_resource_free_t free,
474 struct kunit_resource *res,
480 kref_init(&res->refcount);
483 ret = init(res, data);
490 spin_lock(&test->lock);
491 list_add_tail(&res->node, &test->resources);
492 /* refcount for list is established by kref_init() */
493 spin_unlock(&test->lock);
497 EXPORT_SYMBOL_GPL(kunit_add_resource);
499 int kunit_add_named_resource(struct kunit *test,
500 kunit_resource_init_t init,
501 kunit_resource_free_t free,
502 struct kunit_resource *res,
506 struct kunit_resource *existing;
511 existing = kunit_find_named_resource(test, name);
513 kunit_put_resource(existing);
519 return kunit_add_resource(test, init, free, res, data);
521 EXPORT_SYMBOL_GPL(kunit_add_named_resource);
523 struct kunit_resource *kunit_alloc_and_get_resource(struct kunit *test,
524 kunit_resource_init_t init,
525 kunit_resource_free_t free,
529 struct kunit_resource *res;
532 res = kzalloc(sizeof(*res), internal_gfp);
536 ret = kunit_add_resource(test, init, free, res, data);
539 * bump refcount for get; kunit_resource_put() should be called
542 kunit_get_resource(res);
547 EXPORT_SYMBOL_GPL(kunit_alloc_and_get_resource);
549 void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
551 spin_lock(&test->lock);
552 list_del(&res->node);
553 spin_unlock(&test->lock);
554 kunit_put_resource(res);
556 EXPORT_SYMBOL_GPL(kunit_remove_resource);
558 int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
561 struct kunit_resource *res = kunit_find_resource(test, match,
567 kunit_remove_resource(test, res);
569 /* We have a reference also via _find(); drop it. */
570 kunit_put_resource(res);
574 EXPORT_SYMBOL_GPL(kunit_destroy_resource);
576 struct kunit_kmalloc_params {
581 static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
583 struct kunit_kmalloc_params *params = context;
585 res->data = kmalloc(params->size, params->gfp);
592 static void kunit_kmalloc_free(struct kunit_resource *res)
597 void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
599 struct kunit_kmalloc_params params = {
604 return kunit_alloc_resource(test,
610 EXPORT_SYMBOL_GPL(kunit_kmalloc);
612 void kunit_kfree(struct kunit *test, const void *ptr)
614 struct kunit_resource *res;
616 res = kunit_find_resource(test, kunit_resource_instance_match,
620 * Removing the resource from the list of resources drops the
621 * reference count to 1; the final put will trigger the free.
623 kunit_remove_resource(test, res);
625 kunit_put_resource(res);
628 EXPORT_SYMBOL_GPL(kunit_kfree);
630 void kunit_cleanup(struct kunit *test)
632 struct kunit_resource *res;
635 * test->resources is a stack - each allocation must be freed in the
636 * reverse order from which it was added since one resource may depend
637 * on another for its entire lifetime.
638 * Also, we cannot use the normal list_for_each constructs, even the
639 * safe ones because *arbitrary* nodes may be deleted when
640 * kunit_resource_free is called; the list_for_each_safe variants only
641 * protect against the current node being deleted, not the next.
644 spin_lock(&test->lock);
645 if (list_empty(&test->resources)) {
646 spin_unlock(&test->lock);
649 res = list_last_entry(&test->resources,
650 struct kunit_resource,
653 * Need to unlock here as a resource may remove another
654 * resource, and this can't happen if the test->lock
657 spin_unlock(&test->lock);
658 kunit_remove_resource(test, res);
660 current->kunit_test = NULL;
662 EXPORT_SYMBOL_GPL(kunit_cleanup);
664 static int __init kunit_init(void)
666 kunit_debugfs_init();
670 late_initcall(kunit_init);
672 static void __exit kunit_exit(void)
674 kunit_debugfs_cleanup();
676 module_exit(kunit_exit);
678 MODULE_LICENSE("GPL v2");