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