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 "kselftest.h"
72 #define TEST_TIMEOUT_DEFAULT 30
74 /* Utilities exposed to the test definitions */
76 # define TH_LOG_STREAM stderr
79 #ifndef TH_LOG_ENABLED
80 # define TH_LOG_ENABLED 1
87 * @...: optional arguments
93 * Optional debug logging function available for use in tests.
94 * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
95 * E.g., #define TH_LOG_ENABLED 1
97 * If no definition is provided, logging is enabled by default.
99 * If there is no way to print an error message for the process running the
100 * test (e.g. not allowed to write to stderr), it is still possible to get the
101 * ASSERT_* number for which the test failed. This behavior can be enabled by
102 * writing `_metadata->no_print = true;` before the check sequence that is
103 * unable to print. When an error occur, instead of printing an error message
104 * and calling `abort(3)`, the test process call `_exit(2)` with the assert
105 * number as argument, which is then printed by the parent process.
107 #define TH_LOG(fmt, ...) do { \
108 if (TH_LOG_ENABLED) \
109 __TH_LOG(fmt, ##__VA_ARGS__); \
112 /* Unconditional logger for internal use. */
113 #define __TH_LOG(fmt, ...) \
114 fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \
115 __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
120 * @statement: statement to run after reporting SKIP
121 * @fmt: format string
122 * @...: optional arguments
126 * SKIP(statement, fmt, ...);
128 * This forces a "pass" after reporting why something is being skipped
129 * and runs "statement", which is usually "return" or "goto skip".
131 #define SKIP(statement, fmt, ...) do { \
132 snprintf(_metadata->results->reason, \
133 sizeof(_metadata->results->reason), fmt, ##__VA_ARGS__); \
134 if (TH_LOG_ENABLED) { \
135 fprintf(TH_LOG_STREAM, "# SKIP %s\n", \
136 _metadata->results->reason); \
138 _metadata->passed = 1; \
139 _metadata->skip = 1; \
140 _metadata->trigger = 0; \
145 * TEST() - Defines the test function and creates the registration
148 * @test_name: test name
152 * TEST(name) { implementation }
154 * Defines a test by name.
155 * Names must be unique and tests must not be run in parallel. The
156 * implementation containing block is a function and scoping should be treated
157 * as such. Returning early may be performed with a bare "return;" statement.
159 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
161 #define TEST(test_name) __TEST_IMPL(test_name, -1)
166 * @test_name: test name
167 * @signal: signal number
171 * TEST_SIGNAL(name, signal) { implementation }
173 * Defines a test by name and the expected term signal.
174 * Names must be unique and tests must not be run in parallel. The
175 * implementation containing block is a function and scoping should be treated
176 * as such. Returning early may be performed with a bare "return;" statement.
178 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
180 #define TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
182 #define __TEST_IMPL(test_name, _signal) \
183 static void test_name(struct __test_metadata *_metadata); \
184 static inline void wrapper_##test_name( \
185 struct __test_metadata *_metadata, \
186 struct __fixture_variant_metadata *variant) \
188 _metadata->setup_completed = true; \
189 if (setjmp(_metadata->env) == 0) \
190 test_name(_metadata); \
191 __test_check_assert(_metadata); \
193 static struct __test_metadata _##test_name##_object = \
194 { .name = #test_name, \
195 .fn = &wrapper_##test_name, \
196 .fixture = &_fixture_global, \
197 .termsig = _signal, \
198 .timeout = TEST_TIMEOUT_DEFAULT, }; \
199 static void __attribute__((constructor)) _register_##test_name(void) \
201 __register_test(&_##test_name##_object); \
203 static void test_name( \
204 struct __test_metadata __attribute__((unused)) *_metadata)
207 * FIXTURE_DATA() - Wraps the struct name so we have one less
208 * argument to pass around
210 * @datatype_name: datatype name
214 * FIXTURE_DATA(datatype_name)
216 * Almost always, you want just FIXTURE() instead (see below).
217 * This call may be used when the type of the fixture data
218 * is needed. In general, this should not be needed unless
219 * the *self* is being passed to a helper directly.
221 #define FIXTURE_DATA(datatype_name) struct _test_data_##datatype_name
224 * FIXTURE() - Called once per fixture to setup the data and
227 * @fixture_name: fixture name
231 * FIXTURE(fixture_name) {
236 * Defines the data provided to TEST_F()-defined tests as *self*. It should be
237 * populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN().
239 #define FIXTURE(fixture_name) \
240 FIXTURE_VARIANT(fixture_name); \
241 static struct __fixture_metadata _##fixture_name##_fixture_object = \
242 { .name = #fixture_name, }; \
243 static void __attribute__((constructor)) \
244 _register_##fixture_name##_data(void) \
246 __register_fixture(&_##fixture_name##_fixture_object); \
248 FIXTURE_DATA(fixture_name)
251 * FIXTURE_SETUP() - Prepares the setup function for the fixture.
252 * *_metadata* is included so that EXPECT_* and ASSERT_* work correctly.
254 * @fixture_name: fixture name
258 * FIXTURE_SETUP(fixture_name) { implementation }
260 * Populates the required "setup" function for a fixture. An instance of the
261 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
264 * ASSERT_* are valid for use in this context and will prempt the execution
265 * of any dependent fixture tests.
267 * A bare "return;" statement may be used to return early.
269 #define FIXTURE_SETUP(fixture_name) \
270 void fixture_name##_setup( \
271 struct __test_metadata __attribute__((unused)) *_metadata, \
272 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
273 const FIXTURE_VARIANT(fixture_name) \
274 __attribute__((unused)) *variant)
278 * *_metadata* is included so that EXPECT_* and ASSERT_* work correctly.
280 * @fixture_name: fixture name
284 * FIXTURE_TEARDOWN(fixture_name) { implementation }
286 * Populates the required "teardown" function for a fixture. An instance of the
287 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
288 * implementation to clean up.
290 * A bare "return;" statement may be used to return early.
292 #define FIXTURE_TEARDOWN(fixture_name) \
293 void fixture_name##_teardown( \
294 struct __test_metadata __attribute__((unused)) *_metadata, \
295 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
296 const FIXTURE_VARIANT(fixture_name) \
297 __attribute__((unused)) *variant)
300 * FIXTURE_VARIANT() - Optionally called once per fixture
301 * to declare fixture variant
303 * @fixture_name: fixture name
307 * FIXTURE_VARIANT(fixture_name) {
312 * Defines type of constant parameters provided to FIXTURE_SETUP(), TEST_F() and
313 * FIXTURE_TEARDOWN as *variant*. Variants allow the same tests to be run with
314 * different arguments.
316 #define FIXTURE_VARIANT(fixture_name) struct _fixture_variant_##fixture_name
319 * FIXTURE_VARIANT_ADD() - Called once per fixture
320 * variant to setup and register the data
322 * @fixture_name: fixture name
323 * @variant_name: name of the parameter set
327 * FIXTURE_VARIANT_ADD(fixture_name, variant_name) {
332 * Defines a variant of the test fixture, provided to FIXTURE_SETUP() and
333 * TEST_F() as *variant*. Tests of each fixture will be run once for each
336 #define FIXTURE_VARIANT_ADD(fixture_name, variant_name) \
337 extern FIXTURE_VARIANT(fixture_name) \
338 _##fixture_name##_##variant_name##_variant; \
339 static struct __fixture_variant_metadata \
340 _##fixture_name##_##variant_name##_object = \
341 { .name = #variant_name, \
342 .data = &_##fixture_name##_##variant_name##_variant}; \
343 static void __attribute__((constructor)) \
344 _register_##fixture_name##_##variant_name(void) \
346 __register_fixture_variant(&_##fixture_name##_fixture_object, \
347 &_##fixture_name##_##variant_name##_object); \
349 FIXTURE_VARIANT(fixture_name) \
350 _##fixture_name##_##variant_name##_variant =
353 * TEST_F() - Emits test registration and helpers for
354 * fixture-based test cases
356 * @fixture_name: fixture name
357 * @test_name: test name
361 * TEST_F(fixture, name) { implementation }
363 * Defines a test that depends on a fixture (e.g., is part of a test case).
364 * Very similar to TEST() except that *self* is the setup instance of fixture's
365 * datatype exposed for use by the implementation.
367 #define TEST_F(fixture_name, test_name) \
368 __TEST_F_IMPL(fixture_name, test_name, -1, TEST_TIMEOUT_DEFAULT)
370 #define TEST_F_SIGNAL(fixture_name, test_name, signal) \
371 __TEST_F_IMPL(fixture_name, test_name, signal, TEST_TIMEOUT_DEFAULT)
373 #define TEST_F_TIMEOUT(fixture_name, test_name, timeout) \
374 __TEST_F_IMPL(fixture_name, test_name, -1, timeout)
376 #define __TEST_F_IMPL(fixture_name, test_name, signal, tmout) \
377 static void fixture_name##_##test_name( \
378 struct __test_metadata *_metadata, \
379 FIXTURE_DATA(fixture_name) *self, \
380 const FIXTURE_VARIANT(fixture_name) *variant); \
381 static inline void wrapper_##fixture_name##_##test_name( \
382 struct __test_metadata *_metadata, \
383 struct __fixture_variant_metadata *variant) \
385 /* fixture data is alloced, setup, and torn down per call. */ \
386 FIXTURE_DATA(fixture_name) self; \
387 memset(&self, 0, sizeof(FIXTURE_DATA(fixture_name))); \
388 if (setjmp(_metadata->env) == 0) { \
389 fixture_name##_setup(_metadata, &self, variant->data); \
390 /* Let setup failure terminate early. */ \
391 if (!_metadata->passed) \
393 _metadata->setup_completed = true; \
394 fixture_name##_##test_name(_metadata, &self, variant->data); \
396 if (_metadata->setup_completed) \
397 fixture_name##_teardown(_metadata, &self, variant->data); \
398 __test_check_assert(_metadata); \
400 static struct __test_metadata \
401 _##fixture_name##_##test_name##_object = { \
402 .name = #test_name, \
403 .fn = &wrapper_##fixture_name##_##test_name, \
404 .fixture = &_##fixture_name##_fixture_object, \
408 static void __attribute__((constructor)) \
409 _register_##fixture_name##_##test_name(void) \
411 __register_test(&_##fixture_name##_##test_name##_object); \
413 static void fixture_name##_##test_name( \
414 struct __test_metadata __attribute__((unused)) *_metadata, \
415 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
416 const FIXTURE_VARIANT(fixture_name) \
417 __attribute__((unused)) *variant)
420 * TEST_HARNESS_MAIN - Simple wrapper to run the test harness
426 * Use once to append a main() to the test file.
428 #define TEST_HARNESS_MAIN \
429 static void __attribute__((constructor)) \
430 __constructor_order_last(void) \
432 if (!__constructor_order) \
433 __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
435 int main(int argc, char **argv) { \
436 return test_harness_run(argc, argv); \
442 * Operators for use in TEST() and TEST_F().
443 * ASSERT_* calls will stop test execution immediately.
444 * EXPECT_* calls will emit a failure warning, note it, and continue.
450 * @expected: expected value
451 * @seen: measured value
453 * ASSERT_EQ(expected, measured): expected == measured
455 #define ASSERT_EQ(expected, seen) \
456 __EXPECT(expected, #expected, seen, #seen, ==, 1)
461 * @expected: expected value
462 * @seen: measured value
464 * ASSERT_NE(expected, measured): expected != measured
466 #define ASSERT_NE(expected, seen) \
467 __EXPECT(expected, #expected, seen, #seen, !=, 1)
472 * @expected: expected value
473 * @seen: measured value
475 * ASSERT_LT(expected, measured): expected < measured
477 #define ASSERT_LT(expected, seen) \
478 __EXPECT(expected, #expected, seen, #seen, <, 1)
483 * @expected: expected value
484 * @seen: measured value
486 * ASSERT_LE(expected, measured): expected <= measured
488 #define ASSERT_LE(expected, seen) \
489 __EXPECT(expected, #expected, seen, #seen, <=, 1)
494 * @expected: expected value
495 * @seen: measured value
497 * ASSERT_GT(expected, measured): expected > measured
499 #define ASSERT_GT(expected, seen) \
500 __EXPECT(expected, #expected, seen, #seen, >, 1)
505 * @expected: expected value
506 * @seen: measured value
508 * ASSERT_GE(expected, measured): expected >= measured
510 #define ASSERT_GE(expected, seen) \
511 __EXPECT(expected, #expected, seen, #seen, >=, 1)
516 * @seen: measured value
518 * ASSERT_NULL(measured): NULL == measured
520 #define ASSERT_NULL(seen) \
521 __EXPECT(NULL, "NULL", seen, #seen, ==, 1)
526 * @seen: measured value
528 * ASSERT_TRUE(measured): measured != 0
530 #define ASSERT_TRUE(seen) \
531 __EXPECT(0, "0", seen, #seen, !=, 1)
536 * @seen: measured value
538 * ASSERT_FALSE(measured): measured == 0
540 #define ASSERT_FALSE(seen) \
541 __EXPECT(0, "0", seen, #seen, ==, 1)
546 * @expected: expected value
547 * @seen: measured value
549 * ASSERT_STREQ(expected, measured): !strcmp(expected, measured)
551 #define ASSERT_STREQ(expected, seen) \
552 __EXPECT_STR(expected, seen, ==, 1)
557 * @expected: expected value
558 * @seen: measured value
560 * ASSERT_STRNE(expected, measured): strcmp(expected, measured)
562 #define ASSERT_STRNE(expected, seen) \
563 __EXPECT_STR(expected, seen, !=, 1)
568 * @expected: expected value
569 * @seen: measured value
571 * EXPECT_EQ(expected, measured): expected == measured
573 #define EXPECT_EQ(expected, seen) \
574 __EXPECT(expected, #expected, seen, #seen, ==, 0)
579 * @expected: expected value
580 * @seen: measured value
582 * EXPECT_NE(expected, measured): expected != measured
584 #define EXPECT_NE(expected, seen) \
585 __EXPECT(expected, #expected, seen, #seen, !=, 0)
590 * @expected: expected value
591 * @seen: measured value
593 * EXPECT_LT(expected, measured): expected < measured
595 #define EXPECT_LT(expected, seen) \
596 __EXPECT(expected, #expected, seen, #seen, <, 0)
601 * @expected: expected value
602 * @seen: measured value
604 * EXPECT_LE(expected, measured): expected <= measured
606 #define EXPECT_LE(expected, seen) \
607 __EXPECT(expected, #expected, seen, #seen, <=, 0)
612 * @expected: expected value
613 * @seen: measured value
615 * EXPECT_GT(expected, measured): expected > measured
617 #define EXPECT_GT(expected, seen) \
618 __EXPECT(expected, #expected, seen, #seen, >, 0)
623 * @expected: expected value
624 * @seen: measured value
626 * EXPECT_GE(expected, measured): expected >= measured
628 #define EXPECT_GE(expected, seen) \
629 __EXPECT(expected, #expected, seen, #seen, >=, 0)
634 * @seen: measured value
636 * EXPECT_NULL(measured): NULL == measured
638 #define EXPECT_NULL(seen) \
639 __EXPECT(NULL, "NULL", seen, #seen, ==, 0)
644 * @seen: measured value
646 * EXPECT_TRUE(measured): 0 != measured
648 #define EXPECT_TRUE(seen) \
649 __EXPECT(0, "0", seen, #seen, !=, 0)
654 * @seen: measured value
656 * EXPECT_FALSE(measured): 0 == measured
658 #define EXPECT_FALSE(seen) \
659 __EXPECT(0, "0", seen, #seen, ==, 0)
664 * @expected: expected value
665 * @seen: measured value
667 * EXPECT_STREQ(expected, measured): !strcmp(expected, measured)
669 #define EXPECT_STREQ(expected, seen) \
670 __EXPECT_STR(expected, seen, ==, 0)
675 * @expected: expected value
676 * @seen: measured value
678 * EXPECT_STRNE(expected, measured): strcmp(expected, measured)
680 #define EXPECT_STRNE(expected, seen) \
681 __EXPECT_STR(expected, seen, !=, 0)
684 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
687 /* Support an optional handler after and ASSERT_* or EXPECT_*. The approach is
688 * not thread-safe, but it should be fine in most sane test scenarios.
690 * Using __bail(), which optionally abort()s, is the easiest way to early
691 * return while still providing an optional block to the API consumer.
693 #define OPTIONAL_HANDLER(_assert) \
694 for (; _metadata->trigger; _metadata->trigger = \
695 __bail(_assert, _metadata))
697 #define __INC_STEP(_metadata) \
698 /* Keep "step" below 255 (which is used for "SKIP" reporting). */ \
699 if (_metadata->passed && _metadata->step < 253) \
702 #define is_signed_type(var) (!!(((__typeof__(var))(-1)) < (__typeof__(var))1))
704 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \
705 /* Avoid multiple evaluation of the cases */ \
706 __typeof__(_expected) __exp = (_expected); \
707 __typeof__(_seen) __seen = (_seen); \
708 if (_assert) __INC_STEP(_metadata); \
709 if (!(__exp _t __seen)) { \
710 /* Report with actual signedness to avoid weird output. */ \
711 switch (is_signed_type(__exp) * 2 + is_signed_type(__seen)) { \
713 unsigned long long __exp_print = (uintptr_t)__exp; \
714 unsigned long long __seen_print = (uintptr_t)__seen; \
715 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
716 _expected_str, __exp_print, #_t, \
717 _seen_str, __seen_print); \
721 unsigned long long __exp_print = (uintptr_t)__exp; \
722 long long __seen_print = (intptr_t)__seen; \
723 __TH_LOG("Expected %s (%llu) %s %s (%lld)", \
724 _expected_str, __exp_print, #_t, \
725 _seen_str, __seen_print); \
729 long long __exp_print = (intptr_t)__exp; \
730 unsigned long long __seen_print = (uintptr_t)__seen; \
731 __TH_LOG("Expected %s (%lld) %s %s (%llu)", \
732 _expected_str, __exp_print, #_t, \
733 _seen_str, __seen_print); \
737 long long __exp_print = (intptr_t)__exp; \
738 long long __seen_print = (intptr_t)__seen; \
739 __TH_LOG("Expected %s (%lld) %s %s (%lld)", \
740 _expected_str, __exp_print, #_t, \
741 _seen_str, __seen_print); \
745 _metadata->passed = 0; \
746 /* Ensure the optional handler is triggered */ \
747 _metadata->trigger = 1; \
749 } while (0); OPTIONAL_HANDLER(_assert)
751 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
752 const char *__exp = (_expected); \
753 const char *__seen = (_seen); \
754 if (_assert) __INC_STEP(_metadata); \
755 if (!(strcmp(__exp, __seen) _t 0)) { \
756 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
757 _metadata->passed = 0; \
758 _metadata->trigger = 1; \
760 } while (0); OPTIONAL_HANDLER(_assert)
763 #define __LIST_APPEND(head, item) \
765 /* Circular linked list where only prev is circular. */ \
766 if (head == NULL) { \
772 if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \
774 item->prev = head->prev; \
775 item->prev->next = item; \
779 item->next->prev = item; \
785 struct __test_results {
786 char reason[1024]; /* Reason for test result */
789 struct __test_metadata;
790 struct __fixture_variant_metadata;
792 /* Contains all the information about a fixture. */
793 struct __fixture_metadata {
795 struct __test_metadata *tests;
796 struct __fixture_variant_metadata *variant;
797 struct __fixture_metadata *prev, *next;
798 } _fixture_global __attribute__((unused)) = {
800 .prev = &_fixture_global,
803 static struct __fixture_metadata *__fixture_list = &_fixture_global;
804 static int __constructor_order;
806 #define _CONSTRUCTOR_ORDER_FORWARD 1
807 #define _CONSTRUCTOR_ORDER_BACKWARD -1
809 static inline void __register_fixture(struct __fixture_metadata *f)
811 __LIST_APPEND(__fixture_list, f);
814 struct __fixture_variant_metadata {
817 struct __fixture_variant_metadata *prev, *next;
821 __register_fixture_variant(struct __fixture_metadata *f,
822 struct __fixture_variant_metadata *variant)
824 __LIST_APPEND(f->variant, variant);
827 /* Contains all the information for test execution and status checking. */
828 struct __test_metadata {
830 void (*fn)(struct __test_metadata *,
831 struct __fixture_variant_metadata *);
832 pid_t pid; /* pid of test when being run */
833 struct __fixture_metadata *fixture;
836 int skip; /* did SKIP get used? */
837 int trigger; /* extra handler after the evaluation */
838 int timeout; /* seconds to wait for test timeout */
839 bool timed_out; /* did this test timeout instead of exiting? */
841 bool no_print; /* manual trigger when TH_LOG_STREAM is not available */
842 bool aborted; /* stopped test due to failed ASSERT */
843 bool setup_completed; /* did setup finish? */
844 jmp_buf env; /* for exiting out of test early */
845 struct __test_results *results;
846 struct __test_metadata *prev, *next;
850 * Since constructors are called in reverse order, reverse the test
851 * list so tests are run in source declaration order.
852 * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
853 * However, it seems not all toolchains do this correctly, so use
854 * __constructor_order to detect which direction is called first
855 * and adjust list building logic to get things running in the right
858 static inline void __register_test(struct __test_metadata *t)
860 __LIST_APPEND(t->fixture->tests, t);
863 static inline int __bail(int for_realz, struct __test_metadata *t)
865 /* if this is ASSERT, return immediately. */
870 /* otherwise, end the for loop and continue. */
874 static inline void __test_check_assert(struct __test_metadata *t)
883 struct __test_metadata *__active_test;
884 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext)
886 struct __test_metadata *t = __active_test;
888 /* Sanity check handler execution environment. */
890 fprintf(TH_LOG_STREAM,
891 "# no active test in SIGALRM handler!?\n");
894 if (sig != SIGALRM || sig != info->si_signo) {
895 fprintf(TH_LOG_STREAM,
896 "# %s: SIGALRM handler caught signal %d!?\n",
897 t->name, sig != SIGALRM ? sig : info->si_signo);
902 // signal process group
903 kill(-(t->pid), SIGKILL);
906 void __wait_for_test(struct __test_metadata *t)
908 struct sigaction action = {
909 .sa_sigaction = __timeout_handler,
910 .sa_flags = SA_SIGINFO,
912 struct sigaction saved_action;
915 if (sigaction(SIGALRM, &action, &saved_action)) {
917 fprintf(TH_LOG_STREAM,
918 "# %s: unable to install SIGALRM handler\n",
923 t->timed_out = false;
925 waitpid(t->pid, &status, 0);
927 if (sigaction(SIGALRM, &saved_action, NULL)) {
929 fprintf(TH_LOG_STREAM,
930 "# %s: unable to uninstall SIGALRM handler\n",
934 __active_test = NULL;
938 fprintf(TH_LOG_STREAM,
939 "# %s: Test terminated by timeout\n", t->name);
940 } else if (WIFEXITED(status)) {
941 if (t->termsig != -1) {
943 fprintf(TH_LOG_STREAM,
944 "# %s: Test exited normally instead of by signal (code: %d)\n",
946 WEXITSTATUS(status));
948 switch (WEXITSTATUS(status)) {
958 /* Other failure, assume step report. */
961 fprintf(TH_LOG_STREAM,
962 "# %s: Test failed at step #%d\n",
964 WEXITSTATUS(status));
967 } else if (WIFSIGNALED(status)) {
969 if (WTERMSIG(status) == SIGABRT) {
970 fprintf(TH_LOG_STREAM,
971 "# %s: Test terminated by assertion\n",
973 } else if (WTERMSIG(status) == t->termsig) {
976 fprintf(TH_LOG_STREAM,
977 "# %s: Test terminated unexpectedly by signal %d\n",
982 fprintf(TH_LOG_STREAM,
983 "# %s: Test ended in some other way [%u]\n",
989 static void test_harness_list_tests(void)
991 struct __fixture_variant_metadata *v;
992 struct __fixture_metadata *f;
993 struct __test_metadata *t;
995 for (f = __fixture_list; f; f = f->next) {
999 if (f == __fixture_list)
1000 fprintf(stderr, "%-20s %-25s %s\n",
1001 "# FIXTURE", "VARIANT", "TEST");
1003 fprintf(stderr, "--------------------------------------------------------------------------------\n");
1006 fprintf(stderr, "%-20s %-25s %s\n",
1007 t == f->tests ? f->name : "",
1011 v = v ? v->next : NULL;
1012 t = t ? t->next : NULL;
1017 static int test_harness_argv_check(int argc, char **argv)
1021 while ((opt = getopt(argc, argv, "hlF:f:V:v:t:T:r:")) != -1) {
1032 test_harness_list_tests();
1037 "Usage: %s [-h|-l] [-t|-T|-v|-V|-f|-F|-r name]\n"
1039 "\t-l list all tests\n"
1041 "\t-t name include test\n"
1042 "\t-T name exclude test\n"
1043 "\t-v name include variant\n"
1044 "\t-V name exclude variant\n"
1045 "\t-f name include fixture\n"
1046 "\t-F name exclude fixture\n"
1047 "\t-r name run specified test\n"
1049 "Test filter options can be specified "
1050 "multiple times. The filtering stops\n"
1051 "at the first match. For example to "
1052 "include all tests from variant 'bla'\n"
1053 "but not test 'foo' specify '-T foo -v bla'.\n"
1055 return opt == 'h' ? KSFT_SKIP : KSFT_FAIL;
1062 static bool test_enabled(int argc, char **argv,
1063 struct __fixture_metadata *f,
1064 struct __fixture_variant_metadata *v,
1065 struct __test_metadata *t)
1067 unsigned int flen = 0, vlen = 0, tlen = 0;
1068 bool has_positive = false;
1072 while ((opt = getopt(argc, argv, "F:f:V:v:t:T:r:")) != -1) {
1073 has_positive |= islower(opt);
1075 switch (tolower(opt)) {
1077 if (!strcmp(t->name, optarg))
1078 return islower(opt);
1081 if (!strcmp(f->name, optarg))
1082 return islower(opt);
1085 if (!strcmp(v->name, optarg))
1086 return islower(opt);
1090 flen = strlen(f->name);
1091 vlen = strlen(v->name);
1092 tlen = strlen(t->name);
1094 if (strlen(optarg) == flen + 1 + vlen + !!vlen + tlen &&
1095 !strncmp(f->name, &optarg[0], flen) &&
1096 !strncmp(v->name, &optarg[flen + 1], vlen) &&
1097 !strncmp(t->name, &optarg[flen + 1 + vlen + !!vlen], tlen))
1104 * If there are no positive tests then we assume user just wants
1105 * exclusions and everything else is a pass.
1107 return !has_positive;
1110 void __run_test(struct __fixture_metadata *f,
1111 struct __fixture_variant_metadata *variant,
1112 struct __test_metadata *t)
1114 /* reset test struct */
1120 memset(t->results->reason, 0, sizeof(t->results->reason));
1122 ksft_print_msg(" RUN %s%s%s.%s ...\n",
1123 f->name, variant->name[0] ? "." : "", variant->name, t->name);
1125 /* Make sure output buffers are flushed before fork */
1131 ksft_print_msg("ERROR SPAWNING TEST CHILD\n");
1133 } else if (t->pid == 0) {
1138 /* Pass is exit 0 */
1141 /* Something else happened, report the step. */
1146 ksft_print_msg(" %4s %s%s%s.%s\n", t->passed ? "OK" : "FAIL",
1147 f->name, variant->name[0] ? "." : "", variant->name, t->name);
1150 ksft_test_result_skip("%s\n", t->results->reason[0] ?
1151 t->results->reason : "unknown");
1153 ksft_test_result(t->passed, "%s%s%s.%s\n",
1154 f->name, variant->name[0] ? "." : "", variant->name, t->name);
1157 static int test_harness_run(int argc, char **argv)
1159 struct __fixture_variant_metadata no_variant = { .name = "", };
1160 struct __fixture_variant_metadata *v;
1161 struct __fixture_metadata *f;
1162 struct __test_results *results;
1163 struct __test_metadata *t;
1165 unsigned int case_count = 0, test_count = 0;
1166 unsigned int count = 0;
1167 unsigned int pass_count = 0;
1169 ret = test_harness_argv_check(argc, argv);
1170 if (ret != KSFT_PASS)
1173 for (f = __fixture_list; f; f = f->next) {
1174 for (v = f->variant ?: &no_variant; v; v = v->next) {
1175 unsigned int old_tests = test_count;
1177 for (t = f->tests; t; t = t->next)
1178 if (test_enabled(argc, argv, f, v, t))
1181 if (old_tests != test_count)
1186 results = mmap(NULL, sizeof(*results), PROT_READ | PROT_WRITE,
1187 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1189 ksft_print_header();
1190 ksft_set_plan(test_count);
1191 ksft_print_msg("Starting %u tests from %u test cases.\n",
1192 test_count, case_count);
1193 for (f = __fixture_list; f; f = f->next) {
1194 for (v = f->variant ?: &no_variant; v; v = v->next) {
1195 for (t = f->tests; t; t = t->next) {
1196 if (!test_enabled(argc, argv, f, v, t))
1199 t->results = results;
1200 __run_test(f, v, t);
1209 munmap(results, sizeof(*results));
1211 ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED",
1213 ksft_exit(ret == 0);
1219 static void __attribute__((constructor)) __constructor_order_first(void)
1221 if (!__constructor_order)
1222 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
1225 #endif /* __KSELFTEST_HARNESS_H */