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