171e70aead9c029a76f2ff7f338efe855f0578ee
[platform/kernel/linux-starfive.git] / tools / testing / selftests / kselftest_harness.h
1 /*
2  * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3  * Use of this source code is governed by the GPLv2 license.
4  *
5  * kselftest_harness.h: simple C unit test helper.
6  *
7  * Usage:
8  *   #include "../kselftest_harness.h"
9  *   TEST(standalone_test) {
10  *     do_some_stuff;
11  *     EXPECT_GT(10, stuff) {
12  *        stuff_state_t state;
13  *        enumerate_stuff_state(&state);
14  *        TH_LOG("expectation failed with state: %s", state.msg);
15  *     }
16  *     more_stuff;
17  *     ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!");
18  *     last_stuff;
19  *     EXPECT_EQ(0, last_stuff);
20  *   }
21  *
22  *   FIXTURE(my_fixture) {
23  *     mytype_t *data;
24  *     int awesomeness_level;
25  *   };
26  *   FIXTURE_SETUP(my_fixture) {
27  *     self->data = mytype_new();
28  *     ASSERT_NE(NULL, self->data);
29  *   }
30  *   FIXTURE_TEARDOWN(my_fixture) {
31  *     mytype_free(self->data);
32  *   }
33  *   TEST_F(my_fixture, data_is_good) {
34  *     EXPECT_EQ(1, is_my_data_good(self->data));
35  *   }
36  *
37  *   TEST_HARNESS_MAIN
38  *
39  * API inspired by code.google.com/p/googletest
40  */
41
42 #ifndef __KSELFTEST_HARNESS_H
43 #define __KSELFTEST_HARNESS_H
44
45 #define _GNU_SOURCE
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/types.h>
51 #include <sys/wait.h>
52 #include <unistd.h>
53
54 /* All exported functionality should be declared through this macro. */
55 #define TEST_API(x) _##x
56
57 /*
58  * Exported APIs
59  */
60
61 /* TEST(name) { implementation }
62  * Defines a test by name.
63  * Names must be unique and tests must not be run in parallel.  The
64  * implementation containing block is a function and scoping should be treated
65  * as such.  Returning early may be performed with a bare "return;" statement.
66  *
67  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
68  */
69 #define TEST TEST_API(TEST)
70
71 /* TEST_SIGNAL(name, signal) { implementation }
72  * Defines a test by name and the expected term signal.
73  * Names must be unique and tests must not be run in parallel.  The
74  * implementation containing block is a function and scoping should be treated
75  * as such.  Returning early may be performed with a bare "return;" statement.
76  *
77  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
78  */
79 #define TEST_SIGNAL TEST_API(TEST_SIGNAL)
80
81 /* FIXTURE(datatype name) {
82  *   type property1;
83  *   ...
84  * };
85  * Defines the data provided to TEST_F()-defined tests as |self|.  It should be
86  * populated and cleaned up using FIXTURE_SETUP and FIXTURE_TEARDOWN.
87  */
88 #define FIXTURE TEST_API(FIXTURE)
89
90 /* FIXTURE_DATA(datatype name)
91  * This call may be used when the type of the fixture data
92  * is needed.  In general, this should not be needed unless
93  * the |self| is being passed to a helper directly.
94  */
95 #define FIXTURE_DATA TEST_API(FIXTURE_DATA)
96
97 /* FIXTURE_SETUP(fixture name) { implementation }
98  * Populates the required "setup" function for a fixture.  An instance of the
99  * datatype defined with _FIXTURE_DATA will be exposed as |self| for the
100  * implementation.
101  *
102  * ASSERT_* are valid for use in this context and will prempt the execution
103  * of any dependent fixture tests.
104  *
105  * A bare "return;" statement may be used to return early.
106  */
107 #define FIXTURE_SETUP TEST_API(FIXTURE_SETUP)
108
109 /* FIXTURE_TEARDOWN(fixture name) { implementation }
110  * Populates the required "teardown" function for a fixture.  An instance of the
111  * datatype defined with _FIXTURE_DATA will be exposed as |self| for the
112  * implementation to clean up.
113  *
114  * A bare "return;" statement may be used to return early.
115  */
116 #define FIXTURE_TEARDOWN TEST_API(FIXTURE_TEARDOWN)
117
118 /* TEST_F(fixture, name) { implementation }
119  * Defines a test that depends on a fixture (e.g., is part of a test case).
120  * Very similar to TEST() except that |self| is the setup instance of fixture's
121  * datatype exposed for use by the implementation.
122  */
123 #define TEST_F TEST_API(TEST_F)
124
125 #define TEST_F_SIGNAL TEST_API(TEST_F_SIGNAL)
126
127 /* Use once to append a main() to the test file. E.g.,
128  *   TEST_HARNESS_MAIN
129  */
130 #define TEST_HARNESS_MAIN TEST_API(TEST_HARNESS_MAIN)
131
132 /*
133  * Operators for use in TEST and TEST_F.
134  * ASSERT_* calls will stop test execution immediately.
135  * EXPECT_* calls will emit a failure warning, note it, and continue.
136  */
137
138 /* ASSERT_EQ(expected, measured): expected == measured */
139 #define ASSERT_EQ TEST_API(ASSERT_EQ)
140 /* ASSERT_NE(expected, measured): expected != measured */
141 #define ASSERT_NE TEST_API(ASSERT_NE)
142 /* ASSERT_LT(expected, measured): expected < measured */
143 #define ASSERT_LT TEST_API(ASSERT_LT)
144 /* ASSERT_LE(expected, measured): expected <= measured */
145 #define ASSERT_LE TEST_API(ASSERT_LE)
146 /* ASSERT_GT(expected, measured): expected > measured */
147 #define ASSERT_GT TEST_API(ASSERT_GT)
148 /* ASSERT_GE(expected, measured): expected >= measured */
149 #define ASSERT_GE TEST_API(ASSERT_GE)
150 /* ASSERT_NULL(measured): NULL == measured */
151 #define ASSERT_NULL TEST_API(ASSERT_NULL)
152 /* ASSERT_TRUE(measured): measured != 0 */
153 #define ASSERT_TRUE TEST_API(ASSERT_TRUE)
154 /* ASSERT_FALSE(measured): measured == 0 */
155 #define ASSERT_FALSE TEST_API(ASSERT_FALSE)
156 /* ASSERT_STREQ(expected, measured): !strcmp(expected, measured) */
157 #define ASSERT_STREQ TEST_API(ASSERT_STREQ)
158 /* ASSERT_STRNE(expected, measured): strcmp(expected, measured) */
159 #define ASSERT_STRNE TEST_API(ASSERT_STRNE)
160 /* EXPECT_EQ(expected, measured): expected == measured */
161 #define EXPECT_EQ TEST_API(EXPECT_EQ)
162 /* EXPECT_NE(expected, measured): expected != measured */
163 #define EXPECT_NE TEST_API(EXPECT_NE)
164 /* EXPECT_LT(expected, measured): expected < measured */
165 #define EXPECT_LT TEST_API(EXPECT_LT)
166 /* EXPECT_LE(expected, measured): expected <= measured */
167 #define EXPECT_LE TEST_API(EXPECT_LE)
168 /* EXPECT_GT(expected, measured): expected > measured */
169 #define EXPECT_GT TEST_API(EXPECT_GT)
170 /* EXPECT_GE(expected, measured): expected >= measured */
171 #define EXPECT_GE TEST_API(EXPECT_GE)
172 /* EXPECT_NULL(measured): NULL == measured */
173 #define EXPECT_NULL TEST_API(EXPECT_NULL)
174 /* EXPECT_TRUE(measured): 0 != measured */
175 #define EXPECT_TRUE TEST_API(EXPECT_TRUE)
176 /* EXPECT_FALSE(measured): 0 == measured */
177 #define EXPECT_FALSE TEST_API(EXPECT_FALSE)
178 /* EXPECT_STREQ(expected, measured): !strcmp(expected, measured) */
179 #define EXPECT_STREQ TEST_API(EXPECT_STREQ)
180 /* EXPECT_STRNE(expected, measured): strcmp(expected, measured) */
181 #define EXPECT_STRNE TEST_API(EXPECT_STRNE)
182
183 /* TH_LOG(format, ...)
184  * Optional debug logging function available for use in tests.
185  * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
186  * E.g., #define TH_LOG_ENABLED 1
187  * If no definition is provided, logging is enabled by default.
188  */
189 #define TH_LOG  TEST_API(TH_LOG)
190
191 /*
192  * Internal implementation.
193  *
194  */
195
196 /* Utilities exposed to the test definitions */
197 #ifndef TH_LOG_STREAM
198 #  define TH_LOG_STREAM stderr
199 #endif
200
201 #ifndef TH_LOG_ENABLED
202 #  define TH_LOG_ENABLED 1
203 #endif
204
205 #define _TH_LOG(fmt, ...) do { \
206         if (TH_LOG_ENABLED) \
207                 __TH_LOG(fmt, ##__VA_ARGS__); \
208 } while (0)
209
210 /* Unconditional logger for internal use. */
211 #define __TH_LOG(fmt, ...) \
212                 fprintf(TH_LOG_STREAM, "%s:%d:%s:" fmt "\n", \
213                         __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
214
215 /* Defines the test function and creates the registration stub. */
216 #define _TEST(test_name) __TEST_IMPL(test_name, -1)
217
218 #define _TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
219
220 #define __TEST_IMPL(test_name, _signal) \
221         static void test_name(struct __test_metadata *_metadata); \
222         static struct __test_metadata _##test_name##_object = \
223                 { name: "global." #test_name, \
224                   fn: &test_name, termsig: _signal }; \
225         static void __attribute__((constructor)) _register_##test_name(void) \
226         { \
227                 __register_test(&_##test_name##_object); \
228         } \
229         static void test_name( \
230                 struct __test_metadata __attribute__((unused)) *_metadata)
231
232 /* Wraps the struct name so we have one less argument to pass around. */
233 #define _FIXTURE_DATA(fixture_name) struct _test_data_##fixture_name
234
235 /* Called once per fixture to setup the data and register. */
236 #define _FIXTURE(fixture_name) \
237         static void __attribute__((constructor)) \
238         _register_##fixture_name##_data(void) \
239         { \
240                 __fixture_count++; \
241         } \
242         _FIXTURE_DATA(fixture_name)
243
244 /* Prepares the setup function for the fixture.  |_metadata| is included
245  * so that ASSERT_* work as a convenience.
246  */
247 #define _FIXTURE_SETUP(fixture_name) \
248         void fixture_name##_setup( \
249                 struct __test_metadata __attribute__((unused)) *_metadata, \
250                 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
251 #define _FIXTURE_TEARDOWN(fixture_name) \
252         void fixture_name##_teardown( \
253                 struct __test_metadata __attribute__((unused)) *_metadata, \
254                 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
255
256 /* Emits test registration and helpers for fixture-based test
257  * cases.
258  * TODO(wad) register fixtures on dedicated test lists.
259  */
260 #define _TEST_F(fixture_name, test_name) \
261         __TEST_F_IMPL(fixture_name, test_name, -1)
262
263 #define _TEST_F_SIGNAL(fixture_name, test_name, signal) \
264         __TEST_F_IMPL(fixture_name, test_name, signal)
265
266 #define __TEST_F_IMPL(fixture_name, test_name, signal) \
267         static void fixture_name##_##test_name( \
268                 struct __test_metadata *_metadata, \
269                 _FIXTURE_DATA(fixture_name) *self); \
270         static inline void wrapper_##fixture_name##_##test_name( \
271                 struct __test_metadata *_metadata) \
272         { \
273                 /* fixture data is alloced, setup, and torn down per call. */ \
274                 _FIXTURE_DATA(fixture_name) self; \
275                 memset(&self, 0, sizeof(_FIXTURE_DATA(fixture_name))); \
276                 fixture_name##_setup(_metadata, &self); \
277                 /* Let setup failure terminate early. */ \
278                 if (!_metadata->passed) \
279                         return; \
280                 fixture_name##_##test_name(_metadata, &self); \
281                 fixture_name##_teardown(_metadata, &self); \
282         } \
283         static struct __test_metadata \
284                       _##fixture_name##_##test_name##_object = { \
285                 name: #fixture_name "." #test_name, \
286                 fn: &wrapper_##fixture_name##_##test_name, \
287                 termsig: signal, \
288          }; \
289         static void __attribute__((constructor)) \
290                         _register_##fixture_name##_##test_name(void) \
291         { \
292                 __register_test(&_##fixture_name##_##test_name##_object); \
293         } \
294         static void fixture_name##_##test_name( \
295                 struct __test_metadata __attribute__((unused)) *_metadata, \
296                 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
297
298 /* Exports a simple wrapper to run the test harness. */
299 #define _TEST_HARNESS_MAIN \
300         static void __attribute__((constructor)) \
301         __constructor_order_last(void) \
302         { \
303                 if (!__constructor_order) \
304                         __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
305         } \
306         int main(int argc, char **argv) { \
307                 return test_harness_run(argc, argv); \
308         }
309
310 #define _ASSERT_EQ(_expected, _seen) \
311         __EXPECT(_expected, _seen, ==, 1)
312 #define _ASSERT_NE(_expected, _seen) \
313         __EXPECT(_expected, _seen, !=, 1)
314 #define _ASSERT_LT(_expected, _seen) \
315         __EXPECT(_expected, _seen, <, 1)
316 #define _ASSERT_LE(_expected, _seen) \
317         __EXPECT(_expected, _seen, <=, 1)
318 #define _ASSERT_GT(_expected, _seen) \
319         __EXPECT(_expected, _seen, >, 1)
320 #define _ASSERT_GE(_expected, _seen) \
321         __EXPECT(_expected, _seen, >=, 1)
322 #define _ASSERT_NULL(_seen) \
323         __EXPECT(NULL, _seen, ==, 1)
324
325 #define _ASSERT_TRUE(_seen) \
326         _ASSERT_NE(0, _seen)
327 #define _ASSERT_FALSE(_seen) \
328         _ASSERT_EQ(0, _seen)
329 #define _ASSERT_STREQ(_expected, _seen) \
330         __EXPECT_STR(_expected, _seen, ==, 1)
331 #define _ASSERT_STRNE(_expected, _seen) \
332         __EXPECT_STR(_expected, _seen, !=, 1)
333
334 #define _EXPECT_EQ(_expected, _seen) \
335         __EXPECT(_expected, _seen, ==, 0)
336 #define _EXPECT_NE(_expected, _seen) \
337         __EXPECT(_expected, _seen, !=, 0)
338 #define _EXPECT_LT(_expected, _seen) \
339         __EXPECT(_expected, _seen, <, 0)
340 #define _EXPECT_LE(_expected, _seen) \
341         __EXPECT(_expected, _seen, <=, 0)
342 #define _EXPECT_GT(_expected, _seen) \
343         __EXPECT(_expected, _seen, >, 0)
344 #define _EXPECT_GE(_expected, _seen) \
345         __EXPECT(_expected, _seen, >=, 0)
346
347 #define _EXPECT_NULL(_seen) \
348         __EXPECT(NULL, _seen, ==, 0)
349 #define _EXPECT_TRUE(_seen) \
350         _EXPECT_NE(0, _seen)
351 #define _EXPECT_FALSE(_seen) \
352         _EXPECT_EQ(0, _seen)
353
354 #define _EXPECT_STREQ(_expected, _seen) \
355         __EXPECT_STR(_expected, _seen, ==, 0)
356 #define _EXPECT_STRNE(_expected, _seen) \
357         __EXPECT_STR(_expected, _seen, !=, 0)
358
359 #define ARRAY_SIZE(a)   (sizeof(a) / sizeof(a[0]))
360
361 /* Support an optional handler after and ASSERT_* or EXPECT_*.  The approach is
362  * not thread-safe, but it should be fine in most sane test scenarios.
363  *
364  * Using __bail(), which optionally abort()s, is the easiest way to early
365  * return while still providing an optional block to the API consumer.
366  */
367 #define OPTIONAL_HANDLER(_assert) \
368         for (; _metadata->trigger;  _metadata->trigger = __bail(_assert))
369
370 #define __EXPECT(_expected, _seen, _t, _assert) do { \
371         /* Avoid multiple evaluation of the cases */ \
372         __typeof__(_expected) __exp = (_expected); \
373         __typeof__(_seen) __seen = (_seen); \
374         if (!(__exp _t __seen)) { \
375                 unsigned long long __exp_print = (uintptr_t)__exp; \
376                 unsigned long long __seen_print = (uintptr_t)__seen; \
377                 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
378                          #_expected, __exp_print, #_t, \
379                          #_seen, __seen_print); \
380                 _metadata->passed = 0; \
381                 /* Ensure the optional handler is triggered */ \
382                 _metadata->trigger = 1; \
383         } \
384 } while (0); OPTIONAL_HANDLER(_assert)
385
386 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
387         const char *__exp = (_expected); \
388         const char *__seen = (_seen); \
389         if (!(strcmp(__exp, __seen) _t 0))  { \
390                 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
391                 _metadata->passed = 0; \
392                 _metadata->trigger = 1; \
393         } \
394 } while (0); OPTIONAL_HANDLER(_assert)
395
396 /* Contains all the information for test execution and status checking. */
397 struct __test_metadata {
398         const char *name;
399         void (*fn)(struct __test_metadata *);
400         int termsig;
401         int passed;
402         int trigger; /* extra handler after the evaluation */
403         struct __test_metadata *prev, *next;
404 };
405
406 /* Storage for the (global) tests to be run. */
407 static struct __test_metadata *__test_list;
408 static unsigned int __test_count;
409 static unsigned int __fixture_count;
410 static int __constructor_order;
411
412 #define _CONSTRUCTOR_ORDER_FORWARD   1
413 #define _CONSTRUCTOR_ORDER_BACKWARD -1
414
415 /*
416  * Since constructors are called in reverse order, reverse the test
417  * list so tests are run in source declaration order.
418  * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
419  * However, it seems not all toolchains do this correctly, so use
420  * __constructor_order to detect which direction is called first
421  * and adjust list building logic to get things running in the right
422  * direction.
423  */
424 static inline void __register_test(struct __test_metadata *t)
425 {
426         __test_count++;
427         /* Circular linked list where only prev is circular. */
428         if (__test_list == NULL) {
429                 __test_list = t;
430                 t->next = NULL;
431                 t->prev = t;
432                 return;
433         }
434         if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) {
435                 t->next = NULL;
436                 t->prev = __test_list->prev;
437                 t->prev->next = t;
438                 __test_list->prev = t;
439         } else {
440                 t->next = __test_list;
441                 t->next->prev = t;
442                 t->prev = t;
443                 __test_list = t;
444         }
445 }
446
447 static inline int __bail(int for_realz)
448 {
449         if (for_realz)
450                 abort();
451         return 0;
452 }
453
454 void __run_test(struct __test_metadata *t)
455 {
456         pid_t child_pid;
457         int status;
458
459         t->passed = 1;
460         t->trigger = 0;
461         printf("[ RUN      ] %s\n", t->name);
462         child_pid = fork();
463         if (child_pid < 0) {
464                 printf("ERROR SPAWNING TEST CHILD\n");
465                 t->passed = 0;
466         } else if (child_pid == 0) {
467                 t->fn(t);
468                 _exit(t->passed);
469         } else {
470                 /* TODO(wad) add timeout support. */
471                 waitpid(child_pid, &status, 0);
472                 if (WIFEXITED(status)) {
473                         t->passed = t->termsig == -1 ? WEXITSTATUS(status) : 0;
474                         if (t->termsig != -1) {
475                                 fprintf(TH_LOG_STREAM,
476                                         "%s: Test exited normally "
477                                         "instead of by signal (code: %d)\n",
478                                         t->name,
479                                         WEXITSTATUS(status));
480                         }
481                 } else if (WIFSIGNALED(status)) {
482                         t->passed = 0;
483                         if (WTERMSIG(status) == SIGABRT) {
484                                 fprintf(TH_LOG_STREAM,
485                                         "%s: Test terminated by assertion\n",
486                                         t->name);
487                         } else if (WTERMSIG(status) == t->termsig) {
488                                 t->passed = 1;
489                         } else {
490                                 fprintf(TH_LOG_STREAM,
491                                         "%s: Test terminated unexpectedly "
492                                         "by signal %d\n",
493                                         t->name,
494                                         WTERMSIG(status));
495                         }
496                 } else {
497                         fprintf(TH_LOG_STREAM,
498                                 "%s: Test ended in some other way [%u]\n",
499                                 t->name,
500                                 status);
501                 }
502         }
503         printf("[     %4s ] %s\n", (t->passed ? "OK" : "FAIL"), t->name);
504 }
505
506 static int test_harness_run(int __attribute__((unused)) argc,
507                             char __attribute__((unused)) **argv)
508 {
509         struct __test_metadata *t;
510         int ret = 0;
511         unsigned int count = 0;
512         unsigned int pass_count = 0;
513
514         /* TODO(wad) add optional arguments similar to gtest. */
515         printf("[==========] Running %u tests from %u test cases.\n",
516                __test_count, __fixture_count + 1);
517         for (t = __test_list; t; t = t->next) {
518                 count++;
519                 __run_test(t);
520                 if (t->passed)
521                         pass_count++;
522                 else
523                         ret = 1;
524         }
525         printf("[==========] %u / %u tests passed.\n", pass_count, count);
526         printf("[  %s  ]\n", (ret ? "FAILED" : "PASSED"));
527         return ret;
528 }
529
530 static void __attribute__((constructor)) __constructor_order_first(void)
531 {
532         if (!__constructor_order)
533                 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
534 }
535
536 #endif  /* __KSELFTEST_HARNESS_H */