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