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