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  * test_harness.h: simple C unit test helper.
6  *
7  * Usage:
8  *   #include "test_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 #ifndef TEST_HARNESS_H_
42 #define TEST_HARNESS_H_
43 
44 #define _GNU_SOURCE
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sys/types.h>
49 #include <sys/wait.h>
50 #include <unistd.h>
51 
52 /* All exported functionality should be declared through this macro. */
53 #define TEST_API(x) _##x
54 
55 /*
56  * Exported APIs
57  */
58 
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.
64  *
65  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
66  */
67 #define TEST TEST_API(TEST)
68 
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.
74  *
75  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
76  */
77 #define TEST_SIGNAL TEST_API(TEST_SIGNAL)
78 
79 /* FIXTURE(datatype name) {
80  *   type property1;
81  *   ...
82  * };
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.
85  */
86 #define FIXTURE TEST_API(FIXTURE)
87 
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.
92  */
93 #define FIXTURE_DATA TEST_API(FIXTURE_DATA)
94 
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
98  * implementation.
99  *
100  * ASSERT_* are valid for use in this context and will prempt the execution
101  * of any dependent fixture tests.
102  *
103  * A bare "return;" statement may be used to return early.
104  */
105 #define FIXTURE_SETUP TEST_API(FIXTURE_SETUP)
106 
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.
111  *
112  * A bare "return;" statement may be used to return early.
113  */
114 #define FIXTURE_TEARDOWN TEST_API(FIXTURE_TEARDOWN)
115 
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.
120  */
121 #define TEST_F TEST_API(TEST_F)
122 
123 #define TEST_F_SIGNAL TEST_API(TEST_F_SIGNAL)
124 
125 /* Use once to append a main() to the test file. E.g.,
126  *   TEST_HARNESS_MAIN
127  */
128 #define TEST_HARNESS_MAIN TEST_API(TEST_HARNESS_MAIN)
129 
130 /*
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.
134  */
135 
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)
180 
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.
186  */
187 #define TH_LOG  TEST_API(TH_LOG)
188 
189 /*
190  * Internal implementation.
191  *
192  */
193 
194 /* Utilities exposed to the test definitions */
195 #ifndef TH_LOG_STREAM
196 #  define TH_LOG_STREAM stderr
197 #endif
198 
199 #ifndef TH_LOG_ENABLED
200 #  define TH_LOG_ENABLED 1
201 #endif
202 
203 #define _TH_LOG(fmt, ...) do { \
204 	if (TH_LOG_ENABLED) \
205 		__TH_LOG(fmt, ##__VA_ARGS__); \
206 } while (0)
207 
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__)
212 
213 /* Defines the test function and creates the registration stub. */
214 #define _TEST(test_name) __TEST_IMPL(test_name, -1)
215 
216 #define _TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
217 
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) \
224 	{ \
225 		__register_test(&_##test_name##_object); \
226 	} \
227 	static void test_name( \
228 		struct __test_metadata __attribute__((unused)) *_metadata)
229 
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
232 
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) \
237 	{ \
238 		__fixture_count++; \
239 	} \
240 	_FIXTURE_DATA(fixture_name)
241 
242 /* Prepares the setup function for the fixture.  |_metadata| is included
243  * so that ASSERT_* work as a convenience.
244  */
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)
253 
254 /* Emits test registration and helpers for fixture-based test
255  * cases.
256  * TODO(wad) register fixtures on dedicated test lists.
257  */
258 #define _TEST_F(fixture_name, test_name) \
259 	__TEST_F_IMPL(fixture_name, test_name, -1)
260 
261 #define _TEST_F_SIGNAL(fixture_name, test_name, signal) \
262 	__TEST_F_IMPL(fixture_name, test_name, signal)
263 
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) \
270 	{ \
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) \
277 			return; \
278 		fixture_name##_##test_name(_metadata, &self); \
279 		fixture_name##_teardown(_metadata, &self); \
280 	} \
281 	static struct __test_metadata \
282 		      _##fixture_name##_##test_name##_object = { \
283 		name: #fixture_name "." #test_name, \
284 		fn: &wrapper_##fixture_name##_##test_name, \
285 		termsig: signal, \
286 	 }; \
287 	static void __attribute__((constructor)) \
288 			_register_##fixture_name##_##test_name(void) \
289 	{ \
290 		__register_test(&_##fixture_name##_##test_name##_object); \
291 	} \
292 	static void fixture_name##_##test_name( \
293 		struct __test_metadata __attribute__((unused)) *_metadata, \
294 		_FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
295 
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) \
300 	{ \
301 		if (!__constructor_order) \
302 			__constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
303 	} \
304 	int main(int argc, char **argv) { \
305 		return test_harness_run(argc, argv); \
306 	}
307 
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)
322 
323 #define _ASSERT_TRUE(_seen) \
324 	_ASSERT_NE(0, _seen)
325 #define _ASSERT_FALSE(_seen) \
326 	_ASSERT_EQ(0, _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)
331 
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)
344 
345 #define _EXPECT_NULL(_seen) \
346 	__EXPECT(NULL, _seen, ==, 0)
347 #define _EXPECT_TRUE(_seen) \
348 	_EXPECT_NE(0, _seen)
349 #define _EXPECT_FALSE(_seen) \
350 	_EXPECT_EQ(0, _seen)
351 
352 #define _EXPECT_STREQ(_expected, _seen) \
353 	__EXPECT_STR(_expected, _seen, ==, 0)
354 #define _EXPECT_STRNE(_expected, _seen) \
355 	__EXPECT_STR(_expected, _seen, !=, 0)
356 
357 #define ARRAY_SIZE(a)	(sizeof(a) / sizeof(a[0]))
358 
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.
361  *
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.
364  */
365 #define OPTIONAL_HANDLER(_assert) \
366 	for (; _metadata->trigger;  _metadata->trigger = __bail(_assert))
367 
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 = (unsigned long long)__exp; \
374 		unsigned long long __seen_print = (unsigned long long)__seen; \
375 		__TH_LOG("Expected %s (%llu) %s %s (%llu)", \
376 			 #_expected, __exp_print, #_t, \
377 			 #_seen, __seen_print); \
378 		_metadata->passed = 0; \
379 		/* Ensure the optional handler is triggered */ \
380 		_metadata->trigger = 1; \
381 	} \
382 } while (0); OPTIONAL_HANDLER(_assert)
383 
384 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
385 	const char *__exp = (_expected); \
386 	const char *__seen = (_seen); \
387 	if (!(strcmp(__exp, __seen) _t 0))  { \
388 		__TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
389 		_metadata->passed = 0; \
390 		_metadata->trigger = 1; \
391 	} \
392 } while (0); OPTIONAL_HANDLER(_assert)
393 
394 /* Contains all the information for test execution and status checking. */
395 struct __test_metadata {
396 	const char *name;
397 	void (*fn)(struct __test_metadata *);
398 	int termsig;
399 	int passed;
400 	int trigger; /* extra handler after the evaluation */
401 	struct __test_metadata *prev, *next;
402 };
403 
404 /* Storage for the (global) tests to be run. */
405 static struct __test_metadata *__test_list;
406 static unsigned int __test_count;
407 static unsigned int __fixture_count;
408 static int __constructor_order;
409 
410 #define _CONSTRUCTOR_ORDER_FORWARD   1
411 #define _CONSTRUCTOR_ORDER_BACKWARD -1
412 
413 /*
414  * Since constructors are called in reverse order, reverse the test
415  * list so tests are run in source declaration order.
416  * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
417  * However, it seems not all toolchains do this correctly, so use
418  * __constructor_order to detect which direction is called first
419  * and adjust list building logic to get things running in the right
420  * direction.
421  */
__register_test(struct __test_metadata * t)422 static inline void __register_test(struct __test_metadata *t)
423 {
424 	__test_count++;
425 	/* Circular linked list where only prev is circular. */
426 	if (__test_list == NULL) {
427 		__test_list = t;
428 		t->next = NULL;
429 		t->prev = t;
430 		return;
431 	}
432 	if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) {
433 		t->next = NULL;
434 		t->prev = __test_list->prev;
435 		t->prev->next = t;
436 		__test_list->prev = t;
437 	} else {
438 		t->next = __test_list;
439 		t->next->prev = t;
440 		t->prev = t;
441 		__test_list = t;
442 	}
443 }
444 
__bail(int for_realz)445 static inline int __bail(int for_realz)
446 {
447 	if (for_realz)
448 		abort();
449 	return 0;
450 }
451 
__run_test(struct __test_metadata * t)452 void __run_test(struct __test_metadata *t)
453 {
454 	pid_t child_pid;
455 	int status;
456 
457 	t->passed = 1;
458 	t->trigger = 0;
459 	printf("[ RUN      ] %s\n", t->name);
460 	child_pid = fork();
461 	if (child_pid < 0) {
462 		printf("ERROR SPAWNING TEST CHILD\n");
463 		t->passed = 0;
464 	} else if (child_pid == 0) {
465 		t->fn(t);
466 		_exit(t->passed);
467 	} else {
468 		/* TODO(wad) add timeout support. */
469 		waitpid(child_pid, &status, 0);
470 		if (WIFEXITED(status)) {
471 			t->passed = t->termsig == -1 ? WEXITSTATUS(status) : 0;
472 			if (t->termsig != -1) {
473 				fprintf(TH_LOG_STREAM,
474 					"%s: Test exited normally "
475 					"instead of by signal (code: %d)\n",
476 					t->name,
477 					WEXITSTATUS(status));
478 			}
479 		} else if (WIFSIGNALED(status)) {
480 			t->passed = 0;
481 			if (WTERMSIG(status) == SIGABRT) {
482 				fprintf(TH_LOG_STREAM,
483 					"%s: Test terminated by assertion\n",
484 					t->name);
485 			} else if (WTERMSIG(status) == t->termsig) {
486 				t->passed = 1;
487 			} else {
488 				fprintf(TH_LOG_STREAM,
489 					"%s: Test terminated unexpectedly "
490 					"by signal %d\n",
491 					t->name,
492 					WTERMSIG(status));
493 			}
494 		} else {
495 			fprintf(TH_LOG_STREAM,
496 				"%s: Test ended in some other way [%u]\n",
497 				t->name,
498 				status);
499 		}
500 	}
501 	printf("[     %4s ] %s\n", (t->passed ? "OK" : "FAIL"), t->name);
502 }
503 
test_harness_run(int argc,char ** argv)504 static int test_harness_run(int __attribute__((unused)) argc,
505 			    char __attribute__((unused)) **argv)
506 {
507 	struct __test_metadata *t;
508 	int ret = 0;
509 	unsigned int count = 0;
510 	unsigned int pass_count = 0;
511 
512 	/* TODO(wad) add optional arguments similar to gtest. */
513 	printf("[==========] Running %u tests from %u test cases.\n",
514 	       __test_count, __fixture_count + 1);
515 	for (t = __test_list; t; t = t->next) {
516 		count++;
517 		__run_test(t);
518 		if (t->passed)
519 			pass_count++;
520 		else
521 			ret = 1;
522 	}
523 	printf("[==========] %u / %u tests passed.\n", pass_count, count);
524 	printf("[  %s  ]\n", (ret ? "FAILED" : "PASSED"));
525 	return ret;
526 }
527 
__constructor_order_first(void)528 static void __attribute__((constructor)) __constructor_order_first(void)
529 {
530 	if (!__constructor_order)
531 		__constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
532 }
533 
534 #endif  /* TEST_HARNESS_H_ */
535