xref: /linux/lib/kunit/test.c (revision 6ebf5866f2e870cf9451a2068c787bc2b30025e9)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Base unit test (KUnit) API.
4  *
5  * Copyright (C) 2019, Google LLC.
6  * Author: Brendan Higgins <brendanhiggins@google.com>
7  */
8 
9 #include <kunit/test.h>
10 #include <kunit/try-catch.h>
11 #include <linux/kernel.h>
12 #include <linux/sched/debug.h>
13 
14 static void kunit_set_failure(struct kunit *test)
15 {
16 	WRITE_ONCE(test->success, false);
17 }
18 
19 static int kunit_vprintk_emit(int level, const char *fmt, va_list args)
20 {
21 	return vprintk_emit(0, level, NULL, 0, fmt, args);
22 }
23 
24 static int kunit_printk_emit(int level, const char *fmt, ...)
25 {
26 	va_list args;
27 	int ret;
28 
29 	va_start(args, fmt);
30 	ret = kunit_vprintk_emit(level, fmt, args);
31 	va_end(args);
32 
33 	return ret;
34 }
35 
36 static void kunit_vprintk(const struct kunit *test,
37 			  const char *level,
38 			  struct va_format *vaf)
39 {
40 	kunit_printk_emit(level[1] - '0', "\t# %s: %pV", test->name, vaf);
41 }
42 
43 static void kunit_print_tap_version(void)
44 {
45 	static bool kunit_has_printed_tap_version;
46 
47 	if (!kunit_has_printed_tap_version) {
48 		kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");
49 		kunit_has_printed_tap_version = true;
50 	}
51 }
52 
53 static size_t kunit_test_cases_len(struct kunit_case *test_cases)
54 {
55 	struct kunit_case *test_case;
56 	size_t len = 0;
57 
58 	for (test_case = test_cases; test_case->run_case; test_case++)
59 		len++;
60 
61 	return len;
62 }
63 
64 static void kunit_print_subtest_start(struct kunit_suite *suite)
65 {
66 	kunit_print_tap_version();
67 	kunit_printk_emit(LOGLEVEL_INFO, "\t# Subtest: %s\n", suite->name);
68 	kunit_printk_emit(LOGLEVEL_INFO,
69 			  "\t1..%zd\n",
70 			  kunit_test_cases_len(suite->test_cases));
71 }
72 
73 static void kunit_print_ok_not_ok(bool should_indent,
74 				  bool is_ok,
75 				  size_t test_number,
76 				  const char *description)
77 {
78 	const char *indent, *ok_not_ok;
79 
80 	if (should_indent)
81 		indent = "\t";
82 	else
83 		indent = "";
84 
85 	if (is_ok)
86 		ok_not_ok = "ok";
87 	else
88 		ok_not_ok = "not ok";
89 
90 	kunit_printk_emit(LOGLEVEL_INFO,
91 			  "%s%s %zd - %s\n",
92 			  indent, ok_not_ok, test_number, description);
93 }
94 
95 static bool kunit_suite_has_succeeded(struct kunit_suite *suite)
96 {
97 	const struct kunit_case *test_case;
98 
99 	for (test_case = suite->test_cases; test_case->run_case; test_case++)
100 		if (!test_case->success)
101 			return false;
102 
103 	return true;
104 }
105 
106 static void kunit_print_subtest_end(struct kunit_suite *suite)
107 {
108 	static size_t kunit_suite_counter = 1;
109 
110 	kunit_print_ok_not_ok(false,
111 			      kunit_suite_has_succeeded(suite),
112 			      kunit_suite_counter++,
113 			      suite->name);
114 }
115 
116 static void kunit_print_test_case_ok_not_ok(struct kunit_case *test_case,
117 					    size_t test_number)
118 {
119 	kunit_print_ok_not_ok(true,
120 			      test_case->success,
121 			      test_number,
122 			      test_case->name);
123 }
124 
125 static void kunit_print_string_stream(struct kunit *test,
126 				      struct string_stream *stream)
127 {
128 	struct string_stream_fragment *fragment;
129 	char *buf;
130 
131 	buf = string_stream_get_string(stream);
132 	if (!buf) {
133 		kunit_err(test,
134 			  "Could not allocate buffer, dumping stream:\n");
135 		list_for_each_entry(fragment, &stream->fragments, node) {
136 			kunit_err(test, fragment->fragment);
137 		}
138 		kunit_err(test, "\n");
139 	} else {
140 		kunit_err(test, buf);
141 		kunit_kfree(test, buf);
142 	}
143 }
144 
145 static void kunit_fail(struct kunit *test, struct kunit_assert *assert)
146 {
147 	struct string_stream *stream;
148 
149 	kunit_set_failure(test);
150 
151 	stream = alloc_string_stream(test, GFP_KERNEL);
152 	if (!stream) {
153 		WARN(true,
154 		     "Could not allocate stream to print failed assertion in %s:%d\n",
155 		     assert->file,
156 		     assert->line);
157 		return;
158 	}
159 
160 	assert->format(assert, stream);
161 
162 	kunit_print_string_stream(test, stream);
163 
164 	WARN_ON(string_stream_destroy(stream));
165 }
166 
167 static void __noreturn kunit_abort(struct kunit *test)
168 {
169 	kunit_try_catch_throw(&test->try_catch); /* Does not return. */
170 
171 	/*
172 	 * Throw could not abort from test.
173 	 *
174 	 * XXX: we should never reach this line! As kunit_try_catch_throw is
175 	 * marked __noreturn.
176 	 */
177 	WARN_ONCE(true, "Throw could not abort from test!\n");
178 }
179 
180 void kunit_do_assertion(struct kunit *test,
181 			struct kunit_assert *assert,
182 			bool pass,
183 			const char *fmt, ...)
184 {
185 	va_list args;
186 
187 	if (pass)
188 		return;
189 
190 	va_start(args, fmt);
191 
192 	assert->message.fmt = fmt;
193 	assert->message.va = &args;
194 
195 	kunit_fail(test, assert);
196 
197 	va_end(args);
198 
199 	if (assert->type == KUNIT_ASSERTION)
200 		kunit_abort(test);
201 }
202 
203 void kunit_init_test(struct kunit *test, const char *name)
204 {
205 	spin_lock_init(&test->lock);
206 	INIT_LIST_HEAD(&test->resources);
207 	test->name = name;
208 	test->success = true;
209 }
210 
211 /*
212  * Initializes and runs test case. Does not clean up or do post validations.
213  */
214 static void kunit_run_case_internal(struct kunit *test,
215 				    struct kunit_suite *suite,
216 				    struct kunit_case *test_case)
217 {
218 	if (suite->init) {
219 		int ret;
220 
221 		ret = suite->init(test);
222 		if (ret) {
223 			kunit_err(test, "failed to initialize: %d\n", ret);
224 			kunit_set_failure(test);
225 			return;
226 		}
227 	}
228 
229 	test_case->run_case(test);
230 }
231 
232 static void kunit_case_internal_cleanup(struct kunit *test)
233 {
234 	kunit_cleanup(test);
235 }
236 
237 /*
238  * Performs post validations and cleanup after a test case was run.
239  * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
240  */
241 static void kunit_run_case_cleanup(struct kunit *test,
242 				   struct kunit_suite *suite)
243 {
244 	if (suite->exit)
245 		suite->exit(test);
246 
247 	kunit_case_internal_cleanup(test);
248 }
249 
250 struct kunit_try_catch_context {
251 	struct kunit *test;
252 	struct kunit_suite *suite;
253 	struct kunit_case *test_case;
254 };
255 
256 static void kunit_try_run_case(void *data)
257 {
258 	struct kunit_try_catch_context *ctx = data;
259 	struct kunit *test = ctx->test;
260 	struct kunit_suite *suite = ctx->suite;
261 	struct kunit_case *test_case = ctx->test_case;
262 
263 	/*
264 	 * kunit_run_case_internal may encounter a fatal error; if it does,
265 	 * abort will be called, this thread will exit, and finally the parent
266 	 * thread will resume control and handle any necessary clean up.
267 	 */
268 	kunit_run_case_internal(test, suite, test_case);
269 	/* This line may never be reached. */
270 	kunit_run_case_cleanup(test, suite);
271 }
272 
273 static void kunit_catch_run_case(void *data)
274 {
275 	struct kunit_try_catch_context *ctx = data;
276 	struct kunit *test = ctx->test;
277 	struct kunit_suite *suite = ctx->suite;
278 	int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
279 
280 	if (try_exit_code) {
281 		kunit_set_failure(test);
282 		/*
283 		 * Test case could not finish, we have no idea what state it is
284 		 * in, so don't do clean up.
285 		 */
286 		if (try_exit_code == -ETIMEDOUT) {
287 			kunit_err(test, "test case timed out\n");
288 		/*
289 		 * Unknown internal error occurred preventing test case from
290 		 * running, so there is nothing to clean up.
291 		 */
292 		} else {
293 			kunit_err(test, "internal error occurred preventing test case from running: %d\n",
294 				  try_exit_code);
295 		}
296 		return;
297 	}
298 
299 	/*
300 	 * Test case was run, but aborted. It is the test case's business as to
301 	 * whether it failed or not, we just need to clean up.
302 	 */
303 	kunit_run_case_cleanup(test, suite);
304 }
305 
306 /*
307  * Performs all logic to run a test case. It also catches most errors that
308  * occur in a test case and reports them as failures.
309  */
310 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
311 					struct kunit_case *test_case)
312 {
313 	struct kunit_try_catch_context context;
314 	struct kunit_try_catch *try_catch;
315 	struct kunit test;
316 
317 	kunit_init_test(&test, test_case->name);
318 	try_catch = &test.try_catch;
319 
320 	kunit_try_catch_init(try_catch,
321 			     &test,
322 			     kunit_try_run_case,
323 			     kunit_catch_run_case);
324 	context.test = &test;
325 	context.suite = suite;
326 	context.test_case = test_case;
327 	kunit_try_catch_run(try_catch, &context);
328 
329 	test_case->success = test.success;
330 }
331 
332 int kunit_run_tests(struct kunit_suite *suite)
333 {
334 	struct kunit_case *test_case;
335 	size_t test_case_count = 1;
336 
337 	kunit_print_subtest_start(suite);
338 
339 	for (test_case = suite->test_cases; test_case->run_case; test_case++) {
340 		kunit_run_case_catch_errors(suite, test_case);
341 		kunit_print_test_case_ok_not_ok(test_case, test_case_count++);
342 	}
343 
344 	kunit_print_subtest_end(suite);
345 
346 	return 0;
347 }
348 
349 struct kunit_resource *kunit_alloc_and_get_resource(struct kunit *test,
350 						    kunit_resource_init_t init,
351 						    kunit_resource_free_t free,
352 						    gfp_t internal_gfp,
353 						    void *context)
354 {
355 	struct kunit_resource *res;
356 	int ret;
357 
358 	res = kzalloc(sizeof(*res), internal_gfp);
359 	if (!res)
360 		return NULL;
361 
362 	ret = init(res, context);
363 	if (ret)
364 		return NULL;
365 
366 	res->free = free;
367 	spin_lock(&test->lock);
368 	list_add_tail(&res->node, &test->resources);
369 	spin_unlock(&test->lock);
370 
371 	return res;
372 }
373 
374 static void kunit_resource_free(struct kunit *test, struct kunit_resource *res)
375 {
376 	res->free(res);
377 	kfree(res);
378 }
379 
380 static struct kunit_resource *kunit_resource_find(struct kunit *test,
381 						  kunit_resource_match_t match,
382 						  kunit_resource_free_t free,
383 						  void *match_data)
384 {
385 	struct kunit_resource *resource;
386 
387 	lockdep_assert_held(&test->lock);
388 
389 	list_for_each_entry_reverse(resource, &test->resources, node) {
390 		if (resource->free != free)
391 			continue;
392 		if (match(test, resource->allocation, match_data))
393 			return resource;
394 	}
395 
396 	return NULL;
397 }
398 
399 static struct kunit_resource *kunit_resource_remove(
400 		struct kunit *test,
401 		kunit_resource_match_t match,
402 		kunit_resource_free_t free,
403 		void *match_data)
404 {
405 	struct kunit_resource *resource;
406 
407 	spin_lock(&test->lock);
408 	resource = kunit_resource_find(test, match, free, match_data);
409 	if (resource)
410 		list_del(&resource->node);
411 	spin_unlock(&test->lock);
412 
413 	return resource;
414 }
415 
416 int kunit_resource_destroy(struct kunit *test,
417 			   kunit_resource_match_t match,
418 			   kunit_resource_free_t free,
419 			   void *match_data)
420 {
421 	struct kunit_resource *resource;
422 
423 	resource = kunit_resource_remove(test, match, free, match_data);
424 
425 	if (!resource)
426 		return -ENOENT;
427 
428 	kunit_resource_free(test, resource);
429 	return 0;
430 }
431 
432 struct kunit_kmalloc_params {
433 	size_t size;
434 	gfp_t gfp;
435 };
436 
437 static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
438 {
439 	struct kunit_kmalloc_params *params = context;
440 
441 	res->allocation = kmalloc(params->size, params->gfp);
442 	if (!res->allocation)
443 		return -ENOMEM;
444 
445 	return 0;
446 }
447 
448 static void kunit_kmalloc_free(struct kunit_resource *res)
449 {
450 	kfree(res->allocation);
451 }
452 
453 void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
454 {
455 	struct kunit_kmalloc_params params = {
456 		.size = size,
457 		.gfp = gfp
458 	};
459 
460 	return kunit_alloc_resource(test,
461 				    kunit_kmalloc_init,
462 				    kunit_kmalloc_free,
463 				    gfp,
464 				    &params);
465 }
466 
467 void kunit_kfree(struct kunit *test, const void *ptr)
468 {
469 	int rc;
470 
471 	rc = kunit_resource_destroy(test,
472 				    kunit_resource_instance_match,
473 				    kunit_kmalloc_free,
474 				    (void *)ptr);
475 
476 	WARN_ON(rc);
477 }
478 
479 void kunit_cleanup(struct kunit *test)
480 {
481 	struct kunit_resource *resource;
482 
483 	/*
484 	 * test->resources is a stack - each allocation must be freed in the
485 	 * reverse order from which it was added since one resource may depend
486 	 * on another for its entire lifetime.
487 	 * Also, we cannot use the normal list_for_each constructs, even the
488 	 * safe ones because *arbitrary* nodes may be deleted when
489 	 * kunit_resource_free is called; the list_for_each_safe variants only
490 	 * protect against the current node being deleted, not the next.
491 	 */
492 	while (true) {
493 		spin_lock(&test->lock);
494 		if (list_empty(&test->resources)) {
495 			spin_unlock(&test->lock);
496 			break;
497 		}
498 		resource = list_last_entry(&test->resources,
499 					   struct kunit_resource,
500 					   node);
501 		list_del(&resource->node);
502 		spin_unlock(&test->lock);
503 
504 		kunit_resource_free(test, resource);
505 	}
506 }
507 
508 void kunit_printk(const char *level,
509 		  const struct kunit *test,
510 		  const char *fmt, ...)
511 {
512 	struct va_format vaf;
513 	va_list args;
514 
515 	va_start(args, fmt);
516 
517 	vaf.fmt = fmt;
518 	vaf.va = &args;
519 
520 	kunit_vprintk(test, level, &vaf);
521 
522 	va_end(args);
523 }
524