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