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