test_harness.h 17 KB

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