test_harness.h 17 KB

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