Revert "gtestutils: fix "-p" logic"
[platform/upstream/glib.git] / glib / gtestutils.c
1 /* GLib testing utilities
2  * Copyright (C) 2007 Imendio AB
3  * Authors: Tim Janik, Sven Herzberg
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtestutils.h"
24 #include "gfileutils.h"
25
26 #include <sys/types.h>
27 #ifdef G_OS_UNIX
28 #include <sys/wait.h>
29 #include <sys/time.h>
30 #include <fcntl.h>
31 #include <glib/gstdio.h>
32 #endif
33 #include <string.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef G_OS_WIN32
40 #include <io.h>
41 #include <windows.h>
42 #endif
43 #include <errno.h>
44 #include <signal.h>
45 #ifdef HAVE_SYS_SELECT_H
46 #include <sys/select.h>
47 #endif /* HAVE_SYS_SELECT_H */
48
49 #include "gmain.h"
50 #include "gpattern.h"
51 #include "grand.h"
52 #include "gstrfuncs.h"
53 #include "gtimer.h"
54 #include "gslice.h"
55 #include "gspawn.h"
56
57
58 /**
59  * SECTION:testing
60  * @title: Testing
61  * @short_description: a test framework
62  * @see_also: <link linkend="gtester">gtester</link>,
63  *            <link linkend="gtester-report">gtester-report</link>
64  *
65  * GLib provides a framework for writing and maintaining unit tests
66  * in parallel to the code they are testing. The API is designed according
67  * to established concepts found in the other test frameworks (JUnit, NUnit,
68  * RUnit), which in turn is based on smalltalk unit testing concepts.
69  *
70  * <variablelist>
71  *   <varlistentry>
72  *     <term>Test case</term>
73  *     <listitem>Tests (test methods) are grouped together with their
74  *       fixture into test cases.</listitem>
75  *   </varlistentry>
76  *   <varlistentry>
77  *     <term>Fixture</term>
78  *     <listitem>A test fixture consists of fixture data and setup and
79  *       teardown methods to establish the environment for the test
80  *       functions. We use fresh fixtures, i.e. fixtures are newly set
81  *       up and torn down around each test invocation to avoid dependencies
82  *       between tests.</listitem>
83  *   </varlistentry>
84  *   <varlistentry>
85  *     <term>Test suite</term>
86  *     <listitem>Test cases can be grouped into test suites, to allow
87  *       subsets of the available tests to be run. Test suites can be
88  *       grouped into other test suites as well.</listitem>
89  *   </varlistentry>
90  * </variablelist>
91  * The API is designed to handle creation and registration of test suites
92  * and test cases implicitly. A simple call like
93  * |[
94  *   g_test_add_func ("/misc/assertions", test_assertions);
95  * ]|
96  * creates a test suite called "misc" with a single test case named
97  * "assertions", which consists of running the test_assertions function.
98  *
99  * In addition to the traditional g_assert(), the test framework provides
100  * an extended set of assertions for string and numerical comparisons:
101  * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
102  * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
103  * over plain g_assert() is that the assertion messages can be more
104  * elaborate, and include the values of the compared entities.
105  *
106  * GLib ships with two utilities called gtester and gtester-report to
107  * facilitate running tests and producing nicely formatted test reports.
108  */
109
110 /**
111  * g_test_initialized:
112  *
113  * Returns %TRUE if g_test_init() has been called.
114  *
115  * Returns: %TRUE if g_test_init() has been called.
116  *
117  * Since: 2.36
118  */
119
120 /**
121  * g_test_quick:
122  *
123  * Returns %TRUE if tests are run in quick mode.
124  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
125  * there is no "medium speed".
126  *
127  * Returns: %TRUE if in quick mode
128  */
129
130 /**
131  * g_test_slow:
132  *
133  * Returns %TRUE if tests are run in slow mode.
134  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
135  * there is no "medium speed".
136  *
137  * Returns: the opposite of g_test_quick()
138  */
139
140 /**
141  * g_test_thorough:
142  *
143  * Returns %TRUE if tests are run in thorough mode, equivalent to
144  * g_test_slow().
145  *
146  * Returns: the same thing as g_test_slow()
147  */
148
149 /**
150  * g_test_perf:
151  *
152  * Returns %TRUE if tests are run in performance mode.
153  *
154  * Returns: %TRUE if in performance mode
155  */
156
157 /**
158  * g_test_undefined:
159  *
160  * Returns %TRUE if tests may provoke assertions and other formally-undefined
161  * behaviour, to verify that appropriate warnings are given. It might, in some
162  * cases, be useful to turn this off if running tests under valgrind.
163  *
164  * Returns: %TRUE if tests may provoke programming errors
165  */
166
167 /**
168  * g_test_verbose:
169  *
170  * Returns %TRUE if tests are run in verbose mode.
171  * The default is neither g_test_verbose() nor g_test_quiet().
172  *
173  * Returns: %TRUE if in verbose mode
174  */
175
176 /**
177  * g_test_quiet:
178  *
179  * Returns %TRUE if tests are run in quiet mode.
180  * The default is neither g_test_verbose() nor g_test_quiet().
181  *
182  * Returns: %TRUE if in quiet mode
183  */
184
185 /**
186  * g_test_queue_unref:
187  * @gobject: the object to unref
188  *
189  * Enqueue an object to be released with g_object_unref() during
190  * the next teardown phase. This is equivalent to calling
191  * g_test_queue_destroy() with a destroy callback of g_object_unref().
192  *
193  * Since: 2.16
194  */
195
196 /**
197  * GTestTrapFlags:
198  * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
199  *     <filename>/dev/null</filename> so it cannot be observed on the
200  *     console during test runs. The actual output is still captured
201  *     though to allow later tests with g_test_trap_assert_stdout().
202  * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
203  *     <filename>/dev/null</filename> so it cannot be observed on the
204  *     console during test runs. The actual output is still captured
205  *     though to allow later tests with g_test_trap_assert_stderr().
206  * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
207  *     child process is shared with stdin of its parent process.
208  *     It is redirected to <filename>/dev/null</filename> otherwise.
209  *
210  * Test traps are guards around subprocess tests.
211  * These flags determine what traps to set.
212  */
213
214 /**
215  * g_test_trap_assert_passed:
216  *
217  * Assert that the last test subprocess passed.
218  * See g_test_trap_subprocess().
219  *
220  * Since: 2.16
221  */
222
223 /**
224  * g_test_trap_assert_failed:
225  *
226  * Assert that the last test subprocess failed.
227  * See g_test_trap_subprocess().
228  *
229  * This is sometimes used to test situations that are formally considered to
230  * be undefined behaviour, like inputs that fail a g_return_if_fail()
231  * check. In these situations you should skip the entire test, including the
232  * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
233  * to indicate that undefined behaviour may be tested.
234  *
235  * Since: 2.16
236  */
237
238 /**
239  * g_test_trap_assert_stdout:
240  * @soutpattern: a glob-style
241  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
242  *
243  * Assert that the stdout output of the last test subprocess matches
244  * @soutpattern. See g_test_trap_subprocess().
245  *
246  * Since: 2.16
247  */
248
249 /**
250  * g_test_trap_assert_stdout_unmatched:
251  * @soutpattern: a glob-style
252  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
253  *
254  * Assert that the stdout output of the last test subprocess
255  * does not match @soutpattern. See g_test_trap_subprocess().
256  *
257  * Since: 2.16
258  */
259
260 /**
261  * g_test_trap_assert_stderr:
262  * @serrpattern: a glob-style
263  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
264  *
265  * Assert that the stderr output of the last test subprocess
266  * matches @serrpattern. See  g_test_trap_subprocess().
267  *
268  * This is sometimes used to test situations that are formally
269  * considered to be undefined behaviour, like code that hits a
270  * g_assert() or g_error(). In these situations you should skip the
271  * entire test, including the call to g_test_trap_subprocess(), unless
272  * g_test_undefined() returns %TRUE to indicate that undefined
273  * behaviour may be tested.
274  *
275  * Since: 2.16
276  */
277
278 /**
279  * g_test_trap_assert_stderr_unmatched:
280  * @serrpattern: a glob-style
281  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
282  *
283  * Assert that the stderr output of the last test subprocess
284  * does not match @serrpattern. See g_test_trap_subprocess().
285  *
286  * Since: 2.16
287  */
288
289 /**
290  * g_test_rand_bit:
291  *
292  * Get a reproducible random bit (0 or 1), see g_test_rand_int()
293  * for details on test case random numbers.
294  *
295  * Since: 2.16
296  */
297
298 /**
299  * g_assert:
300  * @expr: the expression to check
301  *
302  * Debugging macro to terminate the application if the assertion
303  * fails. If the assertion fails (i.e. the expression is not true),
304  * an error message is logged and the application is terminated.
305  *
306  * The macro can be turned off in final releases of code by defining
307  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
308  */
309
310 /**
311  * g_assert_not_reached:
312  *
313  * Debugging macro to terminate the application if it is ever
314  * reached. If it is reached, an error message is logged and the
315  * application is terminated.
316  *
317  * The macro can be turned off in final releases of code by defining
318  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
319  */
320
321 /**
322  * g_assert_cmpstr:
323  * @s1: a string (may be %NULL)
324  * @cmp: The comparison operator to use.
325  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
326  * @s2: another string (may be %NULL)
327  *
328  * Debugging macro to terminate the application with a warning
329  * message if a string comparison fails. The strings are compared
330  * using g_strcmp0().
331  *
332  * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
333  * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
334  * The advantage of this macro is that it can produce a message that
335  * includes the actual values of @s1 and @s2.
336  *
337  * |[
338  *   g_assert_cmpstr (mystring, ==, "fubar");
339  * ]|
340  *
341  * Since: 2.16
342  */
343
344 /**
345  * g_assert_cmpint:
346  * @n1: an integer
347  * @cmp: The comparison operator to use.
348  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
349  * @n2: another integer
350  *
351  * Debugging macro to terminate the application with a warning
352  * message if an integer comparison fails.
353  *
354  * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
355  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
356  * of this macro is that it can produce a message that includes the
357  * actual values of @n1 and @n2.
358  *
359  * Since: 2.16
360  */
361
362 /**
363  * g_assert_cmpuint:
364  * @n1: an unsigned integer
365  * @cmp: The comparison operator to use.
366  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
367  * @n2: another unsigned integer
368  *
369  * Debugging macro to terminate the application with a warning
370  * message if an unsigned integer comparison fails.
371  *
372  * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
373  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
374  * of this macro is that it can produce a message that includes the
375  * actual values of @n1 and @n2.
376  *
377  * Since: 2.16
378  */
379
380 /**
381  * g_assert_cmphex:
382  * @n1: an unsigned integer
383  * @cmp: The comparison operator to use.
384  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
385  * @n2: another unsigned integer
386  *
387  * Debugging macro to terminate the application with a warning
388  * message if an unsigned integer comparison fails.
389  *
390  * This is a variant of g_assert_cmpuint() that displays the numbers
391  * in hexadecimal notation in the message.
392  *
393  * Since: 2.16
394  */
395
396 /**
397  * g_assert_cmpfloat:
398  * @n1: an floating point number
399  * @cmp: The comparison operator to use.
400  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
401  * @n2: another floating point number
402  *
403  * Debugging macro to terminate the application with a warning
404  * message if a floating point number comparison fails.
405  *
406  * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
407  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
408  * of this macro is that it can produce a message that includes the
409  * actual values of @n1 and @n2.
410  *
411  * Since: 2.16
412  */
413
414 /**
415  * g_assert_no_error:
416  * @err: a #GError, possibly %NULL
417  *
418  * Debugging macro to terminate the application with a warning
419  * message if a method has returned a #GError.
420  *
421  * The effect of <literal>g_assert_no_error (err)</literal> is
422  * the same as <literal>g_assert (err == NULL)</literal>. The advantage
423  * of this macro is that it can produce a message that includes
424  * the error message and code.
425  *
426  * Since: 2.20
427  */
428
429 /**
430  * g_assert_error:
431  * @err: a #GError, possibly %NULL
432  * @dom: the expected error domain (a #GQuark)
433  * @c: the expected error code
434  *
435  * Debugging macro to terminate the application with a warning
436  * message if a method has not returned the correct #GError.
437  *
438  * The effect of <literal>g_assert_error (err, dom, c)</literal> is
439  * the same as <literal>g_assert (err != NULL &amp;&amp; err->domain
440  * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
441  * macro is that it can produce a message that includes the incorrect
442  * error message and code.
443  *
444  * This can only be used to test for a specific error. If you want to
445  * test that @err is set, but don't care what it's set to, just use
446  * <literal>g_assert (err != NULL)</literal>
447  *
448  * Since: 2.20
449  */
450
451 /**
452  * GTestCase:
453  *
454  * An opaque structure representing a test case.
455  */
456
457 /**
458  * GTestSuite:
459  *
460  * An opaque structure representing a test suite.
461  */
462
463
464 /* Global variable for storing assertion messages; this is the counterpart to
465  * glibc's (private) __abort_msg variable, and allows developers and crash
466  * analysis systems like Apport and ABRT to fish out assertion messages from
467  * core dumps, instead of having to catch them on screen output.
468  */
469 char *__glib_assert_msg = NULL;
470
471 /* --- constants --- */
472 #define G_TEST_STATUS_TIMED_OUT 1024
473
474 /* --- structures --- */
475 struct GTestCase
476 {
477   gchar  *name;
478   guint   fixture_size;
479   void   (*fixture_setup)    (void*, gconstpointer);
480   void   (*fixture_test)     (void*, gconstpointer);
481   void   (*fixture_teardown) (void*, gconstpointer);
482   gpointer test_data;
483 };
484 struct GTestSuite
485 {
486   gchar  *name;
487   GSList *suites;
488   GSList *cases;
489 };
490 typedef struct DestroyEntry DestroyEntry;
491 struct DestroyEntry
492 {
493   DestroyEntry *next;
494   GDestroyNotify destroy_func;
495   gpointer       destroy_data;
496 };
497
498 /* --- prototypes --- */
499 static void     test_run_seed                   (const gchar *rseed);
500 static void     test_trap_clear                 (void);
501 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
502                                                  guint       *len);
503 static void     gtest_default_log_handler       (const gchar    *log_domain,
504                                                  GLogLevelFlags  log_level,
505                                                  const gchar    *message,
506                                                  gpointer        unused_data);
507
508
509 /* --- variables --- */
510 static int         test_log_fd = -1;
511 static guint64     test_timeout = 0;
512 static gboolean    test_mode_fatal = TRUE;
513 static gboolean    g_test_run_once = TRUE;
514 static gboolean    test_run_list = FALSE;
515 static gchar      *test_run_seedstr = NULL;
516 static GRand      *test_run_rand = NULL;
517 static gchar      *test_run_name = "";
518 static guint       test_run_forks = 0;
519 static guint       test_run_count = 0;
520 static guint       test_run_success = FALSE;
521 static guint       test_skip_count = 0;
522 static GTimer     *test_user_timer = NULL;
523 static double      test_user_stamp = 0;
524 static GSList     *test_paths = NULL;
525 static GTestSuite *test_suite_root = NULL;
526 static int         test_trap_last_status = 0;
527 static int         test_trap_last_pid = 0;
528 static char       *test_trap_last_subprocess = NULL;
529 static char       *test_trap_last_stdout = NULL;
530 static char       *test_trap_last_stderr = NULL;
531 static char       *test_uri_base = NULL;
532 static gboolean    test_debug_log = FALSE;
533 static DestroyEntry *test_destroy_queue = NULL;
534 static char       *test_argv0 = NULL;
535 static char       *test_initial_cwd = NULL;
536 static gboolean    test_in_subprocess = FALSE;
537 static GTestConfig mutable_test_config_vars = {
538   FALSE,        /* test_initialized */
539   TRUE,         /* test_quick */
540   FALSE,        /* test_perf */
541   FALSE,        /* test_verbose */
542   FALSE,        /* test_quiet */
543   TRUE,         /* test_undefined */
544 };
545 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
546
547 /* --- functions --- */
548 const char*
549 g_test_log_type_name (GTestLogType log_type)
550 {
551   switch (log_type)
552     {
553     case G_TEST_LOG_NONE:               return "none";
554     case G_TEST_LOG_ERROR:              return "error";
555     case G_TEST_LOG_START_BINARY:       return "binary";
556     case G_TEST_LOG_LIST_CASE:          return "list";
557     case G_TEST_LOG_SKIP_CASE:          return "skip";
558     case G_TEST_LOG_START_CASE:         return "start";
559     case G_TEST_LOG_STOP_CASE:          return "stop";
560     case G_TEST_LOG_MIN_RESULT:         return "minperf";
561     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
562     case G_TEST_LOG_MESSAGE:            return "message";
563     }
564   return "???";
565 }
566
567 static void
568 g_test_log_send (guint         n_bytes,
569                  const guint8 *buffer)
570 {
571   if (test_log_fd >= 0)
572     {
573       int r;
574       do
575         r = write (test_log_fd, buffer, n_bytes);
576       while (r < 0 && errno == EINTR);
577     }
578   if (test_debug_log)
579     {
580       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
581       GTestLogMsg *msg;
582       guint ui;
583       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
584       msg = g_test_log_buffer_pop (lbuffer);
585       g_warn_if_fail (msg != NULL);
586       g_warn_if_fail (lbuffer->data->len == 0);
587       g_test_log_buffer_free (lbuffer);
588       /* print message */
589       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
590       for (ui = 0; ui < msg->n_strings; ui++)
591         g_printerr (":{%s}", msg->strings[ui]);
592       if (msg->n_nums)
593         {
594           g_printerr (":(");
595           for (ui = 0; ui < msg->n_nums; ui++)
596             {
597               if ((long double) (long) msg->nums[ui] == msg->nums[ui])
598                 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
599               else
600                 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
601             }
602           g_printerr (")");
603         }
604       g_printerr (":LOG*}\n");
605       g_test_log_msg_free (msg);
606     }
607 }
608
609 static void
610 g_test_log (GTestLogType lbit,
611             const gchar *string1,
612             const gchar *string2,
613             guint        n_args,
614             long double *largs)
615 {
616   gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
617   GTestLogMsg msg;
618   gchar *astrings[3] = { NULL, NULL, NULL };
619   guint8 *dbuffer;
620   guint32 dbufferlen;
621
622   switch (lbit)
623     {
624     case G_TEST_LOG_START_BINARY:
625       if (g_test_verbose())
626         g_print ("GTest: random seed: %s\n", string2);
627       break;
628     case G_TEST_LOG_STOP_CASE:
629       if (g_test_verbose())
630         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
631       else if (!g_test_quiet())
632         g_print ("%s\n", fail ? "FAIL" : "OK");
633       if (fail && test_mode_fatal)
634         abort();
635       break;
636     case G_TEST_LOG_MIN_RESULT:
637       if (g_test_verbose())
638         g_print ("(MINPERF:%s)\n", string1);
639       break;
640     case G_TEST_LOG_MAX_RESULT:
641       if (g_test_verbose())
642         g_print ("(MAXPERF:%s)\n", string1);
643       break;
644     case G_TEST_LOG_MESSAGE:
645       if (g_test_verbose())
646         g_print ("(MSG: %s)\n", string1);
647       break;
648     default: ;
649     }
650
651   msg.log_type = lbit;
652   msg.n_strings = (string1 != NULL) + (string1 && string2);
653   msg.strings = astrings;
654   astrings[0] = (gchar*) string1;
655   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
656   msg.n_nums = n_args;
657   msg.nums = largs;
658   dbuffer = g_test_log_dump (&msg, &dbufferlen);
659   g_test_log_send (dbufferlen, dbuffer);
660   g_free (dbuffer);
661
662   switch (lbit)
663     {
664     case G_TEST_LOG_START_CASE:
665       if (g_test_verbose())
666         g_print ("GTest: run: %s\n", string1);
667       else if (!g_test_quiet())
668         g_print ("%s: ", string1);
669       break;
670     default: ;
671     }
672 }
673
674 /* We intentionally parse the command line without GOptionContext
675  * because otherwise you would never be able to test it.
676  */
677 static void
678 parse_args (gint    *argc_p,
679             gchar ***argv_p)
680 {
681   guint argc = *argc_p;
682   gchar **argv = *argv_p;
683   guint i, e;
684
685   test_argv0 = argv[0];
686   test_initial_cwd = g_get_current_dir ();
687
688   /* parse known args */
689   for (i = 1; i < argc; i++)
690     {
691       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
692         {
693           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
694           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
695           g_log_set_always_fatal (fatal_mask);
696           argv[i] = NULL;
697         }
698       else if (strcmp (argv[i], "--keep-going") == 0 ||
699                strcmp (argv[i], "-k") == 0)
700         {
701           test_mode_fatal = FALSE;
702           argv[i] = NULL;
703         }
704       else if (strcmp (argv[i], "--debug-log") == 0)
705         {
706           test_debug_log = TRUE;
707           argv[i] = NULL;
708         }
709       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
710         {
711           gchar *equal = argv[i] + 12;
712           if (*equal == '=')
713             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
714           else if (i + 1 < argc)
715             {
716               argv[i++] = NULL;
717               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
718             }
719           argv[i] = NULL;
720         }
721       else if (strcmp ("--GTestTimeout", argv[i]) == 0 || strncmp ("--GTestTimeout=", argv[i], 15) == 0)
722         {
723           gchar *equal = argv[i] + 14;
724           if (*equal == '=')
725             test_timeout = g_ascii_strtoull (equal + 1, NULL, 0);
726           else if (i + 1 < argc)
727             {
728               argv[i++] = NULL;
729               test_timeout = g_ascii_strtoull (argv[i], NULL, 0);
730             }
731           argv[i] = NULL;
732         }
733       else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
734         {
735           test_in_subprocess = TRUE;
736           argv[i] = NULL;
737         }
738       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
739         {
740           gchar *equal = argv[i] + 16;
741           if (*equal == '=')
742             test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
743           else if (i + 1 < argc)
744             {
745               argv[i++] = NULL;
746               test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
747             }
748           argv[i] = NULL;
749         }
750       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
751         {
752           gchar *equal = argv[i] + 2;
753           if (*equal == '=')
754             test_paths = g_slist_prepend (test_paths, equal + 1);
755           else if (i + 1 < argc)
756             {
757               argv[i++] = NULL;
758               test_paths = g_slist_prepend (test_paths, argv[i]);
759             }
760           argv[i] = NULL;
761         }
762       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
763         {
764           gchar *equal = argv[i] + 2;
765           const gchar *mode = "";
766           if (*equal == '=')
767             mode = equal + 1;
768           else if (i + 1 < argc)
769             {
770               argv[i++] = NULL;
771               mode = argv[i];
772             }
773           if (strcmp (mode, "perf") == 0)
774             mutable_test_config_vars.test_perf = TRUE;
775           else if (strcmp (mode, "slow") == 0)
776             mutable_test_config_vars.test_quick = FALSE;
777           else if (strcmp (mode, "thorough") == 0)
778             mutable_test_config_vars.test_quick = FALSE;
779           else if (strcmp (mode, "quick") == 0)
780             {
781               mutable_test_config_vars.test_quick = TRUE;
782               mutable_test_config_vars.test_perf = FALSE;
783             }
784           else if (strcmp (mode, "undefined") == 0)
785             mutable_test_config_vars.test_undefined = TRUE;
786           else if (strcmp (mode, "no-undefined") == 0)
787             mutable_test_config_vars.test_undefined = FALSE;
788           else
789             g_error ("unknown test mode: -m %s", mode);
790           argv[i] = NULL;
791         }
792       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
793         {
794           mutable_test_config_vars.test_quiet = TRUE;
795           mutable_test_config_vars.test_verbose = FALSE;
796           argv[i] = NULL;
797         }
798       else if (strcmp ("--verbose", argv[i]) == 0)
799         {
800           mutable_test_config_vars.test_quiet = FALSE;
801           mutable_test_config_vars.test_verbose = TRUE;
802           argv[i] = NULL;
803         }
804       else if (strcmp ("-l", argv[i]) == 0)
805         {
806           test_run_list = TRUE;
807           argv[i] = NULL;
808         }
809       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
810         {
811           gchar *equal = argv[i] + 6;
812           if (*equal == '=')
813             test_run_seedstr = equal + 1;
814           else if (i + 1 < argc)
815             {
816               argv[i++] = NULL;
817               test_run_seedstr = argv[i];
818             }
819           argv[i] = NULL;
820         }
821       else if (strcmp ("-?", argv[i]) == 0 ||
822                strcmp ("-h", argv[i]) == 0 ||
823                strcmp ("--help", argv[i]) == 0)
824         {
825           printf ("Usage:\n"
826                   "  %s [OPTION...]\n\n"
827                   "Help Options:\n"
828                   "  -h, --help                     Show help options\n\n"
829                   "Test Options:\n"
830                   "  --g-fatal-warnings             Make all warnings fatal\n"
831                   "  -l                             List test cases available in a test executable\n"
832                   "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
833                   "  -m {undefined|no-undefined}    Execute tests according to mode\n"
834                   "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
835                   "  -seed=SEEDSTRING               Start tests with random seed SEEDSTRING\n"
836                   "  --debug-log                    debug test logging output\n"
837                   "  -q, --quiet                    Run tests quietly\n"
838                   "  --verbose                      Run tests verbosely\n",
839                   argv[0]);
840           exit (0);
841         }
842     }
843   /* collapse argv */
844   e = 1;
845   for (i = 1; i < argc; i++)
846     if (argv[i])
847       {
848         argv[e++] = argv[i];
849         if (i >= e)
850           argv[i] = NULL;
851       }
852   *argc_p = e;
853 }
854
855 /**
856  * g_test_init:
857  * @argc: Address of the @argc parameter of the main() function.
858  *        Changed if any arguments were handled.
859  * @argv: Address of the @argv parameter of main().
860  *        Any parameters understood by g_test_init() stripped before return.
861  * @...: Reserved for future extension. Currently, you must pass %NULL.
862  *
863  * Initialize the GLib testing framework, e.g. by seeding the
864  * test random number generator, the name for g_get_prgname()
865  * and parsing test related command line args.
866  * So far, the following arguments are understood:
867  * <variablelist>
868  *   <varlistentry>
869  *     <term><option>-l</option></term>
870  *     <listitem><para>
871  *       List test cases available in a test executable.
872  *     </para></listitem>
873  *   </varlistentry>
874  *   <varlistentry>
875  *     <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
876  *     <listitem><para>
877  *       Provide a random seed to reproduce test runs using random numbers.
878  *     </para></listitem>
879  *     </varlistentry>
880  *     <varlistentry>
881  *       <term><option>--verbose</option></term>
882  *       <listitem><para>Run tests verbosely.</para></listitem>
883  *     </varlistentry>
884  *     <varlistentry>
885  *       <term><option>-q</option>, <option>--quiet</option></term>
886  *       <listitem><para>Run tests quietly.</para></listitem>
887  *     </varlistentry>
888  *     <varlistentry>
889  *       <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
890  *       <listitem><para>
891  *         Execute all tests matching <replaceable>TESTPATH</replaceable>.
892  *       </para></listitem>
893  *     </varlistentry>
894  *     <varlistentry>
895  *       <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
896  *       <listitem><para>
897  *         Execute tests according to these test modes:
898  *         <variablelist>
899  *           <varlistentry>
900  *             <term>perf</term>
901  *             <listitem><para>
902  *               Performance tests, may take long and report results.
903  *             </para></listitem>
904  *           </varlistentry>
905  *           <varlistentry>
906  *             <term>slow, thorough</term>
907  *             <listitem><para>
908  *               Slow and thorough tests, may take quite long and
909  *               maximize coverage.
910  *             </para></listitem>
911  *           </varlistentry>
912  *           <varlistentry>
913  *             <term>quick</term>
914  *             <listitem><para>
915  *               Quick tests, should run really quickly and give good coverage.
916  *             </para></listitem>
917  *           </varlistentry>
918  *           <varlistentry>
919  *             <term>undefined</term>
920  *             <listitem><para>
921  *               Tests for undefined behaviour, may provoke programming errors
922  *               under g_test_trap_subprocess() or g_test_expect_messages() to check
923  *               that appropriate assertions or warnings are given
924  *             </para></listitem>
925  *           </varlistentry>
926  *           <varlistentry>
927  *             <term>no-undefined</term>
928  *             <listitem><para>
929  *               Avoid tests for undefined behaviour
930  *             </para></listitem>
931  *           </varlistentry>
932  *         </variablelist>
933  *       </para></listitem>
934  *     </varlistentry>
935  *     <varlistentry>
936  *       <term><option>--debug-log</option></term>
937  *       <listitem><para>Debug test logging output.</para></listitem>
938  *     </varlistentry>
939  *  </variablelist>
940  *
941  * Since: 2.16
942  */
943 void
944 g_test_init (int    *argc,
945              char ***argv,
946              ...)
947 {
948   static char seedstr[4 + 4 * 8 + 1];
949   va_list args;
950   gpointer vararg1;
951   /* make warnings and criticals fatal for all test programs */
952   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
953   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
954   g_log_set_always_fatal (fatal_mask);
955   /* check caller args */
956   g_return_if_fail (argc != NULL);
957   g_return_if_fail (argv != NULL);
958   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
959   mutable_test_config_vars.test_initialized = TRUE;
960
961   va_start (args, argv);
962   vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
963   va_end (args);
964   g_return_if_fail (vararg1 == NULL);
965
966   /* setup random seed string */
967   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
968   test_run_seedstr = seedstr;
969
970   /* parse args, sets up mode, changes seed, etc. */
971   parse_args (argc, argv);
972   if (!g_get_prgname())
973     g_set_prgname ((*argv)[0]);
974
975   /* verify GRand reliability, needed for reliable seeds */
976   if (1)
977     {
978       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
979       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
980       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
981       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
982         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
983       g_rand_free (rg);
984     }
985
986   /* check rand seed */
987   test_run_seed (test_run_seedstr);
988
989   /* report program start */
990   g_log_set_default_handler (gtest_default_log_handler, NULL);
991   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
992 }
993
994 static void
995 test_run_seed (const gchar *rseed)
996 {
997   guint seed_failed = 0;
998   if (test_run_rand)
999     g_rand_free (test_run_rand);
1000   test_run_rand = NULL;
1001   while (strchr (" \t\v\r\n\f", *rseed))
1002     rseed++;
1003   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
1004     {
1005       const char *s = rseed + 4;
1006       if (strlen (s) >= 32)             /* require 4 * 8 chars */
1007         {
1008           guint32 seedarray[4];
1009           gchar *p, hexbuf[9] = { 0, };
1010           memcpy (hexbuf, s + 0, 8);
1011           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1012           seed_failed += p != NULL && *p != 0;
1013           memcpy (hexbuf, s + 8, 8);
1014           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1015           seed_failed += p != NULL && *p != 0;
1016           memcpy (hexbuf, s + 16, 8);
1017           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1018           seed_failed += p != NULL && *p != 0;
1019           memcpy (hexbuf, s + 24, 8);
1020           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1021           seed_failed += p != NULL && *p != 0;
1022           if (!seed_failed)
1023             {
1024               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1025               return;
1026             }
1027         }
1028     }
1029   g_error ("Unknown or invalid random seed: %s", rseed);
1030 }
1031
1032 /**
1033  * g_test_rand_int:
1034  *
1035  * Get a reproducible random integer number.
1036  *
1037  * The random numbers generated by the g_test_rand_*() family of functions
1038  * change with every new test program start, unless the --seed option is
1039  * given when starting test programs.
1040  *
1041  * For individual test cases however, the random number generator is
1042  * reseeded, to avoid dependencies between tests and to make --seed
1043  * effective for all test cases.
1044  *
1045  * Returns: a random number from the seeded random number generator.
1046  *
1047  * Since: 2.16
1048  */
1049 gint32
1050 g_test_rand_int (void)
1051 {
1052   return g_rand_int (test_run_rand);
1053 }
1054
1055 /**
1056  * g_test_rand_int_range:
1057  * @begin: the minimum value returned by this function
1058  * @end:   the smallest value not to be returned by this function
1059  *
1060  * Get a reproducible random integer number out of a specified range,
1061  * see g_test_rand_int() for details on test case random numbers.
1062  *
1063  * Returns: a number with @begin <= number < @end.
1064  * 
1065  * Since: 2.16
1066  */
1067 gint32
1068 g_test_rand_int_range (gint32          begin,
1069                        gint32          end)
1070 {
1071   return g_rand_int_range (test_run_rand, begin, end);
1072 }
1073
1074 /**
1075  * g_test_rand_double:
1076  *
1077  * Get a reproducible random floating point number,
1078  * see g_test_rand_int() for details on test case random numbers.
1079  *
1080  * Returns: a random number from the seeded random number generator.
1081  *
1082  * Since: 2.16
1083  */
1084 double
1085 g_test_rand_double (void)
1086 {
1087   return g_rand_double (test_run_rand);
1088 }
1089
1090 /**
1091  * g_test_rand_double_range:
1092  * @range_start: the minimum value returned by this function
1093  * @range_end: the minimum value not returned by this function
1094  *
1095  * Get a reproducible random floating pointer number out of a specified range,
1096  * see g_test_rand_int() for details on test case random numbers.
1097  *
1098  * Returns: a number with @range_start <= number < @range_end.
1099  *
1100  * Since: 2.16
1101  */
1102 double
1103 g_test_rand_double_range (double          range_start,
1104                           double          range_end)
1105 {
1106   return g_rand_double_range (test_run_rand, range_start, range_end);
1107 }
1108
1109 /**
1110  * g_test_timer_start:
1111  *
1112  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1113  * to be done. Call this function again to restart the timer.
1114  *
1115  * Since: 2.16
1116  */
1117 void
1118 g_test_timer_start (void)
1119 {
1120   if (!test_user_timer)
1121     test_user_timer = g_timer_new();
1122   test_user_stamp = 0;
1123   g_timer_start (test_user_timer);
1124 }
1125
1126 /**
1127  * g_test_timer_elapsed:
1128  *
1129  * Get the time since the last start of the timer with g_test_timer_start().
1130  *
1131  * Returns: the time since the last start of the timer, as a double
1132  *
1133  * Since: 2.16
1134  */
1135 double
1136 g_test_timer_elapsed (void)
1137 {
1138   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1139   return test_user_stamp;
1140 }
1141
1142 /**
1143  * g_test_timer_last:
1144  *
1145  * Report the last result of g_test_timer_elapsed().
1146  *
1147  * Returns: the last result of g_test_timer_elapsed(), as a double
1148  *
1149  * Since: 2.16
1150  */
1151 double
1152 g_test_timer_last (void)
1153 {
1154   return test_user_stamp;
1155 }
1156
1157 /**
1158  * g_test_minimized_result:
1159  * @minimized_quantity: the reported value
1160  * @format: the format string of the report message
1161  * @...: arguments to pass to the printf() function
1162  *
1163  * Report the result of a performance or measurement test.
1164  * The test should generally strive to minimize the reported
1165  * quantities (smaller values are better than larger ones),
1166  * this and @minimized_quantity can determine sorting
1167  * order for test result reports.
1168  *
1169  * Since: 2.16
1170  */
1171 void
1172 g_test_minimized_result (double          minimized_quantity,
1173                          const char     *format,
1174                          ...)
1175 {
1176   long double largs = minimized_quantity;
1177   gchar *buffer;
1178   va_list args;
1179
1180   va_start (args, format);
1181   buffer = g_strdup_vprintf (format, args);
1182   va_end (args);
1183
1184   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1185   g_free (buffer);
1186 }
1187
1188 /**
1189  * g_test_maximized_result:
1190  * @maximized_quantity: the reported value
1191  * @format: the format string of the report message
1192  * @...: arguments to pass to the printf() function
1193  *
1194  * Report the result of a performance or measurement test.
1195  * The test should generally strive to maximize the reported
1196  * quantities (larger values are better than smaller ones),
1197  * this and @maximized_quantity can determine sorting
1198  * order for test result reports.
1199  *
1200  * Since: 2.16
1201  */
1202 void
1203 g_test_maximized_result (double          maximized_quantity,
1204                          const char     *format,
1205                          ...)
1206 {
1207   long double largs = maximized_quantity;
1208   gchar *buffer;
1209   va_list args;
1210
1211   va_start (args, format);
1212   buffer = g_strdup_vprintf (format, args);
1213   va_end (args);
1214
1215   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1216   g_free (buffer);
1217 }
1218
1219 /**
1220  * g_test_message:
1221  * @format: the format string
1222  * @...:    printf-like arguments to @format
1223  *
1224  * Add a message to the test report.
1225  *
1226  * Since: 2.16
1227  */
1228 void
1229 g_test_message (const char *format,
1230                 ...)
1231 {
1232   gchar *buffer;
1233   va_list args;
1234
1235   va_start (args, format);
1236   buffer = g_strdup_vprintf (format, args);
1237   va_end (args);
1238
1239   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1240   g_free (buffer);
1241 }
1242
1243 /**
1244  * g_test_bug_base:
1245  * @uri_pattern: the base pattern for bug URIs
1246  *
1247  * Specify the base URI for bug reports.
1248  *
1249  * The base URI is used to construct bug report messages for
1250  * g_test_message() when g_test_bug() is called.
1251  * Calling this function outside of a test case sets the
1252  * default base URI for all test cases. Calling it from within
1253  * a test case changes the base URI for the scope of the test
1254  * case only.
1255  * Bug URIs are constructed by appending a bug specific URI
1256  * portion to @uri_pattern, or by replacing the special string
1257  * '\%s' within @uri_pattern if that is present.
1258  *
1259  * Since: 2.16
1260  */
1261 void
1262 g_test_bug_base (const char *uri_pattern)
1263 {
1264   g_free (test_uri_base);
1265   test_uri_base = g_strdup (uri_pattern);
1266 }
1267
1268 /**
1269  * g_test_bug:
1270  * @bug_uri_snippet: Bug specific bug tracker URI portion.
1271  *
1272  * This function adds a message to test reports that
1273  * associates a bug URI with a test case.
1274  * Bug URIs are constructed from a base URI set with g_test_bug_base()
1275  * and @bug_uri_snippet.
1276  *
1277  * Since: 2.16
1278  */
1279 void
1280 g_test_bug (const char *bug_uri_snippet)
1281 {
1282   char *c;
1283
1284   g_return_if_fail (test_uri_base != NULL);
1285   g_return_if_fail (bug_uri_snippet != NULL);
1286
1287   c = strstr (test_uri_base, "%s");
1288   if (c)
1289     {
1290       char *b = g_strndup (test_uri_base, c - test_uri_base);
1291       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1292       g_free (b);
1293       g_test_message ("Bug Reference: %s", s);
1294       g_free (s);
1295     }
1296   else
1297     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1298 }
1299
1300 /**
1301  * g_test_get_root:
1302  *
1303  * Get the toplevel test suite for the test path API.
1304  *
1305  * Returns: the toplevel #GTestSuite
1306  *
1307  * Since: 2.16
1308  */
1309 GTestSuite*
1310 g_test_get_root (void)
1311 {
1312   if (!test_suite_root)
1313     {
1314       test_suite_root = g_test_create_suite ("root");
1315       g_free (test_suite_root->name);
1316       test_suite_root->name = g_strdup ("");
1317     }
1318
1319   return test_suite_root;
1320 }
1321
1322 /**
1323  * g_test_run:
1324  *
1325  * Runs all tests under the toplevel suite which can be retrieved
1326  * with g_test_get_root(). Similar to g_test_run_suite(), the test
1327  * cases to be run are filtered according to
1328  * test path arguments (-p <replaceable>testpath</replaceable>) as 
1329  * parsed by g_test_init().
1330  * g_test_run_suite() or g_test_run() may only be called once
1331  * in a program.
1332  *
1333  * Returns: 0 on success
1334  *
1335  * Since: 2.16
1336  */
1337 int
1338 g_test_run (void)
1339 {
1340   return g_test_run_suite (g_test_get_root());
1341 }
1342
1343 /**
1344  * g_test_create_case:
1345  * @test_name:     the name for the test case
1346  * @data_size:     the size of the fixture data structure
1347  * @test_data:     test data argument for the test functions
1348  * @data_setup:    the function to set up the fixture data
1349  * @data_test:     the actual test function
1350  * @data_teardown: the function to teardown the fixture data
1351  *
1352  * Create a new #GTestCase, named @test_name, this API is fairly
1353  * low level, calling g_test_add() or g_test_add_func() is preferable.
1354  * When this test is executed, a fixture structure of size @data_size
1355  * will be allocated and filled with 0s. Then @data_setup is called
1356  * to initialize the fixture. After fixture setup, the actual test
1357  * function @data_test is called. Once the test run completed, the
1358  * fixture structure is torn down  by calling @data_teardown and
1359  * after that the memory is released.
1360  *
1361  * Splitting up a test run into fixture setup, test function and
1362  * fixture teardown is most usful if the same fixture is used for
1363  * multiple tests. In this cases, g_test_create_case() will be
1364  * called with the same fixture, but varying @test_name and
1365  * @data_test arguments.
1366  *
1367  * Returns: a newly allocated #GTestCase.
1368  *
1369  * Since: 2.16
1370  */
1371 GTestCase*
1372 g_test_create_case (const char       *test_name,
1373                     gsize             data_size,
1374                     gconstpointer     test_data,
1375                     GTestFixtureFunc  data_setup,
1376                     GTestFixtureFunc  data_test,
1377                     GTestFixtureFunc  data_teardown)
1378 {
1379   GTestCase *tc;
1380
1381   g_return_val_if_fail (test_name != NULL, NULL);
1382   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1383   g_return_val_if_fail (test_name[0] != 0, NULL);
1384   g_return_val_if_fail (data_test != NULL, NULL);
1385
1386   tc = g_slice_new0 (GTestCase);
1387   tc->name = g_strdup (test_name);
1388   tc->test_data = (gpointer) test_data;
1389   tc->fixture_size = data_size;
1390   tc->fixture_setup = (void*) data_setup;
1391   tc->fixture_test = (void*) data_test;
1392   tc->fixture_teardown = (void*) data_teardown;
1393
1394   return tc;
1395 }
1396
1397 /**
1398  * GTestFixtureFunc:
1399  * @fixture: the test fixture
1400  * @user_data: the data provided when registering the test
1401  *
1402  * The type used for functions that operate on test fixtures.  This is
1403  * used for the fixture setup and teardown functions as well as for the
1404  * testcases themselves.
1405  *
1406  * @user_data is a pointer to the data that was given when registering
1407  * the test case.
1408  *
1409  * @fixture will be a pointer to the area of memory allocated by the
1410  * test framework, of the size requested.  If the requested size was
1411  * zero then @fixture will be equal to @user_data.
1412  *
1413  * Since: 2.28
1414  */
1415 void
1416 g_test_add_vtable (const char       *testpath,
1417                    gsize             data_size,
1418                    gconstpointer     test_data,
1419                    GTestFixtureFunc  data_setup,
1420                    GTestFixtureFunc  fixture_test_func,
1421                    GTestFixtureFunc  data_teardown)
1422 {
1423   gchar **segments;
1424   guint ui;
1425   GTestSuite *suite;
1426
1427   g_return_if_fail (testpath != NULL);
1428   g_return_if_fail (g_path_is_absolute (testpath));
1429   g_return_if_fail (fixture_test_func != NULL);
1430
1431   suite = g_test_get_root();
1432   segments = g_strsplit (testpath, "/", -1);
1433   for (ui = 0; segments[ui] != NULL; ui++)
1434     {
1435       const char *seg = segments[ui];
1436       gboolean islast = segments[ui + 1] == NULL;
1437       if (islast && !seg[0])
1438         g_error ("invalid test case path: %s", testpath);
1439       else if (!seg[0])
1440         continue;       /* initial or duplicate slash */
1441       else if (!islast)
1442         {
1443           GTestSuite *csuite = g_test_create_suite (seg);
1444           g_test_suite_add_suite (suite, csuite);
1445           suite = csuite;
1446         }
1447       else /* islast */
1448         {
1449           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1450           g_test_suite_add (suite, tc);
1451         }
1452     }
1453   g_strfreev (segments);
1454 }
1455
1456 /**
1457  * g_test_fail:
1458  *
1459  * Indicates that a test failed. This function can be called
1460  * multiple times from the same test. You can use this function
1461  * if your test failed in a recoverable way.
1462  * 
1463  * Do not use this function if the failure of a test could cause
1464  * other tests to malfunction.
1465  *
1466  * Calling this function will not stop the test from running, you
1467  * need to return from the test function yourself. So you can
1468  * produce additional diagnostic messages or even continue running
1469  * the test.
1470  *
1471  * If not called from inside a test, this function does nothing.
1472  *
1473  * Since: 2.30
1474  **/
1475 void
1476 g_test_fail (void)
1477 {
1478   test_run_success = FALSE;
1479 }
1480
1481 /**
1482  * GTestFunc:
1483  *
1484  * The type used for test case functions.
1485  *
1486  * Since: 2.28
1487  */
1488
1489 /**
1490  * g_test_add_func:
1491  * @testpath:   /-separated test case path name for the test.
1492  * @test_func:  The test function to invoke for this test.
1493  *
1494  * Create a new test case, similar to g_test_create_case(). However
1495  * the test is assumed to use no fixture, and test suites are automatically
1496  * created on the fly and added to the root fixture, based on the
1497  * slash-separated portions of @testpath.
1498  *
1499  * Since: 2.16
1500  */
1501 void
1502 g_test_add_func (const char *testpath,
1503                  GTestFunc   test_func)
1504 {
1505   g_return_if_fail (testpath != NULL);
1506   g_return_if_fail (testpath[0] == '/');
1507   g_return_if_fail (test_func != NULL);
1508   g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1509 }
1510
1511 /**
1512  * GTestDataFunc:
1513  * @user_data: the data provided when registering the test
1514  *
1515  * The type used for test case functions that take an extra pointer
1516  * argument.
1517  *
1518  * Since: 2.28
1519  */
1520
1521 /**
1522  * g_test_add_data_func:
1523  * @testpath:   /-separated test case path name for the test.
1524  * @test_data:  Test data argument for the test function.
1525  * @test_func:  The test function to invoke for this test.
1526  *
1527  * Create a new test case, similar to g_test_create_case(). However
1528  * the test is assumed to use no fixture, and test suites are automatically
1529  * created on the fly and added to the root fixture, based on the
1530  * slash-separated portions of @testpath. The @test_data argument
1531  * will be passed as first argument to @test_func.
1532  *
1533  * Since: 2.16
1534  */
1535 void
1536 g_test_add_data_func (const char     *testpath,
1537                       gconstpointer   test_data,
1538                       GTestDataFunc   test_func)
1539 {
1540   g_return_if_fail (testpath != NULL);
1541   g_return_if_fail (testpath[0] == '/');
1542   g_return_if_fail (test_func != NULL);
1543
1544   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1545 }
1546
1547 /**
1548  * g_test_add_data_func_full:
1549  * @testpath: /-separated test case path name for the test.
1550  * @test_data: Test data argument for the test function.
1551  * @test_func: The test function to invoke for this test.
1552  * @data_free_func: #GDestroyNotify for @test_data.
1553  *
1554  * Create a new test case, as with g_test_add_data_func(), but freeing
1555  * @test_data after the test run is complete.
1556  *
1557  * Since: 2.34
1558  */
1559 void
1560 g_test_add_data_func_full (const char     *testpath,
1561                            gpointer        test_data,
1562                            GTestDataFunc   test_func,
1563                            GDestroyNotify  data_free_func)
1564 {
1565   g_return_if_fail (testpath != NULL);
1566   g_return_if_fail (testpath[0] == '/');
1567   g_return_if_fail (test_func != NULL);
1568
1569   g_test_add_vtable (testpath, 0, test_data, NULL,
1570                      (GTestFixtureFunc) test_func,
1571                      (GTestFixtureFunc) data_free_func);
1572 }
1573
1574 static gboolean
1575 g_test_suite_case_exists (GTestSuite *suite,
1576                           const char *test_path)
1577 {
1578   GSList *iter;
1579   char *slash;
1580   GTestCase *tc;
1581
1582   test_path++;
1583   slash = strchr (test_path, '/');
1584
1585   if (slash)
1586     {
1587       for (iter = suite->suites; iter; iter = iter->next)
1588         {
1589           GTestSuite *child_suite = iter->data;
1590
1591           if (!strncmp (child_suite->name, test_path, slash - test_path))
1592             if (g_test_suite_case_exists (child_suite, slash))
1593               return TRUE;
1594         }
1595     }
1596   else
1597     {
1598       for (iter = suite->cases; iter; iter = iter->next)
1599         {
1600           tc = iter->data;
1601           if (!strcmp (tc->name, test_path))
1602             return TRUE;
1603         }
1604     }
1605
1606   return FALSE;
1607 }
1608
1609 /**
1610  * g_test_case_exists:
1611  * @test_path: test case
1612  *
1613  * Tests if a test by the name of @test_path is registered.
1614  *
1615  * Returns: %TRUE if a test case named @test_name has been registered.
1616  *
1617  * Since: 2.36
1618  */
1619 gboolean
1620 g_test_case_exists (const char *test_path)
1621 {
1622   g_return_val_if_fail (test_path != NULL, FALSE);
1623   g_return_val_if_fail (g_path_is_absolute (test_path), FALSE);
1624
1625   return g_test_suite_case_exists (g_test_get_root (), test_path);
1626 }
1627
1628 /**
1629  * g_test_create_suite:
1630  * @suite_name: a name for the suite
1631  *
1632  * Create a new test suite with the name @suite_name.
1633  *
1634  * Returns: A newly allocated #GTestSuite instance.
1635  *
1636  * Since: 2.16
1637  */
1638 GTestSuite*
1639 g_test_create_suite (const char *suite_name)
1640 {
1641   GTestSuite *ts;
1642   g_return_val_if_fail (suite_name != NULL, NULL);
1643   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1644   g_return_val_if_fail (suite_name[0] != 0, NULL);
1645   ts = g_slice_new0 (GTestSuite);
1646   ts->name = g_strdup (suite_name);
1647   return ts;
1648 }
1649
1650 /**
1651  * g_test_suite_add:
1652  * @suite: a #GTestSuite
1653  * @test_case: a #GTestCase
1654  *
1655  * Adds @test_case to @suite.
1656  *
1657  * Since: 2.16
1658  */
1659 void
1660 g_test_suite_add (GTestSuite     *suite,
1661                   GTestCase      *test_case)
1662 {
1663   g_return_if_fail (suite != NULL);
1664   g_return_if_fail (test_case != NULL);
1665
1666   suite->cases = g_slist_prepend (suite->cases, test_case);
1667 }
1668
1669 /**
1670  * g_test_suite_add_suite:
1671  * @suite:       a #GTestSuite
1672  * @nestedsuite: another #GTestSuite
1673  *
1674  * Adds @nestedsuite to @suite.
1675  *
1676  * Since: 2.16
1677  */
1678 void
1679 g_test_suite_add_suite (GTestSuite     *suite,
1680                         GTestSuite     *nestedsuite)
1681 {
1682   g_return_if_fail (suite != NULL);
1683   g_return_if_fail (nestedsuite != NULL);
1684
1685   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1686 }
1687
1688 /**
1689  * g_test_queue_free:
1690  * @gfree_pointer: the pointer to be stored.
1691  *
1692  * Enqueue a pointer to be released with g_free() during the next
1693  * teardown phase. This is equivalent to calling g_test_queue_destroy()
1694  * with a destroy callback of g_free().
1695  *
1696  * Since: 2.16
1697  */
1698 void
1699 g_test_queue_free (gpointer gfree_pointer)
1700 {
1701   if (gfree_pointer)
1702     g_test_queue_destroy (g_free, gfree_pointer);
1703 }
1704
1705 /**
1706  * g_test_queue_destroy:
1707  * @destroy_func:       Destroy callback for teardown phase.
1708  * @destroy_data:       Destroy callback data.
1709  *
1710  * This function enqueus a callback @destroy_func to be executed
1711  * during the next test case teardown phase. This is most useful
1712  * to auto destruct allocted test resources at the end of a test run.
1713  * Resources are released in reverse queue order, that means enqueueing
1714  * callback A before callback B will cause B() to be called before
1715  * A() during teardown.
1716  *
1717  * Since: 2.16
1718  */
1719 void
1720 g_test_queue_destroy (GDestroyNotify destroy_func,
1721                       gpointer       destroy_data)
1722 {
1723   DestroyEntry *dentry;
1724
1725   g_return_if_fail (destroy_func != NULL);
1726
1727   dentry = g_slice_new0 (DestroyEntry);
1728   dentry->destroy_func = destroy_func;
1729   dentry->destroy_data = destroy_data;
1730   dentry->next = test_destroy_queue;
1731   test_destroy_queue = dentry;
1732 }
1733
1734 static gboolean
1735 test_case_run (GTestCase *tc)
1736 {
1737   gchar *old_name, *old_base;
1738   gboolean success = TRUE;
1739
1740   if (strchr (tc->name, ':'))
1741     {
1742       GSList *iter;
1743       gchar *full_name = g_strdup_printf ("%s/%s", test_run_name, tc->name);
1744       gboolean found = FALSE;
1745
1746       for (iter = test_paths; iter; iter = iter->next)
1747         {
1748           if (!strcmp (full_name, iter->data))
1749             {
1750               found = TRUE;
1751               break;
1752             }
1753         }
1754
1755       if (!found)
1756         {
1757           if (g_test_verbose())
1758             g_print ("GTest: skipping: %s/%s\n", test_run_name, tc->name);
1759           return TRUE;
1760         }
1761     } 
1762
1763   old_name = test_run_name;
1764   old_base = g_strdup (test_uri_base);
1765   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1766   if (++test_run_count <= test_skip_count)
1767     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1768   else if (test_run_list)
1769     {
1770       g_print ("%s\n", test_run_name);
1771       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1772     }
1773   else
1774     {
1775       GTimer *test_run_timer = g_timer_new();
1776       long double largs[3];
1777       void *fixture;
1778       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1779       test_run_forks = 0;
1780       test_run_success = TRUE;
1781       g_test_log_set_fatal_handler (NULL, NULL);
1782       g_timer_start (test_run_timer);
1783       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1784       test_run_seed (test_run_seedstr);
1785       if (tc->fixture_setup)
1786         tc->fixture_setup (fixture, tc->test_data);
1787       tc->fixture_test (fixture, tc->test_data);
1788       test_trap_clear();
1789       while (test_destroy_queue)
1790         {
1791           DestroyEntry *dentry = test_destroy_queue;
1792           test_destroy_queue = dentry->next;
1793           dentry->destroy_func (dentry->destroy_data);
1794           g_slice_free (DestroyEntry, dentry);
1795         }
1796       if (tc->fixture_teardown)
1797         tc->fixture_teardown (fixture, tc->test_data);
1798       if (tc->fixture_size)
1799         g_free (fixture);
1800       g_timer_stop (test_run_timer);
1801       success = test_run_success;
1802       test_run_success = FALSE;
1803       largs[0] = success ? 0 : 1; /* OK */
1804       largs[1] = test_run_forks;
1805       largs[2] = g_timer_elapsed (test_run_timer, NULL);
1806       g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1807       g_timer_destroy (test_run_timer);
1808     }
1809   g_free (test_run_name);
1810   test_run_name = old_name;
1811   g_free (test_uri_base);
1812   test_uri_base = old_base;
1813
1814   return success;
1815 }
1816
1817 static int
1818 g_test_run_suite_internal (GTestSuite *suite,
1819                            const char *path)
1820 {
1821   guint n_bad = 0, l;
1822   gchar *rest, *old_name = test_run_name;
1823   GSList *slist, *reversed;
1824
1825   g_return_val_if_fail (suite != NULL, -1);
1826
1827   while (path[0] == '/')
1828     path++;
1829   l = strlen (path);
1830   rest = strchr (path, '/');
1831   l = rest ? MIN (l, rest - path) : l;
1832   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1833   reversed = g_slist_reverse (g_slist_copy (suite->cases));
1834   for (slist = reversed; slist; slist = slist->next)
1835     {
1836       GTestCase *tc = slist->data;
1837       guint n = l ? strlen (tc->name) : 0;
1838       if (l == n && strncmp (path, tc->name, n) == 0)
1839         {
1840           if (!test_case_run (tc))
1841             n_bad++;
1842         }
1843     }
1844   g_slist_free (reversed);
1845   reversed = g_slist_reverse (g_slist_copy (suite->suites));
1846   for (slist = reversed; slist; slist = slist->next)
1847     {
1848       GTestSuite *ts = slist->data;
1849       guint n = l ? strlen (ts->name) : 0;
1850       if (l == n && strncmp (path, ts->name, n) == 0)
1851         n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1852     }
1853   g_slist_free (reversed);
1854   g_free (test_run_name);
1855   test_run_name = old_name;
1856
1857   return n_bad;
1858 }
1859
1860 static gpointer
1861 test_timeout_thread (gpointer user_data)
1862 {
1863   g_usleep (test_timeout);
1864 #ifdef G_OS_WIN32
1865   TerminateProcess (GetCurrentProcess (), G_TEST_STATUS_TIMED_OUT);
1866 #else
1867   kill (getpid (), SIGALRM);
1868 #endif
1869
1870   return NULL;
1871 }
1872
1873 /**
1874  * g_test_run_suite:
1875  * @suite: a #GTestSuite
1876  *
1877  * Execute the tests within @suite and all nested #GTestSuites.
1878  * The test suites to be executed are filtered according to
1879  * test path arguments (-p <replaceable>testpath</replaceable>) 
1880  * as parsed by g_test_init().
1881  * g_test_run_suite() or g_test_run() may only be called once
1882  * in a program.
1883  *
1884  * Returns: 0 on success
1885  *
1886  * Since: 2.16
1887  */
1888 int
1889 g_test_run_suite (GTestSuite *suite)
1890 {
1891   GSList *my_test_paths;
1892   guint n_bad = 0;
1893
1894   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1895   g_return_val_if_fail (g_test_run_once == TRUE, -1);
1896
1897   g_test_run_once = FALSE;
1898
1899   if (test_timeout)
1900     {
1901       GThread *thread;
1902
1903       thread = g_thread_new ("GTestTimeout", test_timeout_thread, NULL);
1904       g_thread_unref (thread);
1905     }
1906
1907   if (test_paths)
1908     my_test_paths = g_slist_copy (test_paths);
1909   else
1910     my_test_paths = g_slist_prepend (NULL, "");
1911
1912   while (my_test_paths)
1913     {
1914       const char *rest, *path = my_test_paths->data;
1915       guint l, n = strlen (suite->name);
1916       my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
1917       while (path[0] == '/')
1918         path++;
1919       if (!n) /* root suite, run unconditionally */
1920         {
1921           n_bad += g_test_run_suite_internal (suite, path);
1922           continue;
1923         }
1924       /* regular suite, match path */
1925       rest = strchr (path, '/');
1926       l = strlen (path);
1927       l = rest ? MIN (l, rest - path) : l;
1928       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1929         n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1930     }
1931
1932   return n_bad;
1933 }
1934
1935 static void
1936 gtest_default_log_handler (const gchar    *log_domain,
1937                            GLogLevelFlags  log_level,
1938                            const gchar    *message,
1939                            gpointer        unused_data)
1940 {
1941   const gchar *strv[16];
1942   gboolean fatal = FALSE;
1943   gchar *msg;
1944   guint i = 0;
1945
1946   if (log_domain)
1947     {
1948       strv[i++] = log_domain;
1949       strv[i++] = "-";
1950     }
1951   if (log_level & G_LOG_FLAG_FATAL)
1952     {
1953       strv[i++] = "FATAL-";
1954       fatal = TRUE;
1955     }
1956   if (log_level & G_LOG_FLAG_RECURSION)
1957     strv[i++] = "RECURSIVE-";
1958   if (log_level & G_LOG_LEVEL_ERROR)
1959     strv[i++] = "ERROR";
1960   if (log_level & G_LOG_LEVEL_CRITICAL)
1961     strv[i++] = "CRITICAL";
1962   if (log_level & G_LOG_LEVEL_WARNING)
1963     strv[i++] = "WARNING";
1964   if (log_level & G_LOG_LEVEL_MESSAGE)
1965     strv[i++] = "MESSAGE";
1966   if (log_level & G_LOG_LEVEL_INFO)
1967     strv[i++] = "INFO";
1968   if (log_level & G_LOG_LEVEL_DEBUG)
1969     strv[i++] = "DEBUG";
1970   strv[i++] = ": ";
1971   strv[i++] = message;
1972   strv[i++] = NULL;
1973
1974   msg = g_strjoinv ("", (gchar**) strv);
1975   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1976   g_log_default_handler (log_domain, log_level, message, unused_data);
1977
1978   g_free (msg);
1979 }
1980
1981 void
1982 g_assertion_message (const char     *domain,
1983                      const char     *file,
1984                      int             line,
1985                      const char     *func,
1986                      const char     *message)
1987 {
1988   char lstr[32];
1989   char *s;
1990
1991   if (!message)
1992     message = "code should not be reached";
1993   g_snprintf (lstr, 32, "%d", line);
1994   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1995                    "ERROR:", file, ":", lstr, ":",
1996                    func, func[0] ? ":" : "",
1997                    " ", message, NULL);
1998   g_printerr ("**\n%s\n", s);
1999
2000   /* store assertion message in global variable, so that it can be found in a
2001    * core dump */
2002   if (__glib_assert_msg != NULL)
2003       /* free the old one */
2004       free (__glib_assert_msg);
2005   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2006   strcpy (__glib_assert_msg, s);
2007
2008   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2009   g_free (s);
2010   abort();
2011 }
2012
2013 void
2014 g_assertion_message_expr (const char     *domain,
2015                           const char     *file,
2016                           int             line,
2017                           const char     *func,
2018                           const char     *expr)
2019 {
2020   char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2021   g_assertion_message (domain, file, line, func, s);
2022   g_free (s);
2023 }
2024
2025 void
2026 g_assertion_message_cmpnum (const char     *domain,
2027                             const char     *file,
2028                             int             line,
2029                             const char     *func,
2030                             const char     *expr,
2031                             long double     arg1,
2032                             const char     *cmp,
2033                             long double     arg2,
2034                             char            numtype)
2035 {
2036   char *s = NULL;
2037
2038   switch (numtype)
2039     {
2040     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%" G_GINT64_MODIFIER "i %s %" G_GINT64_MODIFIER "i)", expr, (gint64) arg1, cmp, (gint64) arg2); break;
2041     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;
2042     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2043       /* ideally use: floats=%.7g double=%.17g */
2044     }
2045   g_assertion_message (domain, file, line, func, s);
2046   g_free (s);
2047 }
2048
2049 void
2050 g_assertion_message_cmpstr (const char     *domain,
2051                             const char     *file,
2052                             int             line,
2053                             const char     *func,
2054                             const char     *expr,
2055                             const char     *arg1,
2056                             const char     *cmp,
2057                             const char     *arg2)
2058 {
2059   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2060   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2061   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2062   g_free (t1);
2063   g_free (t2);
2064   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2065   g_free (a1);
2066   g_free (a2);
2067   g_assertion_message (domain, file, line, func, s);
2068   g_free (s);
2069 }
2070
2071 void
2072 g_assertion_message_error (const char     *domain,
2073                            const char     *file,
2074                            int             line,
2075                            const char     *func,
2076                            const char     *expr,
2077                            const GError   *error,
2078                            GQuark          error_domain,
2079                            int             error_code)
2080 {
2081   GString *gstring;
2082
2083   /* This is used by both g_assert_error() and g_assert_no_error(), so there
2084    * are three cases: expected an error but got the wrong error, expected
2085    * an error but got no error, and expected no error but got an error.
2086    */
2087
2088   gstring = g_string_new ("assertion failed ");
2089   if (error_domain)
2090       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2091                               g_quark_to_string (error_domain), error_code);
2092   else
2093     g_string_append_printf (gstring, "(%s == NULL): ", expr);
2094
2095   if (error)
2096       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2097                               g_quark_to_string (error->domain), error->code);
2098   else
2099     g_string_append_printf (gstring, "%s is NULL", expr);
2100
2101   g_assertion_message (domain, file, line, func, gstring->str);
2102   g_string_free (gstring, TRUE);
2103 }
2104
2105 /**
2106  * g_strcmp0:
2107  * @str1: (allow-none): a C string or %NULL
2108  * @str2: (allow-none): another C string or %NULL
2109  *
2110  * Compares @str1 and @str2 like strcmp(). Handles %NULL
2111  * gracefully by sorting it before non-%NULL strings.
2112  * Comparing two %NULL pointers returns 0.
2113  *
2114  * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2115  *
2116  * Since: 2.16
2117  */
2118 int
2119 g_strcmp0 (const char     *str1,
2120            const char     *str2)
2121 {
2122   if (!str1)
2123     return -(str1 != str2);
2124   if (!str2)
2125     return str1 != str2;
2126   return strcmp (str1, str2);
2127 }
2128
2129 #ifdef G_OS_UNIX
2130 static int /* 0 on success */
2131 kill_child (int  pid,
2132             int *status,
2133             int  patience)
2134 {
2135   int wr;
2136   if (patience >= 3)    /* try graceful reap */
2137     {
2138       if (waitpid (pid, status, WNOHANG) > 0)
2139         return 0;
2140     }
2141   if (patience >= 2)    /* try SIGHUP */
2142     {
2143       kill (pid, SIGHUP);
2144       if (waitpid (pid, status, WNOHANG) > 0)
2145         return 0;
2146       g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
2147       if (waitpid (pid, status, WNOHANG) > 0)
2148         return 0;
2149       g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
2150       if (waitpid (pid, status, WNOHANG) > 0)
2151         return 0;
2152       g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
2153       if (waitpid (pid, status, WNOHANG) > 0)
2154         return 0;
2155     }
2156   if (patience >= 1)    /* try SIGTERM */
2157     {
2158       kill (pid, SIGTERM);
2159       if (waitpid (pid, status, WNOHANG) > 0)
2160         return 0;
2161       g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
2162       if (waitpid (pid, status, WNOHANG) > 0)
2163         return 0;
2164       g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
2165       if (waitpid (pid, status, WNOHANG) > 0)
2166         return 0;
2167     }
2168   /* finish it off */
2169   kill (pid, SIGKILL);
2170   do
2171     wr = waitpid (pid, status, 0);
2172   while (wr < 0 && errno == EINTR);
2173   return wr;
2174 }
2175 #endif
2176
2177 static inline int
2178 g_string_must_read (GString *gstring,
2179                     int      fd)
2180 {
2181 #define STRING_BUFFER_SIZE     4096
2182   char buf[STRING_BUFFER_SIZE];
2183   gssize bytes;
2184  again:
2185   bytes = read (fd, buf, sizeof (buf));
2186   if (bytes == 0)
2187     return 0; /* EOF, calling this function assumes data is available */
2188   else if (bytes > 0)
2189     {
2190       g_string_append_len (gstring, buf, bytes);
2191       return 1;
2192     }
2193   else if (bytes < 0 && errno == EINTR)
2194     goto again;
2195   else /* bytes < 0 */
2196     {
2197       if (test_trap_last_subprocess)
2198         g_warning ("failed to read() from child process (%s): %s", test_trap_last_subprocess, g_strerror (errno));
2199       else
2200         g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2201       return 1; /* ignore error after warning */
2202     }
2203 }
2204
2205 static inline void
2206 g_string_write_out (GString *gstring,
2207                     int      outfd,
2208                     int     *stringpos)
2209 {
2210   if (*stringpos < gstring->len)
2211     {
2212       int r;
2213       do
2214         r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2215       while (r < 0 && errno == EINTR);
2216       *stringpos += MAX (r, 0);
2217     }
2218 }
2219
2220 static void
2221 test_trap_clear (void)
2222 {
2223   test_trap_last_status = 0;
2224   test_trap_last_pid = 0;
2225   g_free (test_trap_last_subprocess);
2226   test_trap_last_subprocess = NULL;
2227   g_free (test_trap_last_stdout);
2228   test_trap_last_stdout = NULL;
2229   g_free (test_trap_last_stderr);
2230   test_trap_last_stderr = NULL;
2231 }
2232
2233 #ifdef G_OS_UNIX
2234
2235 static int
2236 sane_dup2 (int fd1,
2237            int fd2)
2238 {
2239   int ret;
2240   do
2241     ret = dup2 (fd1, fd2);
2242   while (ret < 0 && errno == EINTR);
2243   return ret;
2244 }
2245
2246 static guint64
2247 test_time_stamp (void)
2248 {
2249   GTimeVal tv;
2250   guint64 stamp;
2251   g_get_current_time (&tv);
2252   stamp = tv.tv_sec;
2253   stamp = stamp * 1000000 + tv.tv_usec;
2254   return stamp;
2255 }
2256
2257 #endif
2258
2259 /**
2260  * g_test_trap_fork:
2261  * @usec_timeout:    Timeout for the forked test in micro seconds.
2262  * @test_trap_flags: Flags to modify forking behaviour.
2263  *
2264  * Fork the current test program to execute a test case that might
2265  * not return or that might abort.
2266  *
2267  * If @usec_timeout is non-0, the forked test case is aborted and
2268  * considered failing if its run time exceeds it.
2269  *
2270  * The forking behavior can be configured with the #GTestTrapFlags flags.
2271  *
2272  * In the following example, the test code forks, the forked child
2273  * process produces some sample output and exits successfully.
2274  * The forking parent process then asserts successful child program
2275  * termination and validates child program outputs.
2276  *
2277  * |[
2278  *   static void
2279  *   test_fork_patterns (void)
2280  *   {
2281  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2282  *       {
2283  *         g_print ("some stdout text: somagic17\n");
2284  *         g_printerr ("some stderr text: semagic43\n");
2285  *         exit (0); /&ast; successful test run &ast;/
2286  *       }
2287  *     g_test_trap_assert_passed ();
2288  *     g_test_trap_assert_stdout ("*somagic17*");
2289  *     g_test_trap_assert_stderr ("*semagic43*");
2290  *   }
2291  * ]|
2292  *
2293  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2294  *
2295  * Since: 2.16
2296  *
2297  * Deprecated: This function is implemented only on Unix platforms,
2298  * and is not always reliable due to problems inherent in
2299  * fork-without-exec. Use g_test_trap_subprocess() instead.
2300  */
2301 gboolean
2302 g_test_trap_fork (guint64        usec_timeout,
2303                   GTestTrapFlags test_trap_flags)
2304 {
2305 #ifdef G_OS_UNIX
2306   gboolean pass_on_forked_log = FALSE;
2307   int stdout_pipe[2] = { -1, -1 };
2308   int stderr_pipe[2] = { -1, -1 };
2309   int stdtst_pipe[2] = { -1, -1 };
2310   test_trap_clear();
2311   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2312     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2313   signal (SIGCHLD, SIG_DFL);
2314   test_trap_last_pid = fork ();
2315   if (test_trap_last_pid < 0)
2316     g_error ("failed to fork test program: %s", g_strerror (errno));
2317   if (test_trap_last_pid == 0)  /* child */
2318     {
2319       int fd0 = -1;
2320       close (stdout_pipe[0]);
2321       close (stderr_pipe[0]);
2322       close (stdtst_pipe[0]);
2323       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2324         fd0 = g_open ("/dev/null", O_RDONLY, 0);
2325       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2326         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2327       if (fd0 >= 3)
2328         close (fd0);
2329       if (stdout_pipe[1] >= 3)
2330         close (stdout_pipe[1]);
2331       if (stderr_pipe[1] >= 3)
2332         close (stderr_pipe[1]);
2333       test_log_fd = stdtst_pipe[1];
2334       return TRUE;
2335     }
2336   else                          /* parent */
2337     {
2338       GString *sout = g_string_new (NULL);
2339       GString *serr = g_string_new (NULL);
2340       guint64 sstamp;
2341       int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2342       test_run_forks++;
2343       close (stdout_pipe[1]);
2344       close (stderr_pipe[1]);
2345       close (stdtst_pipe[1]);
2346       sstamp = test_time_stamp();
2347       /* read data until we get EOF on all pipes */
2348       while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2349         {
2350           fd_set fds;
2351           struct timeval tv;
2352           int ret;
2353           FD_ZERO (&fds);
2354           if (stdout_pipe[0] >= 0)
2355             FD_SET (stdout_pipe[0], &fds);
2356           if (stderr_pipe[0] >= 0)
2357             FD_SET (stderr_pipe[0], &fds);
2358           if (stdtst_pipe[0] >= 0)
2359             FD_SET (stdtst_pipe[0], &fds);
2360           tv.tv_sec = 0;
2361           tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2362           ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2363           if (ret < 0 && errno != EINTR)
2364             {
2365               g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2366               break;
2367             }
2368           if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2369               g_string_must_read (sout, stdout_pipe[0]) == 0)
2370             {
2371               close (stdout_pipe[0]);
2372               stdout_pipe[0] = -1;
2373             }
2374           if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2375               g_string_must_read (serr, stderr_pipe[0]) == 0)
2376             {
2377               close (stderr_pipe[0]);
2378               stderr_pipe[0] = -1;
2379             }
2380           if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2381             {
2382               guint8 buffer[4096];
2383               gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2384               if (r > 0 && test_log_fd > 0)
2385                 do
2386                   l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2387                 while (l < 0 && errno == EINTR);
2388               if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2389                 {
2390                   close (stdtst_pipe[0]);
2391                   stdtst_pipe[0] = -1;
2392                 }
2393             }
2394           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2395             g_string_write_out (sout, 1, &soutpos);
2396           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2397             g_string_write_out (serr, 2, &serrpos);
2398           if (usec_timeout)
2399             {
2400               guint64 nstamp = test_time_stamp();
2401               int status = 0;
2402               sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2403               if (usec_timeout < nstamp - sstamp)
2404                 {
2405                   /* timeout reached, need to abort the child now */
2406                   kill_child (test_trap_last_pid, &status, 3);
2407                   test_trap_last_status = G_TEST_STATUS_TIMED_OUT;
2408                   if (0 && WIFSIGNALED (status))
2409                     g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2410                   need_wait = FALSE;
2411                   break;
2412                 }
2413             }
2414         }
2415       if (stdout_pipe[0] != -1)
2416         close (stdout_pipe[0]);
2417       if (stderr_pipe[0] != -1)
2418         close (stderr_pipe[0]);
2419       if (stdtst_pipe[0] != -1)
2420         close (stdtst_pipe[0]);
2421       if (need_wait)
2422         {
2423           int status = 0;
2424           do
2425             wr = waitpid (test_trap_last_pid, &status, 0);
2426           while (wr < 0 && errno == EINTR);
2427           if (WIFEXITED (status)) /* normal exit */
2428             test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2429           else if (WIFSIGNALED (status))
2430             test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2431           else /* WCOREDUMP (status) */
2432             test_trap_last_status = 512; /* coredump */
2433         }
2434       test_trap_last_stdout = g_string_free (sout, FALSE);
2435       test_trap_last_stderr = g_string_free (serr, FALSE);
2436       return FALSE;
2437     }
2438 #else
2439   g_message ("Not implemented: g_test_trap_fork");
2440
2441   return FALSE;
2442 #endif
2443 }
2444
2445 /**
2446  * g_test_trap_subprocess:
2447  * @test_name:       Test to run in a subprocess
2448  * @usec_timeout:    Timeout for the subprocess test in micro seconds.
2449  * @test_trap_flags: Flags to modify subprocess behaviour.
2450  *
2451  * Respawns the test program to run only @test_name in a subprocess.
2452  * This can be used for a test case that might not return or that
2453  * might abort. @test_name will normally be the name of the parent
2454  * test, followed by a "<literal>:</literal>" and a name for the
2455  * specific subtest; tests with names of this form will automatically
2456  * be skipped in the parent process.
2457  *
2458  * If @usec_timeout is non-0, the test subprocess is aborted and
2459  * considered failing if its run time exceeds it.
2460  *
2461  * The subprocess behavior can be configured with the #GTestTrapFlags
2462  * flags.
2463  *
2464  * You can use methods such as g_test_trap_assert_passed(),
2465  * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to check
2466  * the results of the subprocess.
2467  *
2468  * If your <literal>main ()</literal> needs to behave differently in
2469  * the subprocess, you can call g_test_subprocess() (after calling
2470  * test_init()) to see whether you are in a subprocess.
2471  *
2472  * The following example tests that calling
2473  * <literal>my_object_new(1000000)</literal> will abort with an error
2474  * message.
2475  *
2476  * |[
2477  *   static void
2478  *   test_create_large_object_subprocess (void)
2479  *   {
2480  *     my_object_new (1000000);
2481  *     g_assert_not_reached ();
2482  *   }
2483  *
2484  *   static void
2485  *   test_create_large_object (void)
2486  *   {
2487  *     g_test_trap_subprocess ("/myobject/create_large_object:subprocess", 0,
2488  *                             G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR);
2489  *     g_test_trap_assert_failed ();
2490  *     g_test_trap_assert_stderr ("*ERROR*too large*");
2491  *   }
2492  *
2493  *   int
2494  *   main (int argc, char **argv)
2495  *   {
2496  *     g_test_init (&argc, &argv, NULL);
2497  *
2498  *     g_test_add_func ("/myobject/create_large_object",
2499  *                      test_create_large_object);
2500  *     /&ast; Because of the ':' in the name, this test will not be run
2501  *      &ast; by the g_test_run () call below.
2502  *      &ast;/
2503  *     g_test_add_func ("/myobject/create_large_object:subprocess",
2504  *                      test_create_large_object_subprocess);
2505  *
2506  *     return g_test_run ();
2507  *   }
2508  * ]|
2509  *
2510  * Since: 2.36
2511  */
2512 #undef g_test_trap_subprocess
2513 void
2514 g_test_trap_subprocess (const char     *test_path,
2515                         guint64         usec_timeout,
2516                         GTestTrapFlags  test_trap_flags)
2517 {
2518   GError *error = NULL;
2519   GPtrArray *argv;
2520   char **stdout_p, **stderr_p;
2521   GSpawnFlags flags;
2522   int status;
2523
2524   if (g_test_verbose())
2525     g_print ("GTest: subprocess: %s\n", test_path);
2526
2527   test_trap_clear ();
2528   test_trap_last_subprocess = g_strdup (test_path);
2529
2530   argv = g_ptr_array_new ();
2531   g_ptr_array_add (argv, test_argv0);
2532   g_ptr_array_add (argv, "-q");
2533   g_ptr_array_add (argv, "-p");
2534   g_ptr_array_add (argv, (char *)test_path);
2535   g_ptr_array_add (argv, "--GTestSubprocess");
2536   if (test_log_fd != -1)
2537     {
2538       char log_fd_buf[128];
2539
2540       g_ptr_array_add (argv, "--GTestLogFD");
2541       g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2542       g_ptr_array_add (argv, log_fd_buf);
2543     }
2544   if (usec_timeout != 0)
2545     {
2546       char timeout_buf[128];
2547
2548       g_ptr_array_add (argv, "--GTestTimeout");
2549       g_snprintf (timeout_buf, sizeof (timeout_buf), "%" G_GUINT64_FORMAT, usec_timeout);
2550       g_ptr_array_add (argv, timeout_buf);
2551     }
2552   g_ptr_array_add (argv, NULL);
2553
2554   if (test_trap_flags & G_TEST_TRAP_INHERIT_STDIN)
2555     flags = G_SPAWN_CHILD_INHERITS_STDIN;
2556   else
2557     flags = 0;
2558   if (test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT)
2559     stdout_p = &test_trap_last_stdout;
2560   else
2561     stdout_p = NULL;
2562   if (test_trap_flags & G_TEST_TRAP_SILENCE_STDERR)
2563     stderr_p = &test_trap_last_stderr;
2564   else
2565     stderr_p = NULL;
2566
2567   if (!g_spawn_sync (test_initial_cwd,
2568                      (char **)argv->pdata,
2569                      NULL, flags,
2570                      NULL, NULL,
2571                      stdout_p, stderr_p,
2572                      &status, &error))
2573     {
2574       g_error ("g_test_trap_subprocess() failed: %s\n",
2575                error->message);
2576     }
2577   g_ptr_array_free (argv, TRUE);
2578
2579 #ifdef G_OS_UNIX
2580   if (WIFEXITED (status))
2581     test_trap_last_status = WEXITSTATUS (status);
2582   else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2583     test_trap_last_status = G_TEST_STATUS_TIMED_OUT;
2584   else
2585     test_trap_last_status = -1;
2586 #else
2587     test_trap_last_status = status;
2588 #endif
2589 }
2590
2591 /**
2592  * g_test_subprocess:
2593  *
2594  * Returns %TRUE (after g_test_init() has been called) if the test
2595  * program is running under g_test_trap_subprocess().
2596  *
2597  * Returns: %TRUE if the test program is running under
2598  * g_test_trap_subprocess().
2599  *
2600  * Since: 2.36
2601  */
2602 gboolean
2603 g_test_subprocess (void)
2604 {
2605   return test_in_subprocess;
2606 }
2607
2608 /**
2609  * g_test_trap_has_passed:
2610  *
2611  * Check the result of the last g_test_trap_subprocess() call.
2612  *
2613  * Returns: %TRUE if the last test subprocess terminated successfully.
2614  *
2615  * Since: 2.16
2616  */
2617 gboolean
2618 g_test_trap_has_passed (void)
2619 {
2620   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2621 }
2622
2623 /**
2624  * g_test_trap_reached_timeout:
2625  *
2626  * Check the result of the last g_test_trap_subprocess() call.
2627  *
2628  * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2629  *
2630  * Since: 2.16
2631  */
2632 gboolean
2633 g_test_trap_reached_timeout (void)
2634 {
2635   return test_trap_last_status != G_TEST_STATUS_TIMED_OUT;
2636 }
2637
2638 void
2639 g_test_trap_assertions (const char     *domain,
2640                         const char     *file,
2641                         int             line,
2642                         const char     *func,
2643                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2644                         const char     *pattern)
2645 {
2646   gboolean must_pass = assertion_flags == 0;
2647   gboolean must_fail = assertion_flags == 1;
2648   gboolean match_result = 0 == (assertion_flags & 1);
2649   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2650   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2651   const char *match_error = match_result ? "failed to match" : "contains invalid match";
2652   char *process_id;
2653
2654   if (test_trap_last_pid != 0)
2655     process_id = g_strdup_printf ("%d", test_trap_last_pid);
2656   else if (test_trap_last_subprocess != NULL)
2657     process_id = g_strdup (test_trap_last_subprocess);
2658   else
2659     g_error ("g_test_trap_ assertion with no trapped test");
2660
2661   if (must_pass && !g_test_trap_has_passed())
2662     {
2663       char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2664       g_assertion_message (domain, file, line, func, msg);
2665       g_free (msg);
2666     }
2667   if (must_fail && g_test_trap_has_passed())
2668     {
2669       char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
2670       g_assertion_message (domain, file, line, func, msg);
2671       g_free (msg);
2672     }
2673   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2674     {
2675       char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
2676       g_assertion_message (domain, file, line, func, msg);
2677       g_free (msg);
2678     }
2679   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2680     {
2681       char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
2682       g_assertion_message (domain, file, line, func, msg);
2683       g_free (msg);
2684     }
2685 }
2686
2687 static void
2688 gstring_overwrite_int (GString *gstring,
2689                        guint    pos,
2690                        guint32  vuint)
2691 {
2692   vuint = g_htonl (vuint);
2693   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2694 }
2695
2696 static void
2697 gstring_append_int (GString *gstring,
2698                     guint32  vuint)
2699 {
2700   vuint = g_htonl (vuint);
2701   g_string_append_len (gstring, (const gchar*) &vuint, 4);
2702 }
2703
2704 static void
2705 gstring_append_double (GString *gstring,
2706                        double   vdouble)
2707 {
2708   union { double vdouble; guint64 vuint64; } u;
2709   u.vdouble = vdouble;
2710   u.vuint64 = GUINT64_TO_BE (u.vuint64);
2711   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2712 }
2713
2714 static guint8*
2715 g_test_log_dump (GTestLogMsg *msg,
2716                  guint       *len)
2717 {
2718   GString *gstring = g_string_sized_new (1024);
2719   guint ui;
2720   gstring_append_int (gstring, 0);              /* message length */
2721   gstring_append_int (gstring, msg->log_type);
2722   gstring_append_int (gstring, msg->n_strings);
2723   gstring_append_int (gstring, msg->n_nums);
2724   gstring_append_int (gstring, 0);      /* reserved */
2725   for (ui = 0; ui < msg->n_strings; ui++)
2726     {
2727       guint l = strlen (msg->strings[ui]);
2728       gstring_append_int (gstring, l);
2729       g_string_append_len (gstring, msg->strings[ui], l);
2730     }
2731   for (ui = 0; ui < msg->n_nums; ui++)
2732     gstring_append_double (gstring, msg->nums[ui]);
2733   *len = gstring->len;
2734   gstring_overwrite_int (gstring, 0, *len);     /* message length */
2735   return (guint8*) g_string_free (gstring, FALSE);
2736 }
2737
2738 static inline long double
2739 net_double (const gchar **ipointer)
2740 {
2741   union { guint64 vuint64; double vdouble; } u;
2742   guint64 aligned_int64;
2743   memcpy (&aligned_int64, *ipointer, 8);
2744   *ipointer += 8;
2745   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2746   return u.vdouble;
2747 }
2748
2749 static inline guint32
2750 net_int (const gchar **ipointer)
2751 {
2752   guint32 aligned_int;
2753   memcpy (&aligned_int, *ipointer, 4);
2754   *ipointer += 4;
2755   return g_ntohl (aligned_int);
2756 }
2757
2758 static gboolean
2759 g_test_log_extract (GTestLogBuffer *tbuffer)
2760 {
2761   const gchar *p = tbuffer->data->str;
2762   GTestLogMsg msg;
2763   guint mlength;
2764   if (tbuffer->data->len < 4 * 5)
2765     return FALSE;
2766   mlength = net_int (&p);
2767   if (tbuffer->data->len < mlength)
2768     return FALSE;
2769   msg.log_type = net_int (&p);
2770   msg.n_strings = net_int (&p);
2771   msg.n_nums = net_int (&p);
2772   if (net_int (&p) == 0)
2773     {
2774       guint ui;
2775       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2776       msg.nums = g_new0 (long double, msg.n_nums);
2777       for (ui = 0; ui < msg.n_strings; ui++)
2778         {
2779           guint sl = net_int (&p);
2780           msg.strings[ui] = g_strndup (p, sl);
2781           p += sl;
2782         }
2783       for (ui = 0; ui < msg.n_nums; ui++)
2784         msg.nums[ui] = net_double (&p);
2785       if (p <= tbuffer->data->str + mlength)
2786         {
2787           g_string_erase (tbuffer->data, 0, mlength);
2788           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2789           return TRUE;
2790         }
2791     }
2792   g_free (msg.nums);
2793   g_strfreev (msg.strings);
2794   g_error ("corrupt log stream from test program");
2795   return FALSE;
2796 }
2797
2798 /**
2799  * g_test_log_buffer_new:
2800  *
2801  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2802  */
2803 GTestLogBuffer*
2804 g_test_log_buffer_new (void)
2805 {
2806   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2807   tb->data = g_string_sized_new (1024);
2808   return tb;
2809 }
2810
2811 /**
2812  * g_test_log_buffer_free:
2813  *
2814  * Internal function for gtester to free test log messages, no ABI guarantees provided.
2815  */
2816 void
2817 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2818 {
2819   g_return_if_fail (tbuffer != NULL);
2820   while (tbuffer->msgs)
2821     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2822   g_string_free (tbuffer->data, TRUE);
2823   g_free (tbuffer);
2824 }
2825
2826 /**
2827  * g_test_log_buffer_push:
2828  *
2829  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2830  */
2831 void
2832 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2833                         guint           n_bytes,
2834                         const guint8   *bytes)
2835 {
2836   g_return_if_fail (tbuffer != NULL);
2837   if (n_bytes)
2838     {
2839       gboolean more_messages;
2840       g_return_if_fail (bytes != NULL);
2841       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2842       do
2843         more_messages = g_test_log_extract (tbuffer);
2844       while (more_messages);
2845     }
2846 }
2847
2848 /**
2849  * g_test_log_buffer_pop:
2850  *
2851  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2852  */
2853 GTestLogMsg*
2854 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2855 {
2856   GTestLogMsg *msg = NULL;
2857   g_return_val_if_fail (tbuffer != NULL, NULL);
2858   if (tbuffer->msgs)
2859     {
2860       GSList *slist = g_slist_last (tbuffer->msgs);
2861       msg = slist->data;
2862       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2863     }
2864   return msg;
2865 }
2866
2867 /**
2868  * g_test_log_msg_free:
2869  *
2870  * Internal function for gtester to free test log messages, no ABI guarantees provided.
2871  */
2872 void
2873 g_test_log_msg_free (GTestLogMsg *tmsg)
2874 {
2875   g_return_if_fail (tmsg != NULL);
2876   g_strfreev (tmsg->strings);
2877   g_free (tmsg->nums);
2878   g_free (tmsg);
2879 }
2880
2881 /* --- macros docs START --- */
2882 /**
2883  * g_test_add:
2884  * @testpath:  The test path for a new test case.
2885  * @Fixture:   The type of a fixture data structure.
2886  * @tdata:     Data argument for the test functions.
2887  * @fsetup:    The function to set up the fixture data.
2888  * @ftest:     The actual test function.
2889  * @fteardown: The function to tear down the fixture data.
2890  *
2891  * Hook up a new test case at @testpath, similar to g_test_add_func().
2892  * A fixture data structure with setup and teardown function may be provided
2893  * though, similar to g_test_create_case().
2894  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2895  * fteardown() callbacks can expect a @Fixture pointer as first argument in
2896  * a type safe manner.
2897  *
2898  * Since: 2.16
2899  **/
2900 /* --- macros docs END --- */