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