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