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