1 /* Copyright (c) 2011 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 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/types.h>
51 #include <sys/wait.h>
52 #include <unistd.h>
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 /* FIXTURE(datatype name) {
72 * type property1;
73 * ...
74 * };
75 * Defines the data provided to TEST_F()-defined tests as |self|. It should be
76 * populated and cleaned up using FIXTURE_SETUP and FIXTURE_TEARDOWN.
77 */
78 #define FIXTURE TEST_API(FIXTURE)
79
80 /* FIXTURE_DATA(datatype name)
81 * This call may be used when the type of the fixture data
82 * is needed. In general, this should not be needed unless
83 * the |self| is being passed to a helper directly.
84 */
85 #define FIXTURE_DATA TEST_API(FIXTURE_DATA)
86
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
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
108 /* TEST_F(fixture, name) { implementation }
109 * Defines a test that depends on a fixture (e.g., is part of a test case).
110 * Very similar to TEST() except that |self| is the setup instance of fixture's
111 * datatype exposed for use by the implementation.
112 */
113 #define TEST_F TEST_API(TEST_F)
114
115 /* Use once to append a main() to the test file. E.g.,
116 * TEST_HARNESS_MAIN
117 */
118 #define TEST_HARNESS_MAIN TEST_API(TEST_HARNESS_MAIN)
119
120 /*
121 * Operators for use in TEST and TEST_F.
122 * ASSERT_* calls will stop test execution immediately.
123 * EXPECT_* calls will emit a failure warning, note it, and continue.
124 */
125
126 /* ASSERT_EQ(expected, measured): expected == measured */
127 #define ASSERT_EQ TEST_API(ASSERT_EQ)
128 /* ASSERT_NE(expected, measured): expected != measured */
129 #define ASSERT_NE TEST_API(ASSERT_NE)
130 /* ASSERT_LT(expected, measured): expected < measured */
131 #define ASSERT_LT TEST_API(ASSERT_LT)
132 /* ASSERT_LE(expected, measured): expected <= measured */
133 #define ASSERT_LE TEST_API(ASSERT_LE)
134 /* ASSERT_GT(expected, measured): expected > measured */
135 #define ASSERT_GT TEST_API(ASSERT_GT)
136 /* ASSERT_GE(expected, measured): expected >= measured */
137 #define ASSERT_GE TEST_API(ASSERT_GE)
138 /* ASSERT_NULL(measured): NULL == measured */
139 #define ASSERT_NULL TEST_API(ASSERT_NULL)
140 /* ASSERT_TRUE(measured): measured != 0 */
141 #define ASSERT_TRUE TEST_API(ASSERT_TRUE)
142 /* ASSERT_FALSE(measured): measured == 0 */
143 #define ASSERT_FALSE TEST_API(ASSERT_FALSE)
144 /* ASSERT_STREQ(expected, measured): !strcmp(expected, measured) */
145 #define ASSERT_STREQ TEST_API(ASSERT_STREQ)
146 /* ASSERT_STRNE(expected, measured): strcmp(expected, measured) */
147 #define ASSERT_STRNE TEST_API(ASSERT_STRNE)
148 /* EXPECT_EQ(expected, measured): expected == measured */
149 #define EXPECT_EQ TEST_API(EXPECT_EQ)
150 /* EXPECT_NE(expected, measured): expected != measured */
151 #define EXPECT_NE TEST_API(EXPECT_NE)
152 /* EXPECT_LT(expected, measured): expected < measured */
153 #define EXPECT_LT TEST_API(EXPECT_LT)
154 /* EXPECT_LE(expected, measured): expected <= measured */
155 #define EXPECT_LE TEST_API(EXPECT_LE)
156 /* EXPECT_GT(expected, measured): expected > measured */
157 #define EXPECT_GT TEST_API(EXPECT_GT)
158 /* EXPECT_GE(expected, measured): expected >= measured */
159 #define EXPECT_GE TEST_API(EXPECT_GE)
160 /* EXPECT_NULL(measured): NULL == measured */
161 #define EXPECT_NULL TEST_API(EXPECT_NULL)
162 /* EXPECT_TRUE(measured): 0 != measured */
163 #define EXPECT_TRUE TEST_API(EXPECT_TRUE)
164 /* EXPECT_FALSE(measured): 0 == measured */
165 #define EXPECT_FALSE TEST_API(EXPECT_FALSE)
166 /* EXPECT_STREQ(expected, measured): !strcmp(expected, measured) */
167 #define EXPECT_STREQ TEST_API(EXPECT_STREQ)
168 /* EXPECT_STRNE(expected, measured): strcmp(expected, measured) */
169 #define EXPECT_STRNE TEST_API(EXPECT_STRNE)
170
171 /* TH_LOG(format, ...)
172 * Optional debug logging function available for use in tests.
173 * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
174 * E.g., #define TH_LOG_ENABLED 1
175 * If no definition is provided, logging is enabled by default.
176 */
177 #define TH_LOG TEST_API(TH_LOG)
178
179 /*
180 * Internal implementation.
181 *
182 */
183
184 /* Utilities exposed to the test definitions */
185 #ifndef TH_LOG_STREAM
186 # define TH_LOG_STREAM stderr
187 #endif
188
189 #ifndef TH_LOG_ENABLED
190 # define TH_LOG_ENABLED 1
191 #endif
192
193 #define _TH_LOG(fmt, ...) do { \
194 if (TH_LOG_ENABLED) \
195 __TH_LOG(fmt, ##__VA_ARGS__); \
196 } while (0)
197
198 /* Unconditional logger for internal use. */
199 #define __TH_LOG(fmt, ...) \
200 fprintf(TH_LOG_STREAM, "%s:%d:%s:" fmt "\n", \
201 __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
202
203 /* Defines the test function and creates the registration stub. */
204 #define _TEST(test_name) \
205 static void test_name(struct __test_metadata *_metadata); \
206 static struct __test_metadata _##test_name##_object = \
207 { .name = "global." #test_name, .fn = &test_name }; \
208 static void __attribute__((constructor)) _register_##test_name(void) { \
209 __register_test(&_##test_name##_object); \
210 } \
211 static void test_name( \
212 struct __test_metadata __attribute__((unused)) *_metadata)
213
214 /* Wraps the struct name so we have one less argument to pass around. */
215 #define _FIXTURE_DATA(fixture_name) struct _test_data_##fixture_name
216
217 /* Called once per fixture to setup the data and register. */
218 #define _FIXTURE(fixture_name) \
219 static void __attribute__((constructor)) \
220 _register_##fixture_name##_data(void) { \
221 __fixture_count++; \
222 } \
223 _FIXTURE_DATA(fixture_name)
224
225 /* Prepares the setup function for the fixture. |_metadata| is included
226 * so that ASSERT_* work as a convenience.
227 */
228 #define _FIXTURE_SETUP(fixture_name) \
229 void fixture_name##_setup( \
230 struct __test_metadata __attribute__((unused)) *_metadata, \
231 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
232 #define _FIXTURE_TEARDOWN(fixture_name) \
233 void fixture_name##_teardown( \
234 struct __test_metadata __attribute__((unused)) *_metadata, \
235 _FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
236
237 /* Emits test registration and helpers for fixture-based test
238 * cases.
239 * TODO(wad) register fixtures on dedicated test lists.
240 */
241 #define _TEST_F(fixture_name, test_name) \
242 static void fixture_name##_##test_name( \
243 struct __test_metadata *_metadata, \
244 _FIXTURE_DATA(fixture_name) *self); \
245 static inline void wrapper_##fixture_name##_##test_name( \
246 struct __test_metadata *_metadata) { \
247 /* fixture data is allocated, setup, and torn down per call. */ \
248 _FIXTURE_DATA(fixture_name) self; \
249 memset(&self, 0, sizeof(_FIXTURE_DATA(fixture_name))); \
250 fixture_name##_setup(_metadata, &self); \
251 /* Let setup failure terminate early. */ \
252 if (!_metadata->passed) return; \
253 fixture_name##_##test_name(_metadata, &self); \
254 fixture_name##_teardown(_metadata, &self); \
255 } \
256 static struct __test_metadata _##fixture_name##_##test_name##_object = { \
257 .name = #fixture_name "." #test_name, \
258 .fn = &wrapper_##fixture_name##_##test_name, \
259 }; \
260 static void __attribute__((constructor)) \
261 _register_##fixture_name##_##test_name(void) { \
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
268 /* Exports a simple wrapper to run the test harness. */
269 #define _TEST_HARNESS_MAIN \
270 int main(int argc, char **argv) { return test_harness_run(argc, argv); }
271
272 #define _ASSERT_EQ(_expected, _seen) \
273 __EXPECT(_expected, _seen, ==, 1)
274 #define _ASSERT_NE(_expected, _seen) \
275 __EXPECT(_expected, _seen, !=, 1)
276 #define _ASSERT_LT(_expected, _seen) \
277 __EXPECT(_expected, _seen, <, 1)
278 #define _ASSERT_LE(_expected, _seen) \
279 __EXPECT(_expected, _seen, <=, 1)
280 #define _ASSERT_GT(_expected, _seen) \
281 __EXPECT(_expected, _seen, >, 1)
282 #define _ASSERT_GE(_expected, _seen) \
283 __EXPECT(_expected, _seen, >=, 1)
284 #define _ASSERT_NULL(_seen) \
285 __EXPECT(NULL, _seen, ==, 1)
286
287 #define _ASSERT_TRUE(_seen) \
288 _ASSERT_NE(0, _seen)
289 #define _ASSERT_FALSE(_seen) \
290 _ASSERT_EQ(0, _seen)
291 #define _ASSERT_STREQ(_expected, _seen) \
292 __EXPECT_STR(_expected, _seen, ==, 1)
293 #define _ASSERT_STRNE(_expected, _seen) \
294 __EXPECT_STR(_expected, _seen, !=, 1)
295
296 #define _EXPECT_EQ(_expected, _seen) \
297 __EXPECT(_expected, _seen, ==, 0)
298 #define _EXPECT_NE(_expected, _seen) \
299 __EXPECT(_expected, _seen, !=, 0)
300 #define _EXPECT_LT(_expected, _seen) \
301 __EXPECT(_expected, _seen, <, 0)
302 #define _EXPECT_LE(_expected, _seen) \
303 __EXPECT(_expected, _seen, <=, 0)
304 #define _EXPECT_GT(_expected, _seen) \
305 __EXPECT(_expected, _seen, >, 0)
306 #define _EXPECT_GE(_expected, _seen) \
307 __EXPECT(_expected, _seen, >=, 0)
308
309 #define _EXPECT_NULL(_seen) \
310 __EXPECT(NULL, _seen, ==, 0)
311 #define _EXPECT_TRUE(_seen) \
312 _EXPECT_NE(0, _seen)
313 #define _EXPECT_FALSE(_seen) \
314 _EXPECT_EQ(0, _seen)
315
316 #define _EXPECT_STREQ(_expected, _seen) \
317 __EXPECT_STR(_expected, _seen, ==, 0)
318 #define _EXPECT_STRNE(_expected, _seen) \
319 __EXPECT_STR(_expected, _seen, !=, 0)
320
321 /* Support an optional handler after and ASSERT_* or EXPECT_*. The approach is
322 * not thread-safe, but it should be fine in most sane test scenarios.
323 *
324 * Using __bail(), which optionally abort()s, is the easiest way to early
325 * return while still providing an optional block to the API consumer.
326 */
327 #define OPTIONAL_HANDLER(_assert) \
328 for (; _metadata->trigger; _metadata->trigger = __bail(_assert))
329
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
349 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
350 const char *__exp = (_expected); \
351 const char *__seen = (_seen); \
352 if (!(strcmp(__exp, __seen) _t 0)) { \
353 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
354 _metadata->passed = 0; \
355 _metadata->trigger = 1; \
356 } \
357 } while (0); OPTIONAL_HANDLER(_assert)
358
359 /* Contains all the information for test execution and status checking. */
360 struct __test_metadata
361 {
362 const char *name;
363 void (*fn) (struct __test_metadata *);
364 int passed;
365 int trigger; /* extra handler after the evaluation */
366 struct __test_metadata *prev, *next;
367 };
368
369 /* Storage for the (global) tests to be run. */
370 static struct __test_metadata *__test_list = NULL;
371 static unsigned int __test_count = 0;
372 static unsigned int __fixture_count = 0;
373
__register_test(struct __test_metadata * t)374 static inline void __register_test (struct __test_metadata *t)
375 {
376 __test_count++;
377 /* Circular linked list where only prev is circular. */
378 if (__test_list == NULL)
379 {
380 __test_list = t;
381 t->next = NULL;
382 t->prev = t;
383 return;
384 }
385 t->next = NULL;
386 t->prev = __test_list->prev;
387 t->prev->next = t;
388 __test_list->prev = t;
389 }
390
__bail(int for_realz)391 static inline int __bail (int for_realz)
392 {
393 if (for_realz)
394 abort();
395 return 0;
396 }
397
test_harness_run(int argc,char ** argv)398 static int test_harness_run (int __attribute__ ( (unused)) argc,
399 char __attribute__ ( (unused)) **argv)
400 {
401 struct __test_metadata *t;
402 int ret = 0;
403 unsigned int count = 0;
404 /* TODO(wad) add optional arguments similar to gtest. */
405 printf ("[==========] Running %u tests from %u test cases.\n",
406 __test_count, __fixture_count + 1);
407 for (t = __test_list; t; t = t->next)
408 {
409 pid_t child_pid;
410 int status;
411 count++;
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 {
418 printf ("ERROR SPAWNING TEST CHILD\n");
419 t->passed = 0;
420 }
421 else if (child_pid == 0)
422 {
423 t->fn (t);
424 _exit (t->passed);
425 }
426 else
427 {
428 /* TODO(wad) add timeout support. */
429 waitpid (child_pid, &status, 0);
430 if (WIFEXITED (status))
431 t->passed = WEXITSTATUS (status);
432 if (WIFSIGNALED (status))
433 {
434 t->passed = 0;
435 fprintf (TH_LOG_STREAM,
436 "%s: Test terminated unexpectedly by signal %d\n",
437 t->name,
438 WTERMSIG (status));
439 }
440 }
441 printf ("[ %4s ] %s\n", (t->passed ? "OK" : "FAIL"), t->name);
442 if (!t->passed)
443 ret = 1;
444 }
445 /* TODO(wad) organize by fixtures since ordering is not guaranteed now. */
446 printf ("[==========] %u tests ran.\n", count);
447 printf ("[ %s ]\n", (ret ? "FAILED" : "PASSED"));
448 return ret;
449 }
450
451 #endif /* TEST_HARNESS_H_ */
452