1 /* SPDX-License-Identifier: GPL-2.0-only */
3 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
5 * kselftest_harness.h: simple C unit test helper.
7 * See documentation in Documentation/dev-tools/kselftest.rst
9 * API inspired by code.google.com/p/googletest
17 * #include "../kselftest_harness.h"
19 * TEST(standalone_test) {
21 * EXPECT_GT(10, stuff) {
22 * stuff_state_t state;
23 * enumerate_stuff_state(&state);
24 * TH_LOG("expectation failed with state: %s", state.msg);
27 * ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!");
29 * EXPECT_EQ(0, last_stuff);
32 * FIXTURE(my_fixture) {
34 * int awesomeness_level;
36 * FIXTURE_SETUP(my_fixture) {
37 * self->data = mytype_new();
38 * ASSERT_NE(NULL, self->data);
40 * FIXTURE_TEARDOWN(my_fixture) {
41 * mytype_free(self->data);
43 * TEST_F(my_fixture, data_is_good) {
44 * EXPECT_EQ(1, is_my_data_good(self->data));
50 #ifndef __KSELFTEST_HARNESS_H
51 #define __KSELFTEST_HARNESS_H
56 #include <asm/types.h>
65 #include <sys/types.h>
70 #include <linux/sched.h>
72 #include "kselftest.h"
74 #define TEST_TIMEOUT_DEFAULT 30
76 /* Utilities exposed to the test definitions */
78 # define TH_LOG_STREAM stderr
81 #ifndef TH_LOG_ENABLED
82 # define TH_LOG_ENABLED 1
85 /* Wait for the child process to end but without sharing memory mapping. */
86 static inline pid_t clone3_vfork(void)
88 struct clone_args args = {
90 .exit_signal = SIGCHLD,
93 return syscall(__NR_clone3, &args, sizeof(args));
100 * @...: optional arguments
104 * TH_LOG(format, ...)
106 * Optional debug logging function available for use in tests.
107 * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
108 * E.g., #define TH_LOG_ENABLED 1
110 * If no definition is provided, logging is enabled by default.
112 #define TH_LOG(fmt, ...) do { \
113 if (TH_LOG_ENABLED) \
114 __TH_LOG(fmt, ##__VA_ARGS__); \
117 /* Unconditional logger for internal use. */
118 #define __TH_LOG(fmt, ...) \
119 fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \
120 __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
125 * @statement: statement to run after reporting SKIP
126 * @fmt: format string
127 * @...: optional arguments
131 * SKIP(statement, fmt, ...);
133 * This forces a "pass" after reporting why something is being skipped
134 * and runs "statement", which is usually "return" or "goto skip".
136 #define SKIP(statement, fmt, ...) do { \
137 snprintf(_metadata->results->reason, \
138 sizeof(_metadata->results->reason), fmt, ##__VA_ARGS__); \
139 if (TH_LOG_ENABLED) { \
140 fprintf(TH_LOG_STREAM, "# SKIP %s\n", \
141 _metadata->results->reason); \
143 _metadata->exit_code = KSFT_SKIP; \
144 _metadata->trigger = 0; \
149 * TEST() - Defines the test function and creates the registration
152 * @test_name: test name
156 * TEST(name) { implementation }
158 * Defines a test by name.
159 * Names must be unique and tests must not be run in parallel. The
160 * implementation containing block is a function and scoping should be treated
161 * as such. Returning early may be performed with a bare "return;" statement.
163 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
165 #define TEST(test_name) __TEST_IMPL(test_name, -1)
170 * @test_name: test name
171 * @signal: signal number
175 * TEST_SIGNAL(name, signal) { implementation }
177 * Defines a test by name and the expected term signal.
178 * Names must be unique and tests must not be run in parallel. The
179 * implementation containing block is a function and scoping should be treated
180 * as such. Returning early may be performed with a bare "return;" statement.
182 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
184 #define TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
186 #define __TEST_IMPL(test_name, _signal) \
187 static void test_name(struct __test_metadata *_metadata); \
188 static inline void wrapper_##test_name( \
189 struct __test_metadata *_metadata, \
190 struct __fixture_variant_metadata *variant) \
192 _metadata->setup_completed = true; \
193 if (setjmp(_metadata->env) == 0) \
194 test_name(_metadata); \
195 __test_check_assert(_metadata); \
197 static struct __test_metadata _##test_name##_object = \
198 { .name = #test_name, \
199 .fn = &wrapper_##test_name, \
200 .fixture = &_fixture_global, \
201 .termsig = _signal, \
202 .timeout = TEST_TIMEOUT_DEFAULT, }; \
203 static void __attribute__((constructor)) _register_##test_name(void) \
205 __register_test(&_##test_name##_object); \
207 static void test_name( \
208 struct __test_metadata __attribute__((unused)) *_metadata)
211 * FIXTURE_DATA() - Wraps the struct name so we have one less
212 * argument to pass around
214 * @datatype_name: datatype name
218 * FIXTURE_DATA(datatype_name)
220 * Almost always, you want just FIXTURE() instead (see below).
221 * This call may be used when the type of the fixture data
222 * is needed. In general, this should not be needed unless
223 * the *self* is being passed to a helper directly.
225 #define FIXTURE_DATA(datatype_name) struct _test_data_##datatype_name
228 * FIXTURE() - Called once per fixture to setup the data and
231 * @fixture_name: fixture name
235 * FIXTURE(fixture_name) {
240 * Defines the data provided to TEST_F()-defined tests as *self*. It should be
241 * populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN().
243 #define FIXTURE(fixture_name) \
244 FIXTURE_VARIANT(fixture_name); \
245 static struct __fixture_metadata _##fixture_name##_fixture_object = \
246 { .name = #fixture_name, }; \
247 static void __attribute__((constructor)) \
248 _register_##fixture_name##_data(void) \
250 __register_fixture(&_##fixture_name##_fixture_object); \
252 FIXTURE_DATA(fixture_name)
255 * FIXTURE_SETUP() - Prepares the setup function for the fixture.
256 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly.
258 * @fixture_name: fixture name
262 * FIXTURE_SETUP(fixture_name) { implementation }
264 * Populates the required "setup" function for a fixture. An instance of the
265 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
268 * ASSERT_* are valid for use in this context and will prempt the execution
269 * of any dependent fixture tests.
271 * A bare "return;" statement may be used to return early.
273 #define FIXTURE_SETUP(fixture_name) \
274 void fixture_name##_setup( \
275 struct __test_metadata __attribute__((unused)) *_metadata, \
276 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
277 const FIXTURE_VARIANT(fixture_name) \
278 __attribute__((unused)) *variant)
282 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly.
284 * @fixture_name: fixture name
288 * FIXTURE_TEARDOWN(fixture_name) { implementation }
290 * Populates the required "teardown" function for a fixture. An instance of the
291 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
292 * implementation to clean up.
294 * A bare "return;" statement may be used to return early.
296 #define FIXTURE_TEARDOWN(fixture_name) \
297 static const bool fixture_name##_teardown_parent; \
298 __FIXTURE_TEARDOWN(fixture_name)
301 * FIXTURE_TEARDOWN_PARENT()
302 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly.
304 * @fixture_name: fixture name
308 * FIXTURE_TEARDOWN_PARENT(fixture_name) { implementation }
310 * Same as FIXTURE_TEARDOWN() but run this code in a parent process. This
311 * enables the test process to drop its privileges without impacting the
312 * related FIXTURE_TEARDOWN_PARENT() (e.g. to remove files from a directory
313 * where write access was dropped).
315 * To make it possible for the parent process to use *self*, share (MAP_SHARED)
316 * the fixture data between all forked processes.
318 #define FIXTURE_TEARDOWN_PARENT(fixture_name) \
319 static const bool fixture_name##_teardown_parent = true; \
320 __FIXTURE_TEARDOWN(fixture_name)
322 #define __FIXTURE_TEARDOWN(fixture_name) \
323 void fixture_name##_teardown( \
324 struct __test_metadata __attribute__((unused)) *_metadata, \
325 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
326 const FIXTURE_VARIANT(fixture_name) \
327 __attribute__((unused)) *variant)
330 * FIXTURE_VARIANT() - Optionally called once per fixture
331 * to declare fixture variant
333 * @fixture_name: fixture name
337 * FIXTURE_VARIANT(fixture_name) {
342 * Defines type of constant parameters provided to FIXTURE_SETUP(), TEST_F() and
343 * FIXTURE_TEARDOWN as *variant*. Variants allow the same tests to be run with
344 * different arguments.
346 #define FIXTURE_VARIANT(fixture_name) struct _fixture_variant_##fixture_name
349 * FIXTURE_VARIANT_ADD() - Called once per fixture
350 * variant to setup and register the data
352 * @fixture_name: fixture name
353 * @variant_name: name of the parameter set
357 * FIXTURE_VARIANT_ADD(fixture_name, variant_name) {
362 * Defines a variant of the test fixture, provided to FIXTURE_SETUP() and
363 * TEST_F() as *variant*. Tests of each fixture will be run once for each
366 #define FIXTURE_VARIANT_ADD(fixture_name, variant_name) \
367 extern const FIXTURE_VARIANT(fixture_name) \
368 _##fixture_name##_##variant_name##_variant; \
369 static struct __fixture_variant_metadata \
370 _##fixture_name##_##variant_name##_object = \
371 { .name = #variant_name, \
372 .data = &_##fixture_name##_##variant_name##_variant}; \
373 static void __attribute__((constructor)) \
374 _register_##fixture_name##_##variant_name(void) \
376 __register_fixture_variant(&_##fixture_name##_fixture_object, \
377 &_##fixture_name##_##variant_name##_object); \
379 const FIXTURE_VARIANT(fixture_name) \
380 _##fixture_name##_##variant_name##_variant =
383 * TEST_F() - Emits test registration and helpers for
384 * fixture-based test cases
386 * @fixture_name: fixture name
387 * @test_name: test name
391 * TEST_F(fixture, name) { implementation }
393 * Defines a test that depends on a fixture (e.g., is part of a test case).
394 * Very similar to TEST() except that *self* is the setup instance of fixture's
395 * datatype exposed for use by the implementation.
397 * The _metadata object is shared (MAP_SHARED) with all the potential forked
398 * processes, which enables them to use EXCEPT_*() and ASSERT_*().
400 * The *self* object is only shared with the potential forked processes if
401 * FIXTURE_TEARDOWN_PARENT() is used instead of FIXTURE_TEARDOWN().
403 #define TEST_F(fixture_name, test_name) \
404 __TEST_F_IMPL(fixture_name, test_name, -1, TEST_TIMEOUT_DEFAULT)
406 #define TEST_F_SIGNAL(fixture_name, test_name, signal) \
407 __TEST_F_IMPL(fixture_name, test_name, signal, TEST_TIMEOUT_DEFAULT)
409 #define TEST_F_TIMEOUT(fixture_name, test_name, timeout) \
410 __TEST_F_IMPL(fixture_name, test_name, -1, timeout)
412 #define __TEST_F_IMPL(fixture_name, test_name, signal, tmout) \
413 static void fixture_name##_##test_name( \
414 struct __test_metadata *_metadata, \
415 FIXTURE_DATA(fixture_name) *self, \
416 const FIXTURE_VARIANT(fixture_name) *variant); \
417 static inline void wrapper_##fixture_name##_##test_name( \
418 struct __test_metadata *_metadata, \
419 struct __fixture_variant_metadata *variant) \
421 /* fixture data is alloced, setup, and torn down per call. */ \
422 FIXTURE_DATA(fixture_name) self_private, *self = NULL; \
425 /* Makes sure there is only one teardown, even when child forks again. */ \
426 bool *teardown = mmap(NULL, sizeof(*teardown), \
427 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); \
429 if (sizeof(*self) > 0) { \
430 if (fixture_name##_teardown_parent) { \
431 self = mmap(NULL, sizeof(*self), PROT_READ | PROT_WRITE, \
432 MAP_SHARED | MAP_ANONYMOUS, -1, 0); \
434 memset(&self_private, 0, sizeof(self_private)); \
435 self = &self_private; \
438 if (setjmp(_metadata->env) == 0) { \
439 /* _metadata and potentially self are shared with all forks. */ \
440 child = clone3_vfork(); \
442 fixture_name##_setup(_metadata, self, variant->data); \
443 /* Let setup failure terminate early. */ \
444 if (_metadata->exit_code) \
446 _metadata->setup_completed = true; \
447 fixture_name##_##test_name(_metadata, self, variant->data); \
448 } else if (child < 0 || child != waitpid(child, &status, 0)) { \
449 ksft_print_msg("ERROR SPAWNING TEST GRANDCHILD\n"); \
450 _metadata->exit_code = KSFT_FAIL; \
454 if (_metadata->setup_completed && !fixture_name##_teardown_parent && \
455 __sync_bool_compare_and_swap(teardown, false, true)) \
456 fixture_name##_teardown(_metadata, self, variant->data); \
459 if (_metadata->setup_completed && fixture_name##_teardown_parent && \
460 __sync_bool_compare_and_swap(teardown, false, true)) \
461 fixture_name##_teardown(_metadata, self, variant->data); \
462 munmap(teardown, sizeof(*teardown)); \
463 if (self && fixture_name##_teardown_parent) \
464 munmap(self, sizeof(*self)); \
465 if (WIFEXITED(status)) { \
466 if (WEXITSTATUS(status)) \
467 _metadata->exit_code = WEXITSTATUS(status); \
468 } else if (WIFSIGNALED(status)) { \
469 /* Forward signal to __wait_for_test(). */ \
470 kill(getpid(), WTERMSIG(status)); \
472 __test_check_assert(_metadata); \
474 static struct __test_metadata *_##fixture_name##_##test_name##_object; \
475 static void __attribute__((constructor)) \
476 _register_##fixture_name##_##test_name(void) \
478 struct __test_metadata *object = mmap(NULL, sizeof(*object), \
479 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); \
480 object->name = #test_name; \
481 object->fn = &wrapper_##fixture_name##_##test_name; \
482 object->fixture = &_##fixture_name##_fixture_object; \
483 object->termsig = signal; \
484 object->timeout = tmout; \
485 _##fixture_name##_##test_name##_object = object; \
486 __register_test(object); \
488 static void fixture_name##_##test_name( \
489 struct __test_metadata __attribute__((unused)) *_metadata, \
490 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
491 const FIXTURE_VARIANT(fixture_name) \
492 __attribute__((unused)) *variant)
495 * TEST_HARNESS_MAIN - Simple wrapper to run the test harness
501 * Use once to append a main() to the test file.
503 #define TEST_HARNESS_MAIN \
504 static void __attribute__((constructor)) \
505 __constructor_order_last(void) \
507 if (!__constructor_order) \
508 __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
510 int main(int argc, char **argv) { \
511 return test_harness_run(argc, argv); \
517 * Operators for use in TEST() and TEST_F().
518 * ASSERT_* calls will stop test execution immediately.
519 * EXPECT_* calls will emit a failure warning, note it, and continue.
525 * @expected: expected value
526 * @seen: measured value
528 * ASSERT_EQ(expected, measured): expected == measured
530 #define ASSERT_EQ(expected, seen) \
531 __EXPECT(expected, #expected, seen, #seen, ==, 1)
536 * @expected: expected value
537 * @seen: measured value
539 * ASSERT_NE(expected, measured): expected != measured
541 #define ASSERT_NE(expected, seen) \
542 __EXPECT(expected, #expected, seen, #seen, !=, 1)
547 * @expected: expected value
548 * @seen: measured value
550 * ASSERT_LT(expected, measured): expected < measured
552 #define ASSERT_LT(expected, seen) \
553 __EXPECT(expected, #expected, seen, #seen, <, 1)
558 * @expected: expected value
559 * @seen: measured value
561 * ASSERT_LE(expected, measured): expected <= measured
563 #define ASSERT_LE(expected, seen) \
564 __EXPECT(expected, #expected, seen, #seen, <=, 1)
569 * @expected: expected value
570 * @seen: measured value
572 * ASSERT_GT(expected, measured): expected > measured
574 #define ASSERT_GT(expected, seen) \
575 __EXPECT(expected, #expected, seen, #seen, >, 1)
580 * @expected: expected value
581 * @seen: measured value
583 * ASSERT_GE(expected, measured): expected >= measured
585 #define ASSERT_GE(expected, seen) \
586 __EXPECT(expected, #expected, seen, #seen, >=, 1)
591 * @seen: measured value
593 * ASSERT_NULL(measured): NULL == measured
595 #define ASSERT_NULL(seen) \
596 __EXPECT(NULL, "NULL", seen, #seen, ==, 1)
601 * @seen: measured value
603 * ASSERT_TRUE(measured): measured != 0
605 #define ASSERT_TRUE(seen) \
606 __EXPECT(0, "0", seen, #seen, !=, 1)
611 * @seen: measured value
613 * ASSERT_FALSE(measured): measured == 0
615 #define ASSERT_FALSE(seen) \
616 __EXPECT(0, "0", seen, #seen, ==, 1)
621 * @expected: expected value
622 * @seen: measured value
624 * ASSERT_STREQ(expected, measured): !strcmp(expected, measured)
626 #define ASSERT_STREQ(expected, seen) \
627 __EXPECT_STR(expected, seen, ==, 1)
632 * @expected: expected value
633 * @seen: measured value
635 * ASSERT_STRNE(expected, measured): strcmp(expected, measured)
637 #define ASSERT_STRNE(expected, seen) \
638 __EXPECT_STR(expected, seen, !=, 1)
643 * @expected: expected value
644 * @seen: measured value
646 * EXPECT_EQ(expected, measured): expected == measured
648 #define EXPECT_EQ(expected, seen) \
649 __EXPECT(expected, #expected, seen, #seen, ==, 0)
654 * @expected: expected value
655 * @seen: measured value
657 * EXPECT_NE(expected, measured): expected != measured
659 #define EXPECT_NE(expected, seen) \
660 __EXPECT(expected, #expected, seen, #seen, !=, 0)
665 * @expected: expected value
666 * @seen: measured value
668 * EXPECT_LT(expected, measured): expected < measured
670 #define EXPECT_LT(expected, seen) \
671 __EXPECT(expected, #expected, seen, #seen, <, 0)
676 * @expected: expected value
677 * @seen: measured value
679 * EXPECT_LE(expected, measured): expected <= measured
681 #define EXPECT_LE(expected, seen) \
682 __EXPECT(expected, #expected, seen, #seen, <=, 0)
687 * @expected: expected value
688 * @seen: measured value
690 * EXPECT_GT(expected, measured): expected > measured
692 #define EXPECT_GT(expected, seen) \
693 __EXPECT(expected, #expected, seen, #seen, >, 0)
698 * @expected: expected value
699 * @seen: measured value
701 * EXPECT_GE(expected, measured): expected >= measured
703 #define EXPECT_GE(expected, seen) \
704 __EXPECT(expected, #expected, seen, #seen, >=, 0)
709 * @seen: measured value
711 * EXPECT_NULL(measured): NULL == measured
713 #define EXPECT_NULL(seen) \
714 __EXPECT(NULL, "NULL", seen, #seen, ==, 0)
719 * @seen: measured value
721 * EXPECT_TRUE(measured): 0 != measured
723 #define EXPECT_TRUE(seen) \
724 __EXPECT(0, "0", seen, #seen, !=, 0)
729 * @seen: measured value
731 * EXPECT_FALSE(measured): 0 == measured
733 #define EXPECT_FALSE(seen) \
734 __EXPECT(0, "0", seen, #seen, ==, 0)
739 * @expected: expected value
740 * @seen: measured value
742 * EXPECT_STREQ(expected, measured): !strcmp(expected, measured)
744 #define EXPECT_STREQ(expected, seen) \
745 __EXPECT_STR(expected, seen, ==, 0)
750 * @expected: expected value
751 * @seen: measured value
753 * EXPECT_STRNE(expected, measured): strcmp(expected, measured)
755 #define EXPECT_STRNE(expected, seen) \
756 __EXPECT_STR(expected, seen, !=, 0)
759 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
762 /* Support an optional handler after and ASSERT_* or EXPECT_*. The approach is
763 * not thread-safe, but it should be fine in most sane test scenarios.
765 * Using __bail(), which optionally abort()s, is the easiest way to early
766 * return while still providing an optional block to the API consumer.
768 #define OPTIONAL_HANDLER(_assert) \
769 for (; _metadata->trigger; _metadata->trigger = \
770 __bail(_assert, _metadata))
772 #define is_signed_type(var) (!!(((__typeof__(var))(-1)) < (__typeof__(var))1))
774 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \
775 /* Avoid multiple evaluation of the cases */ \
776 __typeof__(_expected) __exp = (_expected); \
777 __typeof__(_seen) __seen = (_seen); \
778 if (!(__exp _t __seen)) { \
779 /* Report with actual signedness to avoid weird output. */ \
780 switch (is_signed_type(__exp) * 2 + is_signed_type(__seen)) { \
782 unsigned long long __exp_print = (uintptr_t)__exp; \
783 unsigned long long __seen_print = (uintptr_t)__seen; \
784 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
785 _expected_str, __exp_print, #_t, \
786 _seen_str, __seen_print); \
790 unsigned long long __exp_print = (uintptr_t)__exp; \
791 long long __seen_print = (intptr_t)__seen; \
792 __TH_LOG("Expected %s (%llu) %s %s (%lld)", \
793 _expected_str, __exp_print, #_t, \
794 _seen_str, __seen_print); \
798 long long __exp_print = (intptr_t)__exp; \
799 unsigned long long __seen_print = (uintptr_t)__seen; \
800 __TH_LOG("Expected %s (%lld) %s %s (%llu)", \
801 _expected_str, __exp_print, #_t, \
802 _seen_str, __seen_print); \
806 long long __exp_print = (intptr_t)__exp; \
807 long long __seen_print = (intptr_t)__seen; \
808 __TH_LOG("Expected %s (%lld) %s %s (%lld)", \
809 _expected_str, __exp_print, #_t, \
810 _seen_str, __seen_print); \
814 _metadata->exit_code = KSFT_FAIL; \
815 /* Ensure the optional handler is triggered */ \
816 _metadata->trigger = 1; \
818 } while (0); OPTIONAL_HANDLER(_assert)
820 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
821 const char *__exp = (_expected); \
822 const char *__seen = (_seen); \
823 if (!(strcmp(__exp, __seen) _t 0)) { \
824 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
825 _metadata->exit_code = KSFT_FAIL; \
826 _metadata->trigger = 1; \
828 } while (0); OPTIONAL_HANDLER(_assert)
831 #define __LIST_APPEND(head, item) \
833 /* Circular linked list where only prev is circular. */ \
834 if (head == NULL) { \
840 if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \
842 item->prev = head->prev; \
843 item->prev->next = item; \
847 item->next->prev = item; \
853 struct __test_results {
854 char reason[1024]; /* Reason for test result */
857 struct __test_metadata;
858 struct __fixture_variant_metadata;
860 /* Contains all the information about a fixture. */
861 struct __fixture_metadata {
863 struct __test_metadata *tests;
864 struct __fixture_variant_metadata *variant;
865 struct __fixture_metadata *prev, *next;
866 } _fixture_global __attribute__((unused)) = {
868 .prev = &_fixture_global,
871 struct __test_xfail {
872 struct __fixture_metadata *fixture;
873 struct __fixture_variant_metadata *variant;
874 struct __test_metadata *test;
875 struct __test_xfail *prev, *next;
879 * XFAIL_ADD() - mark variant + test case combination as expected to fail
880 * @fixture_name: name of the fixture
881 * @variant_name: name of the variant
882 * @test_name: name of the test case
884 * Mark a combination of variant + test case for a given fixture as expected
885 * to fail. Tests marked this way will report XPASS / XFAIL return codes,
886 * instead of PASS / FAIL,and use respective counters.
888 #define XFAIL_ADD(fixture_name, variant_name, test_name) \
889 static struct __test_xfail \
890 _##fixture_name##_##variant_name##_##test_name##_xfail = \
892 .fixture = &_##fixture_name##_fixture_object, \
893 .variant = &_##fixture_name##_##variant_name##_object, \
895 static void __attribute__((constructor)) \
896 _register_##fixture_name##_##variant_name##_##test_name##_xfail(void) \
898 _##fixture_name##_##variant_name##_##test_name##_xfail.test = \
899 _##fixture_name##_##test_name##_object; \
900 __register_xfail(&_##fixture_name##_##variant_name##_##test_name##_xfail); \
903 static struct __fixture_metadata *__fixture_list = &_fixture_global;
904 static int __constructor_order;
906 #define _CONSTRUCTOR_ORDER_FORWARD 1
907 #define _CONSTRUCTOR_ORDER_BACKWARD -1
909 static inline void __register_fixture(struct __fixture_metadata *f)
911 __LIST_APPEND(__fixture_list, f);
914 struct __fixture_variant_metadata {
917 struct __test_xfail *xfails;
918 struct __fixture_variant_metadata *prev, *next;
922 __register_fixture_variant(struct __fixture_metadata *f,
923 struct __fixture_variant_metadata *variant)
925 __LIST_APPEND(f->variant, variant);
928 /* Contains all the information for test execution and status checking. */
929 struct __test_metadata {
931 void (*fn)(struct __test_metadata *,
932 struct __fixture_variant_metadata *);
933 pid_t pid; /* pid of test when being run */
934 struct __fixture_metadata *fixture;
937 int trigger; /* extra handler after the evaluation */
938 int timeout; /* seconds to wait for test timeout */
939 bool timed_out; /* did this test timeout instead of exiting? */
940 bool aborted; /* stopped test due to failed ASSERT */
941 bool setup_completed; /* did setup finish? */
942 jmp_buf env; /* for exiting out of test early */
943 struct __test_results *results;
944 struct __test_metadata *prev, *next;
947 static inline bool __test_passed(struct __test_metadata *metadata)
949 return metadata->exit_code != KSFT_FAIL &&
950 metadata->exit_code <= KSFT_SKIP;
954 * Since constructors are called in reverse order, reverse the test
955 * list so tests are run in source declaration order.
956 * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
957 * However, it seems not all toolchains do this correctly, so use
958 * __constructor_order to detect which direction is called first
959 * and adjust list building logic to get things running in the right
962 static inline void __register_test(struct __test_metadata *t)
964 __LIST_APPEND(t->fixture->tests, t);
967 static inline void __register_xfail(struct __test_xfail *xf)
969 __LIST_APPEND(xf->variant->xfails, xf);
972 static inline int __bail(int for_realz, struct __test_metadata *t)
974 /* if this is ASSERT, return immediately. */
979 /* otherwise, end the for loop and continue. */
983 static inline void __test_check_assert(struct __test_metadata *t)
989 struct __test_metadata *__active_test;
990 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext)
992 struct __test_metadata *t = __active_test;
994 /* Sanity check handler execution environment. */
996 fprintf(TH_LOG_STREAM,
997 "# no active test in SIGALRM handler!?\n");
1000 if (sig != SIGALRM || sig != info->si_signo) {
1001 fprintf(TH_LOG_STREAM,
1002 "# %s: SIGALRM handler caught signal %d!?\n",
1003 t->name, sig != SIGALRM ? sig : info->si_signo);
1007 t->timed_out = true;
1008 // signal process group
1009 kill(-(t->pid), SIGKILL);
1012 void __wait_for_test(struct __test_metadata *t)
1014 struct sigaction action = {
1015 .sa_sigaction = __timeout_handler,
1016 .sa_flags = SA_SIGINFO,
1018 struct sigaction saved_action;
1021 if (sigaction(SIGALRM, &action, &saved_action)) {
1022 t->exit_code = KSFT_FAIL;
1023 fprintf(TH_LOG_STREAM,
1024 "# %s: unable to install SIGALRM handler\n",
1029 t->timed_out = false;
1031 waitpid(t->pid, &status, 0);
1033 if (sigaction(SIGALRM, &saved_action, NULL)) {
1034 t->exit_code = KSFT_FAIL;
1035 fprintf(TH_LOG_STREAM,
1036 "# %s: unable to uninstall SIGALRM handler\n",
1040 __active_test = NULL;
1043 t->exit_code = KSFT_FAIL;
1044 fprintf(TH_LOG_STREAM,
1045 "# %s: Test terminated by timeout\n", t->name);
1046 } else if (WIFEXITED(status)) {
1047 if (WEXITSTATUS(status) == KSFT_SKIP ||
1048 WEXITSTATUS(status) == KSFT_XPASS ||
1049 WEXITSTATUS(status) == KSFT_XFAIL) {
1050 t->exit_code = WEXITSTATUS(status);
1051 } else if (t->termsig != -1) {
1052 t->exit_code = KSFT_FAIL;
1053 fprintf(TH_LOG_STREAM,
1054 "# %s: Test exited normally instead of by signal (code: %d)\n",
1056 WEXITSTATUS(status));
1058 switch (WEXITSTATUS(status)) {
1061 t->exit_code = KSFT_PASS;
1065 t->exit_code = KSFT_FAIL;
1066 fprintf(TH_LOG_STREAM,
1067 "# %s: Test failed\n",
1071 } else if (WIFSIGNALED(status)) {
1072 t->exit_code = KSFT_FAIL;
1073 if (WTERMSIG(status) == SIGABRT) {
1074 fprintf(TH_LOG_STREAM,
1075 "# %s: Test terminated by assertion\n",
1077 } else if (WTERMSIG(status) == t->termsig) {
1078 t->exit_code = KSFT_PASS;
1080 fprintf(TH_LOG_STREAM,
1081 "# %s: Test terminated unexpectedly by signal %d\n",
1086 fprintf(TH_LOG_STREAM,
1087 "# %s: Test ended in some other way [%u]\n",
1093 static void test_harness_list_tests(void)
1095 struct __fixture_variant_metadata *v;
1096 struct __fixture_metadata *f;
1097 struct __test_metadata *t;
1099 for (f = __fixture_list; f; f = f->next) {
1103 if (f == __fixture_list)
1104 fprintf(stderr, "%-20s %-25s %s\n",
1105 "# FIXTURE", "VARIANT", "TEST");
1107 fprintf(stderr, "--------------------------------------------------------------------------------\n");
1110 fprintf(stderr, "%-20s %-25s %s\n",
1111 t == f->tests ? f->name : "",
1115 v = v ? v->next : NULL;
1116 t = t ? t->next : NULL;
1121 static int test_harness_argv_check(int argc, char **argv)
1125 while ((opt = getopt(argc, argv, "hlF:f:V:v:t:T:r:")) != -1) {
1136 test_harness_list_tests();
1141 "Usage: %s [-h|-l] [-t|-T|-v|-V|-f|-F|-r name]\n"
1143 "\t-l list all tests\n"
1145 "\t-t name include test\n"
1146 "\t-T name exclude test\n"
1147 "\t-v name include variant\n"
1148 "\t-V name exclude variant\n"
1149 "\t-f name include fixture\n"
1150 "\t-F name exclude fixture\n"
1151 "\t-r name run specified test\n"
1153 "Test filter options can be specified "
1154 "multiple times. The filtering stops\n"
1155 "at the first match. For example to "
1156 "include all tests from variant 'bla'\n"
1157 "but not test 'foo' specify '-T foo -v bla'.\n"
1159 return opt == 'h' ? KSFT_SKIP : KSFT_FAIL;
1166 static bool test_enabled(int argc, char **argv,
1167 struct __fixture_metadata *f,
1168 struct __fixture_variant_metadata *v,
1169 struct __test_metadata *t)
1171 unsigned int flen = 0, vlen = 0, tlen = 0;
1172 bool has_positive = false;
1176 while ((opt = getopt(argc, argv, "F:f:V:v:t:T:r:")) != -1) {
1177 has_positive |= islower(opt);
1179 switch (tolower(opt)) {
1181 if (!strcmp(t->name, optarg))
1182 return islower(opt);
1185 if (!strcmp(f->name, optarg))
1186 return islower(opt);
1189 if (!strcmp(v->name, optarg))
1190 return islower(opt);
1194 flen = strlen(f->name);
1195 vlen = strlen(v->name);
1196 tlen = strlen(t->name);
1198 if (strlen(optarg) == flen + 1 + vlen + !!vlen + tlen &&
1199 !strncmp(f->name, &optarg[0], flen) &&
1200 !strncmp(v->name, &optarg[flen + 1], vlen) &&
1201 !strncmp(t->name, &optarg[flen + 1 + vlen + !!vlen], tlen))
1208 * If there are no positive tests then we assume user just wants
1209 * exclusions and everything else is a pass.
1211 return !has_positive;
1214 void __run_test(struct __fixture_metadata *f,
1215 struct __fixture_variant_metadata *variant,
1216 struct __test_metadata *t)
1218 struct __test_xfail *xfail;
1219 char test_name[1024];
1220 const char *diagnostic;
1222 /* reset test struct */
1223 t->exit_code = KSFT_PASS;
1226 t->setup_completed = false;
1227 memset(t->env, 0, sizeof(t->env));
1228 memset(t->results->reason, 0, sizeof(t->results->reason));
1230 snprintf(test_name, sizeof(test_name), "%s%s%s.%s",
1231 f->name, variant->name[0] ? "." : "", variant->name, t->name);
1233 ksft_print_msg(" RUN %s ...\n", test_name);
1235 /* Make sure output buffers are flushed before fork */
1239 t->pid = clone3_vfork();
1241 ksft_print_msg("ERROR SPAWNING TEST CHILD\n");
1242 t->exit_code = KSFT_FAIL;
1243 } else if (t->pid == 0) {
1246 _exit(t->exit_code);
1250 ksft_print_msg(" %4s %s\n",
1251 __test_passed(t) ? "OK" : "FAIL", test_name);
1253 /* Check if we're expecting this test to fail */
1254 for (xfail = variant->xfails; xfail; xfail = xfail->next)
1255 if (xfail->test == t)
1258 t->exit_code = __test_passed(t) ? KSFT_XPASS : KSFT_XFAIL;
1260 if (t->results->reason[0])
1261 diagnostic = t->results->reason;
1262 else if (t->exit_code == KSFT_PASS || t->exit_code == KSFT_FAIL)
1265 diagnostic = "unknown";
1267 ksft_test_result_code(t->exit_code, test_name,
1268 diagnostic ? "%s" : NULL, diagnostic);
1271 static int test_harness_run(int argc, char **argv)
1273 struct __fixture_variant_metadata no_variant = { .name = "", };
1274 struct __fixture_variant_metadata *v;
1275 struct __fixture_metadata *f;
1276 struct __test_results *results;
1277 struct __test_metadata *t;
1279 unsigned int case_count = 0, test_count = 0;
1280 unsigned int count = 0;
1281 unsigned int pass_count = 0;
1283 ret = test_harness_argv_check(argc, argv);
1284 if (ret != KSFT_PASS)
1287 for (f = __fixture_list; f; f = f->next) {
1288 for (v = f->variant ?: &no_variant; v; v = v->next) {
1289 unsigned int old_tests = test_count;
1291 for (t = f->tests; t; t = t->next)
1292 if (test_enabled(argc, argv, f, v, t))
1295 if (old_tests != test_count)
1300 results = mmap(NULL, sizeof(*results), PROT_READ | PROT_WRITE,
1301 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1303 ksft_print_header();
1304 ksft_set_plan(test_count);
1305 ksft_print_msg("Starting %u tests from %u test cases.\n",
1306 test_count, case_count);
1307 for (f = __fixture_list; f; f = f->next) {
1308 for (v = f->variant ?: &no_variant; v; v = v->next) {
1309 for (t = f->tests; t; t = t->next) {
1310 if (!test_enabled(argc, argv, f, v, t))
1313 t->results = results;
1314 __run_test(f, v, t);
1316 if (__test_passed(t))
1323 munmap(results, sizeof(*results));
1325 ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED",
1327 ksft_exit(ret == 0);
1333 static void __attribute__((constructor)) __constructor_order_first(void)
1335 if (!__constructor_order)
1336 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
1339 #endif /* __KSELFTEST_HARNESS_H */