1/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
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, fn: &test_name, termsig: _signal }; \
222  static void __attribute__((constructor)) _register_##test_name(void) { \
223    __register_test(&_##test_name##_object); \
224  } \
225  static void test_name( \
226    struct __test_metadata __attribute__((unused)) *_metadata)
227
228/* Wraps the struct name so we have one less argument to pass around. */
229#define _FIXTURE_DATA(fixture_name) struct _test_data_##fixture_name
230
231/* Called once per fixture to setup the data and register. */
232#define _FIXTURE(fixture_name) \
233  static void __attribute__((constructor)) \
234      _register_##fixture_name##_data(void) { \
235    __fixture_count++; \
236  } \
237  _FIXTURE_DATA(fixture_name)
238
239/* Prepares the setup function for the fixture.  |_metadata| is included
240 * so that ASSERT_* work as a convenience.
241 */
242#define _FIXTURE_SETUP(fixture_name) \
243  void fixture_name##_setup( \
244    struct __test_metadata __attribute__((unused)) *_metadata, \
245    _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
246#define _FIXTURE_TEARDOWN(fixture_name) \
247  void fixture_name##_teardown( \
248    struct __test_metadata __attribute__((unused)) *_metadata, \
249    _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
250
251/* Emits test registration and helpers for fixture-based test
252 * cases.
253 * TODO(wad) register fixtures on dedicated test lists.
254 */
255#define _TEST_F(fixture_name, test_name) \
256  __TEST_F_IMPL(fixture_name, test_name, -1)
257
258#define _TEST_F_SIGNAL(fixture_name, test_name, signal) \
259  __TEST_F_IMPL(fixture_name, test_name, signal)
260
261#define __TEST_F_IMPL(fixture_name, test_name, signal) \
262  static void fixture_name##_##test_name( \
263    struct __test_metadata *_metadata, \
264    _FIXTURE_DATA(fixture_name) *self); \
265  static inline void wrapper_##fixture_name##_##test_name( \
266    struct __test_metadata *_metadata) { \
267    /* fixture data is allocated, setup, and torn down per call. */ \
268    _FIXTURE_DATA(fixture_name) self; \
269    memset(&self, 0, sizeof(_FIXTURE_DATA(fixture_name))); \
270    fixture_name##_setup(_metadata, &self); \
271    /* Let setup failure terminate early. */ \
272    if (!_metadata->passed) return; \
273    fixture_name##_##test_name(_metadata, &self); \
274    fixture_name##_teardown(_metadata, &self); \
275  } \
276  static struct __test_metadata _##fixture_name##_##test_name##_object = { \
277    name: #fixture_name "." #test_name, \
278    fn: &wrapper_##fixture_name##_##test_name, \
279    termsig: signal, \
280   }; \
281  static void __attribute__((constructor)) \
282      _register_##fixture_name##_##test_name(void) { \
283    __register_test(&_##fixture_name##_##test_name##_object); \
284  } \
285  static void fixture_name##_##test_name( \
286    struct __test_metadata __attribute__((unused)) *_metadata, \
287    _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
288
289/* Exports a simple wrapper to run the test harness. */
290#define _TEST_HARNESS_MAIN \
291  int main(int argc, char **argv) { return test_harness_run(argc, argv); }
292
293#define _ASSERT_EQ(_expected, _seen) \
294  __EXPECT(_expected, _seen, ==, 1)
295#define _ASSERT_NE(_expected, _seen) \
296  __EXPECT(_expected, _seen, !=, 1)
297#define _ASSERT_LT(_expected, _seen) \
298  __EXPECT(_expected, _seen, <, 1)
299#define _ASSERT_LE(_expected, _seen) \
300  __EXPECT(_expected, _seen, <=, 1)
301#define _ASSERT_GT(_expected, _seen) \
302  __EXPECT(_expected, _seen, >, 1)
303#define _ASSERT_GE(_expected, _seen) \
304  __EXPECT(_expected, _seen, >=, 1)
305#define _ASSERT_NULL(_seen) \
306  __EXPECT(NULL, _seen, ==, 1)
307
308#define _ASSERT_TRUE(_seen) \
309  _ASSERT_NE(0, _seen)
310#define _ASSERT_FALSE(_seen) \
311  _ASSERT_EQ(0, _seen)
312#define _ASSERT_STREQ(_expected, _seen) \
313  __EXPECT_STR(_expected, _seen, ==, 1)
314#define _ASSERT_STRNE(_expected, _seen) \
315  __EXPECT_STR(_expected, _seen, !=, 1)
316
317#define _EXPECT_EQ(_expected, _seen) \
318  __EXPECT(_expected, _seen, ==, 0)
319#define _EXPECT_NE(_expected, _seen) \
320  __EXPECT(_expected, _seen, !=, 0)
321#define _EXPECT_LT(_expected, _seen) \
322  __EXPECT(_expected, _seen, <, 0)
323#define _EXPECT_LE(_expected, _seen) \
324  __EXPECT(_expected, _seen, <=, 0)
325#define _EXPECT_GT(_expected, _seen) \
326  __EXPECT(_expected, _seen, >, 0)
327#define _EXPECT_GE(_expected, _seen) \
328  __EXPECT(_expected, _seen, >=, 0)
329
330#define _EXPECT_NULL(_seen) \
331  __EXPECT(NULL, _seen, ==, 0)
332#define _EXPECT_TRUE(_seen) \
333  _EXPECT_NE(0, _seen)
334#define _EXPECT_FALSE(_seen) \
335  _EXPECT_EQ(0, _seen)
336
337#define _EXPECT_STREQ(_expected, _seen) \
338  __EXPECT_STR(_expected, _seen, ==, 0)
339#define _EXPECT_STRNE(_expected, _seen) \
340  __EXPECT_STR(_expected, _seen, !=, 0)
341
342/* Support an optional handler after and ASSERT_* or EXPECT_*.  The approach is
343 * not thread-safe, but it should be fine in most sane test scenarios.
344 *
345 * Using __bail(), which optionally abort()s, is the easiest way to early
346 * return while still providing an optional block to the API consumer.
347 */
348#define OPTIONAL_HANDLER(_assert) \
349  for (; _metadata->trigger;  _metadata->trigger = __bail(_assert))
350
351#define __EXPECT(_expected, _seen, _t, _assert) do { \
352  /* Avoid multiple evaluation of the cases */ \
353  __typeof__(_expected) __exp = (_expected); \
354  __typeof__(_seen) __seen = (_seen); \
355  if (!(__exp _t __seen)) { \
356    unsigned long long __exp_print = 0; \
357    unsigned long long __seen_print = 0; \
358    /* Avoid casting complaints the scariest way we can. */ \
359    memcpy(&__exp_print, &__exp, sizeof(__exp)); \
360    memcpy(&__seen_print, &__seen, sizeof(__seen)); \
361    __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
362            #_expected, __exp_print, #_t, \
363            #_seen, __seen_print); \
364    _metadata->passed = 0; \
365    /* Ensure the optional handler is triggered */ \
366    _metadata->trigger = 1; \
367  } \
368} while (0); OPTIONAL_HANDLER(_assert)
369
370#define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
371  const char *__exp = (_expected); \
372  const char *__seen = (_seen); \
373  if (!(strcmp(__exp, __seen) _t 0))  { \
374    __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
375    _metadata->passed = 0; \
376    _metadata->trigger = 1; \
377  } \
378} while (0); OPTIONAL_HANDLER(_assert)
379
380/* Contains all the information for test execution and status checking. */
381struct __test_metadata {
382  const char *name;
383  void (*fn)(struct __test_metadata *);
384  int termsig;
385  int passed;
386  int trigger; /* extra handler after the evaluation */
387  struct __test_metadata *prev, *next;
388};
389
390/* Storage for the (global) tests to be run. */
391static struct __test_metadata *__test_list = NULL;
392static unsigned int __test_count = 0;
393static unsigned int __fixture_count = 0;
394
395/*
396 * Since constructors are called in reverse order, reverse the test
397 * list so tests are run in source declaration order.
398 * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
399 */
400static inline void __register_test(struct __test_metadata *t) {
401  __test_count++;
402  /* Circular linked list where only prev is circular. */
403  if (__test_list == NULL) {
404    __test_list = t;
405    t->next = NULL;
406    t->prev = t;
407    return;
408  }
409  t->next = __test_list;
410  t->next->prev = t;
411  t->prev = t;
412  __test_list = t;
413}
414
415static inline int __bail(int for_realz) {
416  if (for_realz)
417    abort();
418  return 0;
419}
420
421static int test_harness_run(int __attribute__((unused)) argc,
422                            char __attribute__((unused)) **argv) {
423  struct __test_metadata *t;
424  int ret = 0;
425  unsigned int count = 0;
426  unsigned int pass_count = 0;
427
428  /* TODO(wad) add optional arguments similar to gtest. */
429  printf("[==========] Running %u tests from %u test cases.\n",
430          __test_count, __fixture_count + 1);
431  for (t = __test_list; t; t = t->next) {
432    pid_t child_pid;
433    int status;
434    count++;
435    t->passed = 1;
436    t->trigger = 0;
437    printf("[ RUN      ] %s\n", t->name);
438    child_pid = fork();
439    if (child_pid < 0) {
440      printf("ERROR SPAWNING TEST CHILD\n");
441      t->passed = 0;
442    } else if (child_pid == 0) {
443      t->fn(t);
444      _exit(t->passed);
445    } else {
446      /* TODO(wad) add timeout support. */
447      waitpid(child_pid, &status, 0);
448      if (WIFEXITED(status)) {
449        t->passed = t->termsig == -1 ? WEXITSTATUS(status) : 0;
450        if (t->termsig != -1) {
451         fprintf(TH_LOG_STREAM,
452                  "%s: Test exited normally instead of by signal (code: %d)\n",
453                 t->name,
454                 WEXITSTATUS(status));
455        }
456      } else if (WIFSIGNALED(status)) {
457        t->passed = 0;
458        if (WTERMSIG(status) == SIGABRT) {
459          fprintf(TH_LOG_STREAM,
460                  "%s: Test terminated by assertion\n",
461                 t->name);
462        } else if (WTERMSIG(status) == t->termsig) {
463          t->passed = 1;
464        } else {
465          fprintf(TH_LOG_STREAM,
466                  "%s: Test terminated unexpectedly by signal %d\n",
467                 t->name,
468                 WTERMSIG(status));
469        }
470      } else {
471          fprintf(TH_LOG_STREAM,
472                  "%s: Test ended in some other way [%u]\n",
473                 t->name,
474                 status);
475      }
476    }
477    printf("[     %4s ] %s\n", (t->passed ? "OK" : "FAIL"), t->name);
478    if (t->passed)
479      pass_count++;
480    else
481      ret = 1;
482  }
483  /* TODO(wad) organize by fixtures since ordering is not guaranteed now. */
484  printf("[==========] %u / %u tests passed.\n", pass_count, count);
485  printf("[  %s  ]\n", (ret ? "FAILED" : "PASSED"));
486  return ret;
487}
488
489#endif  /* TEST_HARNESS_H_ */
490