f025fe31330370a1f2f2945a47d5110b25f67110
[platform/upstream/glib.git] / glib / gtestframework.c
1 /* GLib testing framework examples
2  * Copyright (C) 2007 Tim Janik
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 #include "config.h"
20 #include "gtestframework.h"
21 #include "galias.h"
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <signal.h>
30 #ifdef HAVE_SYS_SELECT_H
31 #include <sys/select.h>
32 #endif /* HAVE_SYS_SELECT_H */
33
34 /* --- structures --- */
35 struct GTestCase
36 {
37   gchar  *name;
38   guint   fixture_size;
39   void (*fixture_setup) (void*);
40   void (*fixture_test) (void*);
41   void (*fixture_teardown) (void*);
42 };
43 struct GTestSuite
44 {
45   gchar  *name;
46   GSList *suites;
47   GSList *cases;
48 };
49 typedef struct DestroyEntry DestroyEntry;
50 struct DestroyEntry
51 {
52   DestroyEntry *next;
53   GDestroyNotify destroy_func;
54   gpointer       destroy_data;
55 };
56
57 /* --- prototypes --- */
58 static void                     test_run_seed           (const gchar *rseed);
59 static void                     test_trap_clear         (void);
60 static guint8*                  g_test_log_dump         (GTestLogMsg *msg,
61                                                          guint       *len);
62
63 /* --- variables --- */
64 static int         test_log_fd = -1;
65 static gboolean    test_mode_fatal = TRUE;
66 static gboolean    g_test_run_once = TRUE;
67 static gboolean    test_run_list = FALSE;
68 static gchar      *test_run_seedstr = NULL;
69 static GRand      *test_run_rand = NULL;
70 static gchar      *test_run_name = "";
71 static guint       test_run_forks = 0;
72 static guint       test_run_count = 0;
73 static guint       test_skip_count = 0;
74 static GTimer     *test_user_timer = NULL;
75 static double      test_user_stamp = 0;
76 static GSList     *test_paths = NULL;
77 static GTestSuite *test_suite_root = NULL;
78 static int         test_trap_last_status = 0;
79 static int         test_trap_last_pid = 0;
80 static char       *test_trap_last_stdout = NULL;
81 static char       *test_trap_last_stderr = NULL;
82 static char       *test_uri_base = NULL;
83 static gboolean    test_debug_log = FALSE;
84 static DestroyEntry *test_destroy_queue = NULL;
85 const GTestConfig *g_test_config_vars = NULL;
86 static GTestConfig mutable_test_config_vars = {
87   TRUE,         /* test_quick */
88   FALSE,        /* test_perf */
89   FALSE,        /* test_verbose */
90   FALSE,        /* test_quiet */
91 };
92
93 /* --- functions --- */
94 const char*
95 g_test_log_type_name (GTestLogType log_type)
96 {
97   switch (log_type)
98     {
99     case G_TEST_LOG_NONE:               return "none";
100     case G_TEST_LOG_ERROR:              return "error";
101     case G_TEST_LOG_START_BINARY:       return "binary";
102     case G_TEST_LOG_LIST_CASE:          return "list";
103     case G_TEST_LOG_SKIP_CASE:          return "skip";
104     case G_TEST_LOG_START_CASE:         return "start";
105     case G_TEST_LOG_STOP_CASE:          return "stop";
106     case G_TEST_LOG_MIN_RESULT:         return "minperf";
107     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
108     case G_TEST_LOG_MESSAGE:            return "message";
109     }
110   return "???";
111 }
112
113 static void
114 g_test_log_send (guint         n_bytes,
115                  const guint8 *buffer)
116 {
117   if (test_log_fd >= 0)
118     {
119       int r;
120       do
121         r = write (test_log_fd, buffer, n_bytes);
122       while (r < 0 && errno == EINTR);
123     }
124   if (test_debug_log)
125     {
126       GTestLogBuffer *lbuffer = g_test_log_buffer_new();
127       GTestLogMsg *msg;
128       guint ui;
129       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
130       msg = g_test_log_buffer_pop (lbuffer);
131       g_assert (msg != NULL); // FIXME: should be g_awrn_if_fail
132       g_assert (lbuffer->data->len == 0); // FIXME: should be g_awrn_if_fail
133       g_test_log_buffer_free (lbuffer);
134       /* print message */
135       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
136       for (ui = 0; ui < msg->n_strings; ui++)
137         g_printerr (":{%s}", msg->strings[ui]);
138       if (msg->n_nums)
139         {
140           g_printerr (":(");
141           for (ui = 0; ui < msg->n_nums; ui++)
142             g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
143           g_printerr (")");
144         }
145       g_printerr (":LOG*}\n");
146       g_test_log_msg_free (msg);
147     }
148 }
149
150 static void
151 g_test_log (GTestLogType lbit,
152             const gchar *string1,
153             const gchar *string2,
154             guint        n_args,
155             long double *largs)
156 {
157   gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
158   GTestLogMsg msg;
159   gchar *astrings[3] = { NULL, NULL, NULL };
160   guint8 *dbuffer;
161   guint32 dbufferlen;
162
163   switch (lbit)
164     {
165     case G_TEST_LOG_STOP_CASE:
166       if (!g_test_quiet())
167         g_print ("%s\n", fail ? "FAIL" : "OK");
168       if (fail && test_mode_fatal)
169         abort();
170       break;
171     case G_TEST_LOG_MIN_RESULT:
172       if (g_test_verbose())
173         g_print ("(MINPERF:%s)\n", string1);
174       break;
175     case G_TEST_LOG_MAX_RESULT:
176       if (g_test_verbose())
177         g_print ("(MAXPERF:%s)\n", string1);
178       break;
179     case G_TEST_LOG_MESSAGE:
180       if (g_test_verbose())
181         g_print ("(MSG: %s)\n", string1);
182       break;
183     default: ;
184     }
185
186   msg.log_type = lbit;
187   msg.n_strings = (string1 != NULL) + (string1 && string2);
188   msg.strings = astrings;
189   astrings[0] = (gchar*) string1;
190   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
191   msg.n_nums = n_args;
192   msg.nums = largs;
193   dbuffer = g_test_log_dump (&msg, &dbufferlen);
194   g_test_log_send (dbufferlen, dbuffer);
195   g_free (dbuffer);
196
197   switch (lbit)
198     {
199     case G_TEST_LOG_START_CASE:
200       if (!g_test_quiet())
201         g_print ("%s: ", string1);
202       break;
203     default: ;
204     }
205 }
206
207 static void
208 parse_args (gint    *argc_p,
209             gchar ***argv_p)
210 {
211   guint argc = *argc_p;
212   gchar **argv = *argv_p;
213   guint i, e;
214   /* parse known args */
215   for (i = 1; i < argc; i++)
216     {
217       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
218         {
219           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
220           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
221           g_log_set_always_fatal (fatal_mask);
222           argv[i] = NULL;
223         }
224       else if (strcmp (argv[i], "--keep-going") == 0 ||
225                strcmp (argv[i], "-k") == 0)
226         {
227           test_mode_fatal = FALSE;
228           argv[i] = NULL;
229         }
230       else if (strcmp (argv[i], "--debug-log") == 0)
231         {
232           test_debug_log = TRUE;
233           argv[i] = NULL;
234         }
235       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
236         {
237           gchar *equal = argv[i] + 12;
238           if (*equal == '=')
239             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
240           else if (i + 1 < argc)
241             {
242               argv[i++] = NULL;
243               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
244             }
245           argv[i] = NULL;
246         }
247       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
248         {
249           gchar *equal = argv[i] + 16;
250           if (*equal == '=')
251             test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
252           else if (i + 1 < argc)
253             {
254               argv[i++] = NULL;
255               test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
256             }
257           argv[i] = NULL;
258         }
259       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
260         {
261           gchar *equal = argv[i] + 2;
262           if (*equal == '=')
263             test_paths = g_slist_prepend (test_paths, equal + 1);
264           else if (i + 1 < argc)
265             {
266               argv[i++] = NULL;
267               test_paths = g_slist_prepend (test_paths, argv[i]);
268             }
269           argv[i] = NULL;
270         }
271       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
272         {
273           gchar *equal = argv[i] + 2;
274           const gchar *mode = "";
275           if (*equal == '=')
276             mode = equal + 1;
277           else if (i + 1 < argc)
278             {
279               argv[i++] = NULL;
280               mode = argv[i];
281             }
282           if (strcmp (mode, "perf") == 0)
283             mutable_test_config_vars.test_perf = TRUE;
284           else if (strcmp (mode, "slow") == 0)
285             mutable_test_config_vars.test_quick = FALSE;
286           else if (strcmp (mode, "quick") == 0)
287             {
288               mutable_test_config_vars.test_quick = TRUE;
289               mutable_test_config_vars.test_perf = FALSE;
290             }
291           else
292             g_error ("unknown test mode: -m %s", mode);
293           argv[i] = NULL;
294         }
295       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
296         {
297           mutable_test_config_vars.test_quiet = TRUE;
298           mutable_test_config_vars.test_verbose = FALSE;
299           argv[i] = NULL;
300         }
301       else if (strcmp ("--verbose", argv[i]) == 0)
302         {
303           mutable_test_config_vars.test_quiet = FALSE;
304           mutable_test_config_vars.test_verbose = TRUE;
305           argv[i] = NULL;
306         }
307       else if (strcmp ("-l", argv[i]) == 0)
308         {
309           test_run_list = TRUE;
310           argv[i] = NULL;
311         }
312       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
313         {
314           gchar *equal = argv[i] + 6;
315           if (*equal == '=')
316             test_run_seedstr = equal + 1;
317           else if (i + 1 < argc)
318             {
319               argv[i++] = NULL;
320               test_run_seedstr = argv[i];
321             }
322           argv[i] = NULL;
323         }
324     }
325   /* collapse argv */
326   e = 1;
327   for (i = 1; i < argc; i++)
328     if (argv[i])
329       {
330         argv[e++] = argv[i];
331         if (i >= e)
332           argv[i] = NULL;
333       }
334   *argc_p = e;
335 }
336
337 /**
338  * g_test_init:
339  * @argc: Address of the @argc parameter of the main() function.
340  *        Changed if any arguments were handled.
341  * @argv: Address of the @argv parameter of main().
342  *        Any parameters understood by g_test_init() stripped before return.
343  *
344  * Initialize the GLib testing framework, e.g. by seeding the
345  * test random number generator, the name for g_get_prgname()
346  * and parsing test related command line args.
347  * So far, the following arguments are understood:
348  * <informalexample>
349  * -l                   list test cases available in a test executable.
350  * --seed RANDOMSEED    provide a random seed to reproduce test runs using random numbers.
351  * --verbose            run tests verbosely.
352  * -q, --quiet          run tests quietly.
353  * -p TESTPATH          execute all tests matching TESTPATH.
354  * -m {perf|slow|quick} execute tests according to this test modes:
355  *                      perf - performance tests, may take long and report results.
356  *                      slow - slow and thorough tests, may take quite long and maximize coverage.
357  *                      quick - quick tests, should run really quickly and give good coverage.
358  * --debug-log          debug test logging output.
359  * -k, --keep-going     gtester specific argument.
360  * --GTestLogFD N       gtester specific argument.
361  * --GTestSkipCount N   gtester specific argument.
362  * </informalexample>
363  */
364 void
365 g_test_init (int    *argc,
366              char ***argv,
367              ...)
368 {
369   static char seedstr[4 + 4 * 8 + 1];
370   va_list args;
371   gpointer vararg1;
372   g_return_if_fail (argc != NULL);
373   g_return_if_fail (argv != NULL);
374   g_return_if_fail (g_test_config_vars == NULL);
375   g_test_config_vars = &mutable_test_config_vars;
376
377   va_start (args, argv);
378   vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
379   va_end (args);
380   g_return_if_fail (vararg1 == NULL);
381
382   /* setup random seed string */
383   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
384   test_run_seedstr = seedstr;
385
386   /* parse args, sets up mode, changes seed, etc. */
387   parse_args (argc, argv);
388   if (!g_get_prgname())
389     g_set_prgname ((*argv)[0]);
390
391   /* verify GRand reliability, needed for reliable seeds */
392   if (1)
393     {
394       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
395       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
396       // g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4);
397       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
398         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
399       g_rand_free (rg);
400     }
401
402   /* check rand seed */
403   test_run_seed (test_run_seedstr);
404
405   /* report program start */
406   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
407 }
408
409 static void
410 test_run_seed (const gchar *rseed)
411 {
412   guint seed_failed = 0;
413   if (test_run_rand)
414     g_rand_free (test_run_rand);
415   test_run_rand = NULL;
416   while (strchr (" \t\v\r\n\f", *rseed))
417     rseed++;
418   if (strncmp (rseed, "R02S", 4) == 0)  // seed for random generator 02 (GRand-2.2)
419     {
420       const char *s = rseed + 4;
421       if (strlen (s) >= 32)             // require 4 * 8 chars
422         {
423           guint32 seedarray[4];
424           gchar *p, hexbuf[9] = { 0, };
425           memcpy (hexbuf, s + 0, 8);
426           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
427           seed_failed += p != NULL && *p != 0;
428           memcpy (hexbuf, s + 8, 8);
429           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
430           seed_failed += p != NULL && *p != 0;
431           memcpy (hexbuf, s + 16, 8);
432           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
433           seed_failed += p != NULL && *p != 0;
434           memcpy (hexbuf, s + 24, 8);
435           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
436           seed_failed += p != NULL && *p != 0;
437           if (!seed_failed)
438             {
439               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
440               return;
441             }
442         }
443     }
444   g_error ("Unknown or invalid random seed: %s", rseed);
445 }
446
447 /**
448  * g_test_rand_int:
449  *
450  * Get a reproducable random integer number.
451  * The random numbers generate by the g_test_rand_*() family of functions
452  * change with every new test program start, unless the --seed option is
453  * given when starting test programs.
454  * For individual test cases however, the random number generator is
455  * reseeded, to avoid dependencies between tests and to make --seed
456  * effective for all test cases.
457  *
458  * Returns: a random number from the seeded random number generator.
459  */
460 gint32
461 g_test_rand_int (void)
462 {
463   return g_rand_int (test_run_rand);
464 }
465
466 /**
467  * g_test_rand_int_range:
468  * @begin: the minimum value returned by this function
469  * @end:   the smallest value not to be returned by this function
470  *
471  * Get a reproducable random integer number out of a specified range,
472  * see g_test_rand_int() for details on test case random numbers.
473  *
474  * Returns a number with @begin <= number < @end.
475  */
476 gint32
477 g_test_rand_int_range (gint32          begin,
478                        gint32          end)
479 {
480   return g_rand_int_range (test_run_rand, begin, end);
481 }
482
483 /**
484  * g_test_rand_double:
485  *
486  * Get a reproducable random floating point number,
487  * see g_test_rand_int() for details on test case random numbers.
488  *
489  * Return a random number from the seeded random number generator.
490  */
491 double
492 g_test_rand_double (void)
493 {
494   return g_rand_double (test_run_rand);
495 }
496
497 /**
498  * g_test_rand_double_range:
499  * @range_start: the minimum value returned by this function
500  * @range_end: the minimum value not returned by this function
501  *
502  * Get a reproducable random floating pointer number out of a specified range,
503  * see g_test_rand_int() for details on test case random numbers.
504  *
505  * Returns a number with @range_start <= number < @range_end.
506  */
507 double
508 g_test_rand_double_range (double          range_start,
509                           double          range_end)
510 {
511   return g_rand_double_range (test_run_rand, range_start, range_end);
512 }
513
514 /**
515  * g_test_timer_start:
516  *
517  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
518  * to be done. Call this function again to restart the timer.
519  */
520 void
521 g_test_timer_start (void)
522 {
523   if (!test_user_timer)
524     test_user_timer = g_timer_new();
525   test_user_stamp = 0;
526   g_timer_start (test_user_timer);
527 }
528
529 /**
530  * g_test_timer_elapsed:
531  *
532  * Get the time since the last start of the timer with g_test_timer_start().
533  */
534 double
535 g_test_timer_elapsed (void)
536 {
537   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
538   return test_user_stamp;
539 }
540
541 /**
542  * g_test_timer_last:
543  *
544  * Report the last result of g_test_timer_elapsed().
545  */
546 double
547 g_test_timer_last (void)
548 {
549   return test_user_stamp;
550 }
551
552 /**
553  * g_test_minimized_result:
554  * @minimized_quantity: the reported value
555  * @format: the format string of the report message
556  *
557  * Report the result of a performance or measurement test.
558  * The test should generally strive to minimize the reported
559  * quantities (smaller values are better than larger ones),
560  * this and @minimized_quantity can determine sorting
561  * order for test result reports.
562  */
563 void
564 g_test_minimized_result (double          minimized_quantity,
565                          const char     *format,
566                          ...)
567 {
568   long double largs = minimized_quantity;
569   gchar *buffer;
570   va_list args;
571   va_start (args, format);
572   buffer = g_strdup_vprintf (format, args);
573   va_end (args);
574   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
575   g_free (buffer);
576 }
577
578 /**
579  * g_test_minimized_result:
580  * @maximized_quantity: the reported value
581  * @format: the format string of the report message
582  *
583  * Report the result of a performance or measurement test.
584  * The test should generally strive to maximize the reported
585  * quantities (larger values are better than smaller ones),
586  * this and @maximized_quantity can determine sorting
587  * order for test result reports.
588  */
589 void
590 g_test_maximized_result (double          maximized_quantity,
591                          const char     *format,
592                          ...)
593 {
594   long double largs = maximized_quantity;
595   gchar *buffer;
596   va_list args;
597   va_start (args, format);
598   buffer = g_strdup_vprintf (format, args);
599   va_end (args);
600   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
601   g_free (buffer);
602 }
603
604 /**
605  * g_test_message:
606  * @format: the format string
607  * @...:    printf-like arguments to @format
608  *
609  * Add a message to the test report.
610  */
611 void
612 g_test_message (const char *format,
613                 ...)
614 {
615   gchar *buffer;
616   va_list args;
617   va_start (args, format);
618   buffer = g_strdup_vprintf (format, args);
619   va_end (args);
620   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
621   g_free (buffer);
622 }
623
624 /**
625  * g_test_bug_base:
626  * @uri_pattern: the base pattern for bug URIs
627  *
628  * Specify the base URI for bug reports.
629  * The base URI is used to construct bug report messages for
630  * g_test_message() when g_test_bug() is called.
631  * Calling this function outside of a test case sets the
632  * default base URI for all test cases. Calling it from within
633  * a test case changes the base URI for the scope of the test
634  * case only.
635  * Bug URIs are constructed by appending a bug specific URI
636  * portion to @uri_pattern, or by replacing the special string
637  * '%s' within @uri_pattern if that is present.
638  */
639 void
640 g_test_bug_base (const char *uri_pattern)
641 {
642   g_free (test_uri_base);
643   test_uri_base = g_strdup (uri_pattern);
644 }
645
646 /**
647  * g_test_bug:
648  * @bug_uri_snippet: Bug specific bug tracker URI portion.
649  *
650  * This function adds a message to test reports that
651  * associates a bug URI with a test case.
652  * Bug URIs are constructed from a base URI set with g_test_bug_base()
653  * and @bug_uri_snippet.
654  */
655 void
656 g_test_bug (const char *bug_uri_snippet)
657 {
658   char *c;
659   g_return_if_fail (test_uri_base != NULL);
660   g_return_if_fail (bug_uri_snippet != NULL);
661   c = strstr (test_uri_base, "%s");
662   if (c)
663     {
664       char *b = g_strndup (test_uri_base, c - test_uri_base);
665       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
666       g_free (b);
667       g_test_message ("Bug Reference: %s", s);
668       g_free (s);
669     }
670   else
671     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
672 }
673
674 /**
675  * g_test_get_root:
676  *
677  * Get the toplevel test suite for the test path API.
678  *
679  * Returns: the toplevel #GTestSuite
680  */
681 GTestSuite*
682 g_test_get_root (void)
683 {
684   if (!test_suite_root)
685     {
686       test_suite_root = g_test_create_suite ("root");
687       g_free (test_suite_root->name);
688       test_suite_root->name = g_strdup ("");
689     }
690   return test_suite_root;
691 }
692
693 /**
694  * g_test_run:
695  *
696  * Runs all tests under the toplevel suite which can be retrieved
697  * with g_test_get_root(). Similar to g_test_run_suite(), the test
698  * cases to be run are filtered according to
699  * test path arguments (-p <testpath>) as parsed by g_test_init().
700  * g_test_run_suite() or g_test_run() may only be called once
701  * in a program.
702  */
703 int
704 g_test_run (void)
705 {
706   return g_test_run_suite (g_test_get_root());
707 }
708
709 /**
710  * g_test_create_case:
711  * @test_name:     the name for the test case
712  * @data_size:     the size of the fixture data structure
713  * @data_setup:    the function to set up the fixture data
714  * @data_test:     the actual test function
715  * @data_teardown: the function to teardown the fixture data
716  *
717  * Create a new #GTestCase, named @test_name, this API is fairly
718  * low level, calling g_test_add() or g_test_add_func() is preferable.
719  * When this test is executed, a fixture structure of size @data_size
720  * will be allocated and filled with 0s. Then data_setup() is called
721  * to initialize the fixture. After fixture setup, the actual test
722  * function data_test() is called. Once the test run completed, the
723  * fixture structure is torn down  by calling data_teardown() and
724  * after that the memory is released.
725  * Splitting up a test run into fixture setup, test function and
726  * fixture teardown is most usful if the same fixture is used for
727  * multiple tests. In this cases, g_test_create_case() will be
728  * called with the same fixture, but varying @test_name and
729  * @data_test arguments.
730  *
731  * Returns a newly allocated #GTestCase.
732  */
733 GTestCase*
734 g_test_create_case (const char     *test_name,
735                     gsize           data_size,
736                     void          (*data_setup) (void),
737                     void          (*data_test) (void),
738                     void          (*data_teardown) (void))
739 {
740   g_return_val_if_fail (test_name != NULL, NULL);
741   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
742   g_return_val_if_fail (test_name[0] != 0, NULL);
743   g_return_val_if_fail (data_test != NULL, NULL);
744   GTestCase *tc = g_slice_new0 (GTestCase);
745   tc->name = g_strdup (test_name);
746   tc->fixture_size = data_size;
747   tc->fixture_setup = (void*) data_setup;
748   tc->fixture_test = (void*) data_test;
749   tc->fixture_teardown = (void*) data_teardown;
750   return tc;
751 }
752
753 void
754 g_test_add_vtable (const char     *testpath,
755                    gsize           data_size,
756                    void          (*data_setup)    (void),
757                    void          (*fixture_test_func) (void),
758                    void          (*data_teardown) (void))
759 {
760   gchar **segments;
761   guint ui;
762   GTestSuite *suite;
763
764   g_return_if_fail (testpath != NULL);
765   g_return_if_fail (testpath[0] == '/');
766   g_return_if_fail (fixture_test_func != NULL);
767
768   suite = g_test_get_root();
769   segments = g_strsplit (testpath, "/", -1);
770   for (ui = 0; segments[ui] != NULL; ui++)
771     {
772       const char *seg = segments[ui];
773       gboolean islast = segments[ui + 1] == NULL;
774       if (islast && !seg[0])
775         g_error ("invalid test case path: %s", testpath);
776       else if (!seg[0])
777         continue;       // initial or duplicate slash
778       else if (!islast)
779         {
780           GTestSuite *csuite = g_test_create_suite (seg);
781           g_test_suite_add_suite (suite, csuite);
782           suite = csuite;
783         }
784       else /* islast */
785         {
786           GTestCase *tc = g_test_create_case (seg, data_size, data_setup, fixture_test_func, data_teardown);
787           g_test_suite_add (suite, tc);
788         }
789     }
790   g_strfreev (segments);
791 }
792
793 /**
794  * g_test_add_func:
795  * @testpath:   Slash seperated test case path name for the test.
796  * @test_func:  The test function to invoke for this test.
797  *
798  * Create a new test case, similar to g_test_create_case(). However
799  * the test is assumed to use no fixture, and test suites are automatically
800  * created on the fly and added to the root fixture, based on the
801  * slash seperated portions of @testpath.
802  */
803 void
804 g_test_add_func (const char     *testpath,
805                  void          (*test_func) (void))
806 {
807   g_return_if_fail (testpath != NULL);
808   g_return_if_fail (testpath[0] == '/');
809   g_return_if_fail (test_func != NULL);
810   g_test_add_vtable (testpath, 0, NULL, test_func, NULL);
811 }
812
813 /**
814  * g_test_create_suite:
815  * @suite_name: a name for the suite
816  *
817  * Create a new test suite with the name @suite_name.
818  *
819  * Returns: A newly allocated #GTestSuite instance.
820  */
821 GTestSuite*
822 g_test_create_suite (const char *suite_name)
823 {
824   g_return_val_if_fail (suite_name != NULL, NULL);
825   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
826   g_return_val_if_fail (suite_name[0] != 0, NULL);
827   GTestSuite *ts = g_slice_new0 (GTestSuite);
828   ts->name = g_strdup (suite_name);
829   return ts;
830 }
831
832 /**
833  * g_test_suite_add:
834  * @suite: a #GTestSuite
835  * @test_case: a #GTestCase
836  *
837  * Adds @test_case to @suite.
838  */
839 void
840 g_test_suite_add (GTestSuite     *suite,
841                   GTestCase      *test_case)
842 {
843   g_return_if_fail (suite != NULL);
844   g_return_if_fail (test_case != NULL);
845   suite->cases = g_slist_prepend (suite->cases, test_case);
846 }
847
848 /**
849  * g_test_suite_add_suite:
850  * @suite:       a #GTestSuite
851  * @nestedsuite: another #GTestSuite
852  *
853  * Adds @nestedsuite to @suite.
854  */
855 void
856 g_test_suite_add_suite (GTestSuite     *suite,
857                         GTestSuite     *nestedsuite)
858 {
859   g_return_if_fail (suite != NULL);
860   g_return_if_fail (nestedsuite != NULL);
861   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
862 }
863
864 /**
865  * g_test_queue_free:
866  * @gfree_pointer: the pointer to be stored.
867  *
868  * Enqueue a pointer to be released with g_free() during the next
869  * teardown phase. This is equivalent to calling g_test_queue_destroy()
870  * with a destroy callback of g_free().
871  */
872 void
873 g_test_queue_free (gpointer gfree_pointer)
874 {
875   if (gfree_pointer)
876     g_test_queue_destroy (g_free, gfree_pointer);
877 }
878
879 /**
880  * g_test_queue_destroy:
881  * @destroy_func:       Destroy callback for teardown phase.
882  * @destroy_data:       Destroy callback data.
883  *
884  * This function enqueus a callback @destroy_func() to be executed
885  * during the next test case teardown phase. This is most useful
886  * to auto destruct allocted test resources at the end of a test run.
887  * Resources are released in reverse queue order, that means enqueueing
888  * callback A before callback B will cause B() to be called before
889  * A() during teardown.
890  */
891 void
892 g_test_queue_destroy (GDestroyNotify destroy_func,
893                       gpointer       destroy_data)
894 {
895   DestroyEntry *dentry;
896   g_return_if_fail (destroy_func != NULL);
897   dentry = g_slice_new0 (DestroyEntry);
898   dentry->destroy_func = destroy_func;
899   dentry->destroy_data = destroy_data;
900   dentry->next = test_destroy_queue;
901   test_destroy_queue = dentry;
902 }
903
904 static int
905 test_case_run (GTestCase *tc)
906 {
907   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
908   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
909   if (++test_run_count <= test_skip_count)
910     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
911   else if (test_run_list)
912     {
913       g_print ("%s\n", test_run_name);
914       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
915     }
916   else
917     {
918       GTimer *test_run_timer = g_timer_new();
919       long double largs[3];
920       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
921       test_run_forks = 0;
922       g_timer_start (test_run_timer);
923       void *fixture = g_malloc0 (tc->fixture_size);
924       test_run_seed (test_run_seedstr);
925       if (tc->fixture_setup)
926         tc->fixture_setup (fixture);
927       tc->fixture_test (fixture);
928       test_trap_clear();
929       while (test_destroy_queue)
930         {
931           DestroyEntry *dentry = test_destroy_queue;
932           test_destroy_queue = dentry->next;
933           dentry->destroy_func (dentry->destroy_data);
934           g_slice_free (DestroyEntry, dentry);
935         }
936       if (tc->fixture_teardown)
937         tc->fixture_teardown (fixture);
938       g_free (fixture);
939       g_timer_stop (test_run_timer);
940       largs[0] = 0; // OK
941       largs[1] = test_run_forks;
942       largs[2] = g_timer_elapsed (test_run_timer, NULL);
943       g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
944       g_timer_destroy (test_run_timer);
945     }
946   g_free (test_run_name);
947   test_run_name = old_name;
948   g_free (test_uri_base);
949   test_uri_base = old_base;
950   return 0;
951 }
952
953 static int
954 g_test_run_suite_internal (GTestSuite *suite,
955                            const char *path)
956 {
957   guint n_bad = 0, n_good = 0, bad_suite = 0, l;
958   gchar *rest, *old_name = test_run_name;
959   GSList *slist, *reversed;
960   g_return_val_if_fail (suite != NULL, -1);
961   while (path[0] == '/')
962     path++;
963   l = strlen (path);
964   rest = strchr (path, '/');
965   l = rest ? MIN (l, rest - path) : l;
966   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
967   reversed = g_slist_reverse (g_slist_copy (suite->cases));
968   for (slist = reversed; slist; slist = slist->next)
969     {
970       GTestCase *tc = slist->data;
971       guint n = l ? strlen (tc->name) : 0;
972       if (l == n && strncmp (path, tc->name, n) == 0)
973         {
974           n_good++;
975           n_bad += test_case_run (tc) != 0;
976         }
977     }
978   g_slist_free (reversed);
979   reversed = g_slist_reverse (g_slist_copy (suite->suites));
980   for (slist = reversed; slist; slist = slist->next)
981     {
982       GTestSuite *ts = slist->data;
983       guint n = l ? strlen (ts->name) : 0;
984       if (l == n && strncmp (path, ts->name, n) == 0)
985         bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
986     }
987   g_slist_free (reversed);
988   g_free (test_run_name);
989   test_run_name = old_name;
990   return n_bad || bad_suite;
991 }
992
993 /**
994  * g_test_run_suite:
995  * @suite: a #GTestSuite
996  *
997  * Execute the tests within @suite and all nested #GTestSuites.
998  * The test suites to be executed are filtered according to
999  * test path arguments (-p <testpath>) as parsed by g_test_init().
1000  * g_test_run_suite() or g_test_run() may only be called once
1001  * in a program.
1002  */
1003 int
1004 g_test_run_suite (GTestSuite *suite)
1005 {
1006   guint n_bad = 0;
1007   g_return_val_if_fail (g_test_config_vars != NULL, -1);
1008   g_return_val_if_fail (g_test_run_once == TRUE, -1);
1009   g_test_run_once = FALSE;
1010   if (!test_paths)
1011     test_paths = g_slist_prepend (test_paths, "");
1012   while (test_paths)
1013     {
1014       const char *rest, *path = test_paths->data;
1015       guint l, n = strlen (suite->name);
1016       test_paths = g_slist_delete_link (test_paths, test_paths);
1017       while (path[0] == '/')
1018         path++;
1019       if (!n) /* root suite, run unconditionally */
1020         {
1021           n_bad += 0 != g_test_run_suite_internal (suite, path);
1022           continue;
1023         }
1024       /* regular suite, match path */
1025       rest = strchr (path, '/');
1026       l = strlen (path);
1027       l = rest ? MIN (l, rest - path) : l;
1028       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1029         n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
1030     }
1031   return n_bad;
1032 }
1033
1034 void
1035 g_assertion_message (const char     *domain,
1036                      const char     *file,
1037                      int             line,
1038                      const char     *func,
1039                      const char     *message)
1040 {
1041   char lstr[32];
1042   g_snprintf (lstr, 32, "%d", line);
1043   char *s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1044                          file, ":", lstr, ":",
1045                          func, func[0] ? ":" : "",
1046                          " ", message, NULL);
1047   g_printerr ("**\n** %s\n", s);
1048   g_free (s);
1049   abort();
1050 }
1051
1052 void
1053 g_assertion_message_expr (const char     *domain,
1054                           const char     *file,
1055                           int             line,
1056                           const char     *func,
1057                           const char     *expr)
1058 {
1059   char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1060   g_assertion_message (domain, file, line, func, s);
1061   g_free (s);
1062 }
1063
1064 void
1065 g_assertion_message_cmpnum (const char     *domain,
1066                             const char     *file,
1067                             int             line,
1068                             const char     *func,
1069                             const char     *expr,
1070                             long double     arg1,
1071                             const char     *cmp,
1072                             long double     arg2,
1073                             char            numtype)
1074 {
1075   char *s = NULL;
1076   switch (numtype)
1077     {
1078     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1079     case 'x':   s = g_strdup_printf ("assertion failed (%s): (0x%08Lx %s 0x%08Lx)", expr, (guint64) arg1, cmp, (guint64) arg2); break;
1080     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1081       /* ideally use: floats=%.7g double=%.17g */
1082     }
1083   g_assertion_message (domain, file, line, func, s);
1084   g_free (s);
1085 }
1086
1087 void
1088 g_assertion_message_cmpstr (const char     *domain,
1089                             const char     *file,
1090                             int             line,
1091                             const char     *func,
1092                             const char     *expr,
1093                             const char     *arg1,
1094                             const char     *cmp,
1095                             const char     *arg2)
1096 {
1097   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1098   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1099   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1100   g_free (t1);
1101   g_free (t2);
1102   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1103   g_free (a1);
1104   g_free (a2);
1105   g_assertion_message (domain, file, line, func, s);
1106   g_free (s);
1107 }
1108
1109 /**
1110  * g_strcmp0:
1111  * @str1: a C string or %NULL
1112  * @str2: another C string or %NULL
1113  *
1114  * Compares @str1 and @str2 like strcmp(). Handles %NULL strings gracefully.
1115  */
1116 int
1117 g_strcmp0 (const char     *str1,
1118            const char     *str2)
1119 {
1120   if (!str1)
1121     return -(str1 != str2);
1122   if (!str2)
1123     return str1 != str2;
1124   return strcmp (str1, str2);
1125 }
1126
1127 static int /* 0 on success */
1128 kill_child (int  pid,
1129             int *status,
1130             int  patience)
1131 {
1132   int wr;
1133   if (patience >= 3)    /* try graceful reap */
1134     {
1135       if (waitpid (pid, status, WNOHANG) > 0)
1136         return 0;
1137     }
1138   if (patience >= 2)    /* try SIGHUP */
1139     {
1140       kill (pid, SIGHUP);
1141       if (waitpid (pid, status, WNOHANG) > 0)
1142         return 0;
1143       g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1144       if (waitpid (pid, status, WNOHANG) > 0)
1145         return 0;
1146       g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1147       if (waitpid (pid, status, WNOHANG) > 0)
1148         return 0;
1149       g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1150       if (waitpid (pid, status, WNOHANG) > 0)
1151         return 0;
1152     }
1153   if (patience >= 1)    /* try SIGTERM */
1154     {
1155       kill (pid, SIGTERM);
1156       if (waitpid (pid, status, WNOHANG) > 0)
1157         return 0;
1158       g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1159       if (waitpid (pid, status, WNOHANG) > 0)
1160         return 0;
1161       g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1162       if (waitpid (pid, status, WNOHANG) > 0)
1163         return 0;
1164     }
1165   /* finish it off */
1166   kill (pid, SIGKILL);
1167   do
1168     wr = waitpid (pid, status, 0);
1169   while (wr < 0 && errno == EINTR);
1170   return wr;
1171 }
1172
1173 static inline int
1174 g_string_must_read (GString *gstring,
1175                     int      fd)
1176 {
1177 #define STRING_BUFFER_SIZE     4096
1178   char buf[STRING_BUFFER_SIZE];
1179   gssize bytes;
1180  again:
1181   bytes = read (fd, buf, sizeof (buf));
1182   if (bytes == 0)
1183     return 0; /* EOF, calling this function assumes data is available */
1184   else if (bytes > 0)
1185     {
1186       g_string_append_len (gstring, buf, bytes);
1187       return 1;
1188     }
1189   else if (bytes < 0 && errno == EINTR)
1190     goto again;
1191   else /* bytes < 0 */
1192     {
1193       g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1194       return 1; /* ignore error after warning */
1195     }
1196 }
1197
1198 static inline void
1199 g_string_write_out (GString *gstring,
1200                     int      outfd,
1201                     int     *stringpos)
1202 {
1203   if (*stringpos < gstring->len)
1204     {
1205       int r;
1206       do
1207         r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1208       while (r < 0 && errno == EINTR);
1209       *stringpos += MAX (r, 0);
1210     }
1211 }
1212
1213 static int
1214 sane_dup2 (int fd1,
1215            int fd2)
1216 {
1217   int ret;
1218   do
1219     ret = dup2 (fd1, fd2);
1220   while (ret < 0 && errno == EINTR);
1221   return ret;
1222 }
1223
1224 static void
1225 test_trap_clear (void)
1226 {
1227   test_trap_last_status = 0;
1228   test_trap_last_pid = 0;
1229   g_free (test_trap_last_stdout);
1230   test_trap_last_stdout = NULL;
1231   g_free (test_trap_last_stderr);
1232   test_trap_last_stderr = NULL;
1233 }
1234
1235 static guint64
1236 test_time_stamp (void)
1237 {
1238   GTimeVal tv;
1239   guint64 stamp;
1240   g_get_current_time (&tv);
1241   stamp = tv.tv_sec;
1242   stamp = stamp * 1000000 + tv.tv_usec;
1243   return stamp;
1244 }
1245
1246 /**
1247  * g_test_trap_fork:
1248  * @usec_timeout:    Timeout for the forked test in micro seconds.
1249  * @test_trap_flags: Flags to modify forking behaviour.
1250  *
1251  * Fork the current test program to execute a test case that might
1252  * not return or that might abort. The forked test case is aborted
1253  * and considered failing if its run time exceeds @usec_timeout.
1254  * The forking behavior can be configured with the following flags:
1255  * %G_TEST_TRAP_SILENCE_STDOUT - redirect stdout of the test child
1256  * to /dev/null so it cannot be observed on the console during test
1257  * runs. The actual output is still captured though to allow later
1258  * tests with g_test_trap_assert_stdout().
1259  * %G_TEST_TRAP_SILENCE_STDERR - redirect stderr of the test child
1260  * to /dev/null so it cannot be observed on the console during test
1261  * runs. The actual output is still captured though to allow later
1262  * tests with g_test_trap_assert_stderr().
1263  * %G_TEST_TRAP_INHERIT_STDIN - if this flag is given, stdin of the
1264  * forked child process is shared with stdin of its parent process.
1265  * It is redirected to /dev/null otherwise.
1266  *
1267  * In the following example, the test code forks, the forked child
1268  * process produces some sample output and exits successfully.
1269  * The forking parent process then asserts successfull child program
1270  * termination and validates cihld program outputs.
1271  *
1272  * <informalexample><programlisting>
1273  *   static void
1274  *   test_fork_patterns (void)
1275  *   {
1276  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1277  *       {
1278  *         g_print ("some stdout text: somagic17\n");
1279  *         g_printerr ("some stderr text: semagic43\n");
1280  *         exit (0); // successful test run
1281  *       }
1282  *     g_test_trap_assert_passed();
1283  *     g_test_trap_assert_stdout ("*somagic17*");
1284  *     g_test_trap_assert_stderr ("*semagic43*");
1285  *   }
1286  * </programlisting></informalexample>
1287  *
1288  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1289  */
1290 gboolean
1291 g_test_trap_fork (guint64        usec_timeout,
1292                   GTestTrapFlags test_trap_flags)
1293 {
1294   int stdout_pipe[2] = { -1, -1 };
1295   int stderr_pipe[2] = { -1, -1 };
1296   int stdtst_pipe[2] = { -1, -1 };
1297   test_trap_clear();
1298   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1299     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1300   signal (SIGCHLD, SIG_DFL);
1301   test_trap_last_pid = fork ();
1302   if (test_trap_last_pid < 0)
1303     g_error ("failed to fork test program: %s", g_strerror (errno));
1304   if (test_trap_last_pid == 0)  /* child */
1305     {
1306       int fd0 = -1;
1307       close (stdout_pipe[0]);
1308       close (stderr_pipe[0]);
1309       close (stdtst_pipe[0]);
1310       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1311         fd0 = open ("/dev/null", O_RDONLY);
1312       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1313         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1314       if (fd0 >= 3)
1315         close (fd0);
1316       if (stdout_pipe[1] >= 3)
1317         close (stdout_pipe[1]);
1318       if (stderr_pipe[1] >= 3)
1319         close (stderr_pipe[1]);
1320       test_log_fd = stdtst_pipe[1];
1321       return TRUE;
1322     }
1323   else                          /* parent */
1324     {
1325       GString *sout = g_string_new (NULL);
1326       GString *serr = g_string_new (NULL);
1327       guint64 sstamp;
1328       int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1329       test_run_forks++;
1330       close (stdout_pipe[1]);
1331       close (stderr_pipe[1]);
1332       close (stdtst_pipe[1]);
1333       sstamp = test_time_stamp();
1334       /* read data until we get EOF on all pipes */
1335       while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1336         {
1337           fd_set fds;
1338           struct timeval tv;
1339           FD_ZERO (&fds);
1340           if (stdout_pipe[0] >= 0)
1341             FD_SET (stdout_pipe[0], &fds);
1342           if (stderr_pipe[0] >= 0)
1343             FD_SET (stderr_pipe[0], &fds);
1344           if (stdtst_pipe[0] >= 0)
1345             FD_SET (stdtst_pipe[0], &fds);
1346           tv.tv_sec = 0;
1347           tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); // sleep at most 0.5 seconds to catch clock skews, etc.
1348           int ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1349           if (ret < 0 && errno != EINTR)
1350             {
1351               g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1352               break;
1353             }
1354           if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1355               g_string_must_read (sout, stdout_pipe[0]) == 0)
1356             {
1357               close (stdout_pipe[0]);
1358               stdout_pipe[0] = -1;
1359             }
1360           if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1361               g_string_must_read (serr, stderr_pipe[0]) == 0)
1362             {
1363               close (stderr_pipe[0]);
1364               stderr_pipe[0] = -1;
1365             }
1366           if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1367             {
1368               guint8 buffer[4096];
1369               gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1370               if (r > 0 && test_log_fd > 0)
1371                 do
1372                   l = write (test_log_fd, buffer, r);
1373                 while (l < 0 && errno == EINTR);
1374               if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1375                 {
1376                   close (stdtst_pipe[0]);
1377                   stdtst_pipe[0] = -1;
1378                 }
1379             }
1380           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1381             g_string_write_out (sout, 1, &soutpos);
1382           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1383             g_string_write_out (serr, 2, &serrpos);
1384           if (usec_timeout)
1385             {
1386               guint64 nstamp = test_time_stamp();
1387               int status = 0;
1388               sstamp = MIN (sstamp, nstamp); // guard against backwards clock skews
1389               if (usec_timeout < nstamp - sstamp)
1390                 {
1391                   /* timeout reached, need to abort the child now */
1392                   kill_child (test_trap_last_pid, &status, 3);
1393                   test_trap_last_status = 1024; /* timeout */
1394                   if (0 && WIFSIGNALED (status))
1395                     g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1396                   need_wait = FALSE;
1397                   break;
1398                 }
1399             }
1400         }
1401       close (stdout_pipe[0]);
1402       close (stderr_pipe[0]);
1403       close (stdtst_pipe[0]);
1404       if (need_wait)
1405         {
1406           int status = 0;
1407           do
1408             wr = waitpid (test_trap_last_pid, &status, 0);
1409           while (wr < 0 && errno == EINTR);
1410           if (WIFEXITED (status)) /* normal exit */
1411             test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1412           else if (WIFSIGNALED (status))
1413             test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1414           else /* WCOREDUMP (status) */
1415             test_trap_last_status = 512; /* coredump */
1416         }
1417       test_trap_last_stdout = g_string_free (sout, FALSE);
1418       test_trap_last_stderr = g_string_free (serr, FALSE);
1419       return FALSE;
1420     }
1421 }
1422
1423 /**
1424  * g_test_trap_has_passed:
1425  *
1426  * Check the reuslt of the last g_test_trap_fork() call.
1427  *
1428  * Returns: %TRUE if the last forked child terminated successfully.
1429  */
1430 gboolean
1431 g_test_trap_has_passed (void)
1432 {
1433   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1434 }
1435
1436 /**
1437  * g_test_trap_reached_timeout:
1438  *
1439  * Check the reuslt of the last g_test_trap_fork() call.
1440  *
1441  * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1442  */
1443 gboolean
1444 g_test_trap_reached_timeout (void)
1445 {
1446   return 0 != (test_trap_last_status & 1024); /* timeout flag */
1447 }
1448
1449 void
1450 g_test_trap_assertions (const char     *domain,
1451                         const char     *file,
1452                         int             line,
1453                         const char     *func,
1454                         gboolean        must_pass,
1455                         gboolean        must_fail,
1456                         const char     *stdout_pattern,
1457                         const char     *stderr_pattern)
1458 {
1459   if (test_trap_last_pid == 0)
1460     g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1461   if (must_pass && !g_test_trap_has_passed())
1462     {
1463       char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1464       g_assertion_message (domain, file, line, func, msg);
1465       g_free (msg);
1466     }
1467   if (must_fail && g_test_trap_has_passed())
1468     {
1469       char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1470       g_assertion_message (domain, file, line, func, msg);
1471       g_free (msg);
1472     }
1473   if (stdout_pattern && !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1474     {
1475       char *msg = g_strdup_printf ("stdout of child process (%d) failed to match: %s", test_trap_last_pid, stdout_pattern);
1476       g_assertion_message (domain, file, line, func, msg);
1477       g_free (msg);
1478     }
1479   if (stderr_pattern && !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1480     {
1481       char *msg = g_strdup_printf ("stderr of child process (%d) failed to match: %s", test_trap_last_pid, stderr_pattern);
1482       g_assertion_message (domain, file, line, func, msg);
1483       g_free (msg);
1484     }
1485 }
1486
1487 static void
1488 gstring_overwrite_int (GString *gstring,
1489                        guint    pos,
1490                        guint32  vuint)
1491 {
1492   vuint = g_htonl (vuint);
1493   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1494 }
1495
1496 static void
1497 gstring_append_int (GString *gstring,
1498                     guint32  vuint)
1499 {
1500   vuint = g_htonl (vuint);
1501   g_string_append_len (gstring, (const gchar*) &vuint, 4);
1502 }
1503
1504 static void
1505 gstring_append_double (GString *gstring,
1506                        double   vdouble)
1507 {
1508   union { double vdouble; guint64 vuint64; } u;
1509   u.vdouble = vdouble;
1510   u.vuint64 = GUINT64_TO_BE (u.vuint64);
1511   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1512 }
1513
1514 static guint8*
1515 g_test_log_dump (GTestLogMsg *msg,
1516                  guint       *len)
1517 {
1518   GString *gstring = g_string_sized_new (1024);
1519   guint ui;
1520   gstring_append_int (gstring, 0);              /* message length */
1521   gstring_append_int (gstring, msg->log_type);
1522   gstring_append_int (gstring, msg->n_strings);
1523   gstring_append_int (gstring, msg->n_nums);
1524   gstring_append_int (gstring, 0);      /* reserved */
1525   for (ui = 0; ui < msg->n_strings; ui++)
1526     {
1527       guint l = strlen (msg->strings[ui]);
1528       gstring_append_int (gstring, l);
1529       g_string_append_len (gstring, msg->strings[ui], l);
1530     }
1531   for (ui = 0; ui < msg->n_nums; ui++)
1532     gstring_append_double (gstring, msg->nums[ui]);
1533   *len = gstring->len;
1534   gstring_overwrite_int (gstring, 0, *len);     /* message length */
1535   return (guint8*) g_string_free (gstring, FALSE);
1536 }
1537
1538 static inline long double
1539 net_double (const gchar **ipointer)
1540 {
1541   union { guint64 vuint64; double vdouble; } u;
1542   guint64 aligned_int64;
1543   memcpy (&aligned_int64, *ipointer, 8);
1544   *ipointer += 8;
1545   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1546   return u.vdouble;
1547 }
1548
1549 static inline guint32
1550 net_int (const gchar **ipointer)
1551 {
1552   guint32 aligned_int;
1553   memcpy (&aligned_int, *ipointer, 4);
1554   *ipointer += 4;
1555   return g_ntohl (aligned_int);
1556 }
1557
1558 static gboolean
1559 g_test_log_extract (GTestLogBuffer *tbuffer)
1560 {
1561   const gchar *p = tbuffer->data->str;
1562   GTestLogMsg msg;
1563   guint mlength;
1564   if (tbuffer->data->len < 4 * 5)
1565     return FALSE;
1566   mlength = net_int (&p);
1567   if (tbuffer->data->len < mlength)
1568     return FALSE;
1569   msg.log_type = net_int (&p);
1570   msg.n_strings = net_int (&p);
1571   msg.n_nums = net_int (&p);
1572   if (net_int (&p) == 0)
1573     {
1574       guint ui;
1575       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1576       msg.nums = g_new0 (long double, msg.n_nums);
1577       for (ui = 0; ui < msg.n_strings; ui++)
1578         {
1579           guint sl = net_int (&p);
1580           msg.strings[ui] = g_strndup (p, sl);
1581           p += sl;
1582         }
1583       for (ui = 0; ui < msg.n_nums; ui++)
1584         msg.nums[ui] = net_double (&p);
1585       if (p <= tbuffer->data->str + mlength)
1586         {
1587           g_string_erase (tbuffer->data, 0, mlength);
1588           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1589           return TRUE;
1590         }
1591     }
1592   g_free (msg.nums);
1593   g_strfreev (msg.strings);
1594   g_error ("corrupt log stream from test program");
1595   return FALSE;
1596 }
1597
1598 /**
1599  * g_test_log_buffer_new:
1600  *
1601  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1602  */
1603 GTestLogBuffer*
1604 g_test_log_buffer_new (void)
1605 {
1606   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1607   tb->data = g_string_sized_new (1024);
1608   return tb;
1609 }
1610
1611 /**
1612  * g_test_log_buffer_free
1613  *
1614  * Internal function for gtester to free test log messages, no ABI guarantees provided.
1615  */
1616 void
1617 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1618 {
1619   g_return_if_fail (tbuffer != NULL);
1620   while (tbuffer->msgs)
1621     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1622   g_string_free (tbuffer->data, TRUE);
1623   g_free (tbuffer);
1624 }
1625
1626 /**
1627  * g_test_log_buffer_push
1628  *
1629  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1630  */
1631 void
1632 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
1633                         guint           n_bytes,
1634                         const guint8   *bytes)
1635 {
1636   g_return_if_fail (tbuffer != NULL);
1637   if (n_bytes)
1638     {
1639       gboolean more_messages;
1640       g_return_if_fail (bytes != NULL);
1641       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
1642       do
1643         more_messages = g_test_log_extract (tbuffer);
1644       while (more_messages);
1645     }
1646 }
1647
1648 /**
1649  * g_test_log_buffer_pop:
1650  *
1651  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1652  */
1653 GTestLogMsg*
1654 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
1655 {
1656   GTestLogMsg *msg = NULL;
1657   g_return_val_if_fail (tbuffer != NULL, NULL);
1658   if (tbuffer->msgs)
1659     {
1660       GSList *slist = g_slist_last (tbuffer->msgs);
1661       msg = slist->data;
1662       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
1663     }
1664   return msg;
1665 }
1666
1667 /**
1668  * g_test_log_msg_free:
1669  *
1670  * Internal function for gtester to free test log messages, no ABI guarantees provided.
1671  */
1672 void
1673 g_test_log_msg_free (GTestLogMsg *tmsg)
1674 {
1675   g_return_if_fail (tmsg != NULL);
1676   g_strfreev (tmsg->strings);
1677   g_free (tmsg->nums);
1678   g_free (tmsg);
1679 }
1680
1681 /* --- macros docs START --- */
1682 /**
1683  * g_test_add:
1684  * @testpath:  The test path for a new test case.
1685  * @Fixture:   The type of a fixture data structure.
1686  * @fsetup:    The function to set up the fixture data.
1687  * @ftest:     The actual test function.
1688  * @fteardown: The function to tear down the fixture data.
1689  *
1690  * Hook up a new test case at @testpath, similar to g_test_add_func().
1691  * A fixture data structure with setup and teardown function may be provided
1692  * though, simmilar to g_test_create_case().
1693  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
1694  * fteardown() callbacks can expect a @Fixture pointer as first argument in
1695  * a type safe manner.
1696  **/
1697 /* --- macros docs END --- */
1698
1699 #define __G_TESTFRAMEWORK_C__
1700 #include "galiasdef.c"