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