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