2 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by the GPLv2 license.
5 * test_harness.h: simple C unit test helper.
8 * #include "test_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
41 #ifndef TEST_HARNESS_H_
42 #define TEST_HARNESS_H_
48 #include <sys/types.h>
52 /* All exported functionality should be declared through this macro. */
53 #define TEST_API(x) _##x
59 /* TEST(name) { implementation }
60 * Defines a test by name.
61 * Names must be unique and tests must not be run in parallel. The
62 * implementation containing block is a function and scoping should be treated
63 * as such. Returning early may be performed with a bare "return;" statement.
65 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
67 #define TEST TEST_API(TEST)
69 /* TEST_SIGNAL(name, signal) { implementation }
70 * Defines a test by name and the expected term signal.
71 * Names must be unique and tests must not be run in parallel. The
72 * implementation containing block is a function and scoping should be treated
73 * as such. Returning early may be performed with a bare "return;" statement.
75 * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
77 #define TEST_SIGNAL TEST_API(TEST_SIGNAL)
79 /* FIXTURE(datatype name) {
83 * Defines the data provided to TEST_F()-defined tests as |self|. It should be
84 * populated and cleaned up using FIXTURE_SETUP and FIXTURE_TEARDOWN.
86 #define FIXTURE TEST_API(FIXTURE)
88 /* FIXTURE_DATA(datatype name)
89 * This call may be used when the type of the fixture data
90 * is needed. In general, this should not be needed unless
91 * the |self| is being passed to a helper directly.
93 #define FIXTURE_DATA TEST_API(FIXTURE_DATA)
95 /* FIXTURE_SETUP(fixture name) { implementation }
96 * Populates the required "setup" function for a fixture. An instance of the
97 * datatype defined with _FIXTURE_DATA will be exposed as |self| for the
100 * ASSERT_* are valid for use in this context and will prempt the execution
101 * of any dependent fixture tests.
103 * A bare "return;" statement may be used to return early.
105 #define FIXTURE_SETUP TEST_API(FIXTURE_SETUP)
107 /* FIXTURE_TEARDOWN(fixture name) { implementation }
108 * Populates the required "teardown" function for a fixture. An instance of the
109 * datatype defined with _FIXTURE_DATA will be exposed as |self| for the
110 * implementation to clean up.
112 * A bare "return;" statement may be used to return early.
114 #define FIXTURE_TEARDOWN TEST_API(FIXTURE_TEARDOWN)
116 /* TEST_F(fixture, name) { implementation }
117 * Defines a test that depends on a fixture (e.g., is part of a test case).
118 * Very similar to TEST() except that |self| is the setup instance of fixture's
119 * datatype exposed for use by the implementation.
121 #define TEST_F TEST_API(TEST_F)
123 #define TEST_F_SIGNAL TEST_API(TEST_F_SIGNAL)
125 /* Use once to append a main() to the test file. E.g.,
128 #define TEST_HARNESS_MAIN TEST_API(TEST_HARNESS_MAIN)
131 * Operators for use in TEST and TEST_F.
132 * ASSERT_* calls will stop test execution immediately.
133 * EXPECT_* calls will emit a failure warning, note it, and continue.
136 /* ASSERT_EQ(expected, measured): expected == measured */
137 #define ASSERT_EQ TEST_API(ASSERT_EQ)
138 /* ASSERT_NE(expected, measured): expected != measured */
139 #define ASSERT_NE TEST_API(ASSERT_NE)
140 /* ASSERT_LT(expected, measured): expected < measured */
141 #define ASSERT_LT TEST_API(ASSERT_LT)
142 /* ASSERT_LE(expected, measured): expected <= measured */
143 #define ASSERT_LE TEST_API(ASSERT_LE)
144 /* ASSERT_GT(expected, measured): expected > measured */
145 #define ASSERT_GT TEST_API(ASSERT_GT)
146 /* ASSERT_GE(expected, measured): expected >= measured */
147 #define ASSERT_GE TEST_API(ASSERT_GE)
148 /* ASSERT_NULL(measured): NULL == measured */
149 #define ASSERT_NULL TEST_API(ASSERT_NULL)
150 /* ASSERT_TRUE(measured): measured != 0 */
151 #define ASSERT_TRUE TEST_API(ASSERT_TRUE)
152 /* ASSERT_FALSE(measured): measured == 0 */
153 #define ASSERT_FALSE TEST_API(ASSERT_FALSE)
154 /* ASSERT_STREQ(expected, measured): !strcmp(expected, measured) */
155 #define ASSERT_STREQ TEST_API(ASSERT_STREQ)
156 /* ASSERT_STRNE(expected, measured): strcmp(expected, measured) */
157 #define ASSERT_STRNE TEST_API(ASSERT_STRNE)
158 /* EXPECT_EQ(expected, measured): expected == measured */
159 #define EXPECT_EQ TEST_API(EXPECT_EQ)
160 /* EXPECT_NE(expected, measured): expected != measured */
161 #define EXPECT_NE TEST_API(EXPECT_NE)
162 /* EXPECT_LT(expected, measured): expected < measured */
163 #define EXPECT_LT TEST_API(EXPECT_LT)
164 /* EXPECT_LE(expected, measured): expected <= measured */
165 #define EXPECT_LE TEST_API(EXPECT_LE)
166 /* EXPECT_GT(expected, measured): expected > measured */
167 #define EXPECT_GT TEST_API(EXPECT_GT)
168 /* EXPECT_GE(expected, measured): expected >= measured */
169 #define EXPECT_GE TEST_API(EXPECT_GE)
170 /* EXPECT_NULL(measured): NULL == measured */
171 #define EXPECT_NULL TEST_API(EXPECT_NULL)
172 /* EXPECT_TRUE(measured): 0 != measured */
173 #define EXPECT_TRUE TEST_API(EXPECT_TRUE)
174 /* EXPECT_FALSE(measured): 0 == measured */
175 #define EXPECT_FALSE TEST_API(EXPECT_FALSE)
176 /* EXPECT_STREQ(expected, measured): !strcmp(expected, measured) */
177 #define EXPECT_STREQ TEST_API(EXPECT_STREQ)
178 /* EXPECT_STRNE(expected, measured): strcmp(expected, measured) */
179 #define EXPECT_STRNE TEST_API(EXPECT_STRNE)
181 /* TH_LOG(format, ...)
182 * Optional debug logging function available for use in tests.
183 * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
184 * E.g., #define TH_LOG_ENABLED 1
185 * If no definition is provided, logging is enabled by default.
187 #define TH_LOG TEST_API(TH_LOG)
190 * Internal implementation.
194 /* Utilities exposed to the test definitions */
195 #ifndef TH_LOG_STREAM
196 # define TH_LOG_STREAM stderr
199 #ifndef TH_LOG_ENABLED
200 # define TH_LOG_ENABLED 1
203 #define _TH_LOG(fmt, ...) do { \
204 if (TH_LOG_ENABLED) \
205 __TH_LOG(fmt, ##__VA_ARGS__); \
208 /* Unconditional logger for internal use. */
209 #define __TH_LOG(fmt, ...) \
210 fprintf(TH_LOG_STREAM, "%s:%d:%s:" fmt "\n", \
211 __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
213 /* Defines the test function and creates the registration stub. */
214 #define _TEST(test_name) __TEST_IMPL(test_name, -1)
216 #define _TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
218 #define __TEST_IMPL(test_name, _signal) \
219 static void test_name(struct __test_metadata *_metadata); \
220 static struct __test_metadata _##test_name##_object = \
221 { name: "global." #test_name, \
222 fn: &test_name, termsig: _signal }; \
223 static void __attribute__((constructor)) _register_##test_name(void) \
225 __register_test(&_##test_name##_object); \
227 static void test_name( \
228 struct __test_metadata __attribute__((unused)) *_metadata)
230 /* Wraps the struct name so we have one less argument to pass around. */
231 #define _FIXTURE_DATA(fixture_name) struct _test_data_##fixture_name
233 /* Called once per fixture to setup the data and register. */
234 #define _FIXTURE(fixture_name) \
235 static void __attribute__((constructor)) \
236 _register_##fixture_name##_data(void) \
240 _FIXTURE_DATA(fixture_name)
242 /* Prepares the setup function for the fixture. |_metadata| is included
243 * so that ASSERT_* work as a convenience.
245 #define _FIXTURE_SETUP(fixture_name) \
246 void fixture_name##_setup( \
247 struct __test_metadata __attribute__((unused)) *_metadata, \
248 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
249 #define _FIXTURE_TEARDOWN(fixture_name) \
250 void fixture_name##_teardown( \
251 struct __test_metadata __attribute__((unused)) *_metadata, \
252 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
254 /* Emits test registration and helpers for fixture-based test
256 * TODO(wad) register fixtures on dedicated test lists.
258 #define _TEST_F(fixture_name, test_name) \
259 __TEST_F_IMPL(fixture_name, test_name, -1)
261 #define _TEST_F_SIGNAL(fixture_name, test_name, signal) \
262 __TEST_F_IMPL(fixture_name, test_name, signal)
264 #define __TEST_F_IMPL(fixture_name, test_name, signal) \
265 static void fixture_name##_##test_name( \
266 struct __test_metadata *_metadata, \
267 _FIXTURE_DATA(fixture_name) *self); \
268 static inline void wrapper_##fixture_name##_##test_name( \
269 struct __test_metadata *_metadata) \
271 /* fixture data is alloced, setup, and torn down per call. */ \
272 _FIXTURE_DATA(fixture_name) self; \
273 memset(&self, 0, sizeof(_FIXTURE_DATA(fixture_name))); \
274 fixture_name##_setup(_metadata, &self); \
275 /* Let setup failure terminate early. */ \
276 if (!_metadata->passed) \
278 fixture_name##_##test_name(_metadata, &self); \
279 fixture_name##_teardown(_metadata, &self); \
281 static struct __test_metadata \
282 _##fixture_name##_##test_name##_object = { \
283 name: #fixture_name "." #test_name, \
284 fn: &wrapper_##fixture_name##_##test_name, \
287 static void __attribute__((constructor)) \
288 _register_##fixture_name##_##test_name(void) \
290 __register_test(&_##fixture_name##_##test_name##_object); \
292 static void fixture_name##_##test_name( \
293 struct __test_metadata __attribute__((unused)) *_metadata, \
294 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
296 /* Exports a simple wrapper to run the test harness. */
297 #define _TEST_HARNESS_MAIN \
298 static void __attribute__((constructor)) \
299 __constructor_order_last(void) \
301 if (!__constructor_order) \
302 __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
304 int main(int argc, char **argv) { \
305 return test_harness_run(argc, argv); \
308 #define _ASSERT_EQ(_expected, _seen) \
309 __EXPECT(_expected, _seen, ==, 1)
310 #define _ASSERT_NE(_expected, _seen) \
311 __EXPECT(_expected, _seen, !=, 1)
312 #define _ASSERT_LT(_expected, _seen) \
313 __EXPECT(_expected, _seen, <, 1)
314 #define _ASSERT_LE(_expected, _seen) \
315 __EXPECT(_expected, _seen, <=, 1)
316 #define _ASSERT_GT(_expected, _seen) \
317 __EXPECT(_expected, _seen, >, 1)
318 #define _ASSERT_GE(_expected, _seen) \
319 __EXPECT(_expected, _seen, >=, 1)
320 #define _ASSERT_NULL(_seen) \
321 __EXPECT(NULL, _seen, ==, 1)
323 #define _ASSERT_TRUE(_seen) \
325 #define _ASSERT_FALSE(_seen) \
327 #define _ASSERT_STREQ(_expected, _seen) \
328 __EXPECT_STR(_expected, _seen, ==, 1)
329 #define _ASSERT_STRNE(_expected, _seen) \
330 __EXPECT_STR(_expected, _seen, !=, 1)
332 #define _EXPECT_EQ(_expected, _seen) \
333 __EXPECT(_expected, _seen, ==, 0)
334 #define _EXPECT_NE(_expected, _seen) \
335 __EXPECT(_expected, _seen, !=, 0)
336 #define _EXPECT_LT(_expected, _seen) \
337 __EXPECT(_expected, _seen, <, 0)
338 #define _EXPECT_LE(_expected, _seen) \
339 __EXPECT(_expected, _seen, <=, 0)
340 #define _EXPECT_GT(_expected, _seen) \
341 __EXPECT(_expected, _seen, >, 0)
342 #define _EXPECT_GE(_expected, _seen) \
343 __EXPECT(_expected, _seen, >=, 0)
345 #define _EXPECT_NULL(_seen) \
346 __EXPECT(NULL, _seen, ==, 0)
347 #define _EXPECT_TRUE(_seen) \
349 #define _EXPECT_FALSE(_seen) \
352 #define _EXPECT_STREQ(_expected, _seen) \
353 __EXPECT_STR(_expected, _seen, ==, 0)
354 #define _EXPECT_STRNE(_expected, _seen) \
355 __EXPECT_STR(_expected, _seen, !=, 0)
357 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
359 /* Support an optional handler after and ASSERT_* or EXPECT_*. The approach is
360 * not thread-safe, but it should be fine in most sane test scenarios.
362 * Using __bail(), which optionally abort()s, is the easiest way to early
363 * return while still providing an optional block to the API consumer.
365 #define OPTIONAL_HANDLER(_assert) \
366 for (; _metadata->trigger; _metadata->trigger = __bail(_assert))
368 #define __EXPECT(_expected, _seen, _t, _assert) do { \
369 /* Avoid multiple evaluation of the cases */ \
370 __typeof__(_expected) __exp = (_expected); \
371 __typeof__(_seen) __seen = (_seen); \
372 if (!(__exp _t __seen)) { \
373 unsigned long long __exp_print = 0; \
374 unsigned long long __seen_print = 0; \
375 /* Avoid casting complaints the scariest way we can. */ \
376 memcpy(&__exp_print, &__exp, sizeof(__exp)); \
377 memcpy(&__seen_print, &__seen, sizeof(__seen)); \
378 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
379 #_expected, __exp_print, #_t, \
380 #_seen, __seen_print); \
381 _metadata->passed = 0; \
382 /* Ensure the optional handler is triggered */ \
383 _metadata->trigger = 1; \
385 } while (0); OPTIONAL_HANDLER(_assert)
387 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
388 const char *__exp = (_expected); \
389 const char *__seen = (_seen); \
390 if (!(strcmp(__exp, __seen) _t 0)) { \
391 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
392 _metadata->passed = 0; \
393 _metadata->trigger = 1; \
395 } while (0); OPTIONAL_HANDLER(_assert)
397 /* Contains all the information for test execution and status checking. */
398 struct __test_metadata
{
400 void (*fn
)(struct __test_metadata
*);
403 int trigger
; /* extra handler after the evaluation */
404 struct __test_metadata
*prev
, *next
;
407 /* Storage for the (global) tests to be run. */
408 static struct __test_metadata
*__test_list
;
409 static unsigned int __test_count
;
410 static unsigned int __fixture_count
;
411 static int __constructor_order
;
413 #define _CONSTRUCTOR_ORDER_FORWARD 1
414 #define _CONSTRUCTOR_ORDER_BACKWARD -1
417 * Since constructors are called in reverse order, reverse the test
418 * list so tests are run in source declaration order.
419 * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
420 * However, it seems not all toolchains do this correctly, so use
421 * __constructor_order to detect which direction is called first
422 * and adjust list building logic to get things running in the right
425 static inline void __register_test(struct __test_metadata
*t
)
428 /* Circular linked list where only prev is circular. */
429 if (__test_list
== NULL
) {
435 if (__constructor_order
== _CONSTRUCTOR_ORDER_FORWARD
) {
437 t
->prev
= __test_list
->prev
;
439 __test_list
->prev
= t
;
441 t
->next
= __test_list
;
448 static inline int __bail(int for_realz
)
455 void __run_test(struct __test_metadata
*t
)
462 printf("[ RUN ] %s\n", t
->name
);
465 printf("ERROR SPAWNING TEST CHILD\n");
467 } else if (child_pid
== 0) {
471 /* TODO(wad) add timeout support. */
472 waitpid(child_pid
, &status
, 0);
473 if (WIFEXITED(status
)) {
474 t
->passed
= t
->termsig
== -1 ? WEXITSTATUS(status
) : 0;
475 if (t
->termsig
!= -1) {
476 fprintf(TH_LOG_STREAM
,
477 "%s: Test exited normally "
478 "instead of by signal (code: %d)\n",
480 WEXITSTATUS(status
));
482 } else if (WIFSIGNALED(status
)) {
484 if (WTERMSIG(status
) == SIGABRT
) {
485 fprintf(TH_LOG_STREAM
,
486 "%s: Test terminated by assertion\n",
488 } else if (WTERMSIG(status
) == t
->termsig
) {
491 fprintf(TH_LOG_STREAM
,
492 "%s: Test terminated unexpectedly "
498 fprintf(TH_LOG_STREAM
,
499 "%s: Test ended in some other way [%u]\n",
504 printf("[ %4s ] %s\n", (t
->passed
? "OK" : "FAIL"), t
->name
);
507 static int test_harness_run(int __attribute__((unused
)) argc
,
508 char __attribute__((unused
)) **argv
)
510 struct __test_metadata
*t
;
512 unsigned int count
= 0;
513 unsigned int pass_count
= 0;
515 /* TODO(wad) add optional arguments similar to gtest. */
516 printf("[==========] Running %u tests from %u test cases.\n",
517 __test_count
, __fixture_count
+ 1);
518 for (t
= __test_list
; t
; t
= t
->next
) {
526 printf("[==========] %u / %u tests passed.\n", pass_count
, count
);
527 printf("[ %s ]\n", (ret
? "FAILED" : "PASSED"));
531 static void __attribute__((constructor
)) __constructor_order_first(void)
533 if (!__constructor_order
)
534 __constructor_order
= _CONSTRUCTOR_ORDER_FORWARD
;
537 #endif /* TEST_HARNESS_H_ */