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