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