2 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by the GPLv2 license.
5 * kselftest_harness.h: simple C unit test helper.
8 * #include "../kselftest_harness.h"
9 * TEST(standalone_test) {
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);
17 * ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!");
19 * EXPECT_EQ(0, last_stuff);
22 * FIXTURE(my_fixture) {
24 * int awesomeness_level;
26 * FIXTURE_SETUP(my_fixture) {
27 * self->data = mytype_new();
28 * ASSERT_NE(NULL, self->data);
30 * FIXTURE_TEARDOWN(my_fixture) {
31 * mytype_free(self->data);
33 * TEST_F(my_fixture, data_is_good) {
34 * EXPECT_EQ(1, is_my_data_good(self->data));
39 * API inspired by code.google.com/p/googletest
42 #ifndef __KSELFTEST_HARNESS_H
43 #define __KSELFTEST_HARNESS_H
50 #include <sys/types.h>
54 /* All exported functionality should be declared through this macro. */
55 #define TEST_API(x) _##x
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.
67 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
69 #define TEST TEST_API(TEST)
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.
77 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
79 #define TEST_SIGNAL TEST_API(TEST_SIGNAL)
81 /* FIXTURE(datatype name) {
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.
88 #define FIXTURE TEST_API(FIXTURE)
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.
95 #define FIXTURE_DATA TEST_API(FIXTURE_DATA)
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
102 * ASSERT_* are valid for use in this context and will prempt the execution
103 * of any dependent fixture tests.
105 * A bare "return;" statement may be used to return early.
107 #define FIXTURE_SETUP TEST_API(FIXTURE_SETUP)
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.
114 * A bare "return;" statement may be used to return early.
116 #define FIXTURE_TEARDOWN TEST_API(FIXTURE_TEARDOWN)
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.
123 #define TEST_F TEST_API(TEST_F)
125 #define TEST_F_SIGNAL TEST_API(TEST_F_SIGNAL)
127 /* Use once to append a main() to the test file. E.g.,
130 #define TEST_HARNESS_MAIN TEST_API(TEST_HARNESS_MAIN)
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.
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)
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.
189 #define TH_LOG TEST_API(TH_LOG)
192 * Internal implementation.
196 /* Utilities exposed to the test definitions */
197 #ifndef TH_LOG_STREAM
198 # define TH_LOG_STREAM stderr
201 #ifndef TH_LOG_ENABLED
202 # define TH_LOG_ENABLED 1
205 #define _TH_LOG(fmt, ...) do { \
206 if (TH_LOG_ENABLED) \
207 __TH_LOG(fmt, ##__VA_ARGS__); \
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__)
215 /* Defines the test function and creates the registration stub. */
216 #define _TEST(test_name) __TEST_IMPL(test_name, -1)
218 #define _TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
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) \
227 __register_test(&_##test_name##_object); \
229 static void test_name( \
230 struct __test_metadata __attribute__((unused)) *_metadata)
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
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) \
242 _FIXTURE_DATA(fixture_name)
244 /* Prepares the setup function for the fixture. |_metadata| is included
245 * so that ASSERT_* work as a convenience.
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)
256 /* Emits test registration and helpers for fixture-based test
258 * TODO(wad) register fixtures on dedicated test lists.
260 #define _TEST_F(fixture_name, test_name) \
261 __TEST_F_IMPL(fixture_name, test_name, -1)
263 #define _TEST_F_SIGNAL(fixture_name, test_name, signal) \
264 __TEST_F_IMPL(fixture_name, test_name, signal)
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) \
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) \
280 fixture_name##_##test_name(_metadata, &self); \
281 fixture_name##_teardown(_metadata, &self); \
283 static struct __test_metadata \
284 _##fixture_name##_##test_name##_object = { \
285 name: #fixture_name "." #test_name, \
286 fn: &wrapper_##fixture_name##_##test_name, \
289 static void __attribute__((constructor)) \
290 _register_##fixture_name##_##test_name(void) \
292 __register_test(&_##fixture_name##_##test_name##_object); \
294 static void fixture_name##_##test_name( \
295 struct __test_metadata __attribute__((unused)) *_metadata, \
296 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
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) \
303 if (!__constructor_order) \
304 __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
306 int main(int argc, char **argv) { \
307 return test_harness_run(argc, argv); \
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)
325 #define _ASSERT_TRUE(_seen) \
327 #define _ASSERT_FALSE(_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)
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)
347 #define _EXPECT_NULL(_seen) \
348 __EXPECT(NULL, _seen, ==, 0)
349 #define _EXPECT_TRUE(_seen) \
351 #define _EXPECT_FALSE(_seen) \
354 #define _EXPECT_STREQ(_expected, _seen) \
355 __EXPECT_STR(_expected, _seen, ==, 0)
356 #define _EXPECT_STRNE(_expected, _seen) \
357 __EXPECT_STR(_expected, _seen, !=, 0)
359 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
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.
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.
367 #define OPTIONAL_HANDLER(_assert) \
368 for (; _metadata->trigger; _metadata->trigger = __bail(_assert))
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; \
384 } while (0); OPTIONAL_HANDLER(_assert)
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; \
394 } while (0); OPTIONAL_HANDLER(_assert)
396 /* Contains all the information for test execution and status checking. */
397 struct __test_metadata {
399 void (*fn)(struct __test_metadata *);
402 int trigger; /* extra handler after the evaluation */
403 struct __test_metadata *prev, *next;
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;
412 #define _CONSTRUCTOR_ORDER_FORWARD 1
413 #define _CONSTRUCTOR_ORDER_BACKWARD -1
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
424 static inline void __register_test(struct __test_metadata *t)
427 /* Circular linked list where only prev is circular. */
428 if (__test_list == NULL) {
434 if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) {
436 t->prev = __test_list->prev;
438 __test_list->prev = t;
440 t->next = __test_list;
447 static inline int __bail(int for_realz)
454 void __run_test(struct __test_metadata *t)
461 printf("[ RUN ] %s\n", t->name);
464 printf("ERROR SPAWNING TEST CHILD\n");
466 } else if (child_pid == 0) {
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",
479 WEXITSTATUS(status));
481 } else if (WIFSIGNALED(status)) {
483 if (WTERMSIG(status) == SIGABRT) {
484 fprintf(TH_LOG_STREAM,
485 "%s: Test terminated by assertion\n",
487 } else if (WTERMSIG(status) == t->termsig) {
490 fprintf(TH_LOG_STREAM,
491 "%s: Test terminated unexpectedly "
497 fprintf(TH_LOG_STREAM,
498 "%s: Test ended in some other way [%u]\n",
503 printf("[ %4s ] %s\n", (t->passed ? "OK" : "FAIL"), t->name);
506 static int test_harness_run(int __attribute__((unused)) argc,
507 char __attribute__((unused)) **argv)
509 struct __test_metadata *t;
511 unsigned int count = 0;
512 unsigned int pass_count = 0;
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) {
525 printf("[==========] %u / %u tests passed.\n", pass_count, count);
526 printf("[ %s ]\n", (ret ? "FAILED" : "PASSED"));
530 static void __attribute__((constructor)) __constructor_order_first(void)
532 if (!__constructor_order)
533 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
536 #endif /* __KSELFTEST_HARNESS_H */