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