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